Programs & Examples On #Modularization

0

Can I escape a double quote in a verbatim string literal?

For adding some more information, your example will work without the @ symbol (it prevents escaping with \), this way:

string foo = "this \"word\" is escaped!";

It will work both ways but I prefer the double-quote style for it to be easier working, for example, with filenames (with lots of \ in the string).

How to set column widths to a jQuery datatable?

In java script calculate width using following code

var scrollX = $(window).width()*58/100;
var oTable = $('#reqAllRequestsTable').dataTable({
    "sScrollX": scrollX
    } );

How to increase dbms_output buffer?

When buffer size gets full. There are several options you can try:

1) Increase the size of the DBMS_OUTPUT buffer to 1,000,000

2) Try filtering the data written to the buffer - possibly there is a loop that writes to DBMS_OUTPUT and you do not need this data.

3) Call ENABLE at various checkpoints within your code. Each call will clear the buffer.

DBMS_OUTPUT.ENABLE(NULL) will default to 20000 for backwards compatibility Oracle documentation on dbms_output

You can also create your custom output display.something like below snippets

create or replace procedure cust_output(input_string in varchar2 )
is 

   out_string_in long default in_string; 
   string_lenth number; 
   loop_count number default 0; 

begin 

   str_len := length(out_string_in);

   while loop_count < str_len
   loop 
      dbms_output.put_line( substr( out_string_in, loop_count +1, 255 ) ); 
      loop_count := loop_count +255; 
   end loop; 
end;

Link -Ref :Alternative to dbms_output.putline @ By: Alexander

Output (echo/print) everything from a PHP Array

 //@parram $data-array,$d-if true then die by default it is false
 //@author Your name

 function p($data,$d = false){

     echo "<pre>"; 
         print_r($data);
     echo "</pre>"; 

     if($d == TRUE){
        die();
     } 
} // END OF FUNCTION

Use this function every time whenver you need to string or array it will wroks just GREAT.
There are 2 Patameters
1.$data - It can be Array or String
2.$d - By Default it is FALSE but if you set to true then it will execute die() function

In your case you can use in this way....

while($row = mysql_fetch_array($result)){
    p($row); // Use this function if you use above function in your page.
}

How to get all properties values of a JavaScript Object (without knowing the keys)?

For those early adapting people on the CofeeScript era, here's another equivalent for it.

val for key,val of objects

Which may be better than this because the objects can be reduced to be typed again and decreased readability.

objects[key] for key of objects

Best way to get user GPS location in background in Android

Grant required permission ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION after start service

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.location.LocationListener;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResolvableApiException;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResponse;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.android.gms.location.SettingsClient;
import com.google.android.gms.tasks.OnCanceledListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;

import java.util.concurrent.TimeUnit;

/**
 * Created by Ketan Ramani on 05/11/18.
 */

public class BackgroundLocationUpdateService extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

    /* Declare in manifest
    <service android:name=".BackgroundLocationUpdateService"/>
    */

    private final String TAG = "BackgroundLocationUpdateService";
    private final String TAG_LOCATION = "TAG_LOCATION";
    private Context context;
    private boolean stopService = false;

    /* For Google Fused API */
    protected GoogleApiClient mGoogleApiClient;
    protected LocationSettingsRequest mLocationSettingsRequest;
    private String latitude = "0.0", longitude = "0.0";
    private FusedLocationProviderClient mFusedLocationClient;
    private SettingsClient mSettingsClient;
    private LocationCallback mLocationCallback;
    private LocationRequest mLocationRequest;
    private Location mCurrentLocation;
    /* For Google Fused API */

    @Override
    public void onCreate() {
        super.onCreate();
        context = this;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        StartForeground();
        final Handler handler = new Handler();
        final Runnable runnable = new Runnable() {

            @Override
            public void run() {
                try {
                    if (!stopService) {
                        //Perform your task here
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (!stopService) {
                        handler.postDelayed(this, TimeUnit.SECONDS.toMillis(10));
                    }
                }
            }
        };
        handler.postDelayed(runnable, 2000);

        buildGoogleApiClient();

        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        Log.e(TAG, "Service Stopped");
        stopService = true;
        if (mFusedLocationClient != null) {
            mFusedLocationClient.removeLocationUpdates(mLocationCallback);
            Log.e(TAG_LOCATION, "Location Update Callback Removed");
        }
        super.onDestroy();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void StartForeground() {
        Intent intent = new Intent(context, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT);

        String CHANNEL_ID = "channel_location";
        String CHANNEL_NAME = "channel_location";

        NotificationCompat.Builder builder = null;
        NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
            channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
            notificationManager.createNotificationChannel(channel);
            builder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID);
            builder.setChannelId(CHANNEL_ID);
            builder.setBadgeIconType(NotificationCompat.BADGE_ICON_NONE);
        } else {
            builder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID);
        }

        builder.setContentTitle("Your title");
        builder.setContentText("You are now online");
        Uri notificationSound = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_NOTIFICATION);
        builder.setSound(notificationSound);
        builder.setAutoCancel(true);
        builder.setSmallIcon(R.drawable.ic_logo);
        builder.setContentIntent(pendingIntent);
        Notification notification = builder.build();
        startForeground(101, notification);
    }

    @Override
    public void onLocationChanged(Location location) {
        Log.e(TAG_LOCATION, "Location Changed Latitude : " + location.getLatitude() + "\tLongitude : " + location.getLongitude());

        latitude = String.valueOf(location.getLatitude());
        longitude = String.valueOf(location.getLongitude());

        if (latitude.equalsIgnoreCase("0.0") && longitude.equalsIgnoreCase("0.0")) {
            requestLocationUpdate();
        } else {
            Log.e(TAG_LOCATION, "Latitude : " + location.getLatitude() + "\tLongitude : " + location.getLongitude());
        }
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(10 * 1000);
        mLocationRequest.setFastestInterval(5 * 1000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
        builder.addLocationRequest(mLocationRequest);
        builder.setAlwaysShow(true);
        mLocationSettingsRequest = builder.build();

        mSettingsClient
                .checkLocationSettings(mLocationSettingsRequest)
                .addOnSuccessListener(new OnSuccessListener<LocationSettingsResponse>() {
                    @Override
                    public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
                        Log.e(TAG_LOCATION, "GPS Success");
                        requestLocationUpdate();
                    }
                }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                int statusCode = ((ApiException) e).getStatusCode();
                switch (statusCode) {
                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                        try {
                            int REQUEST_CHECK_SETTINGS = 214;
                            ResolvableApiException rae = (ResolvableApiException) e;
                            rae.startResolutionForResult((AppCompatActivity) context, REQUEST_CHECK_SETTINGS);
                        } catch (IntentSender.SendIntentException sie) {
                            Log.e(TAG_LOCATION, "Unable to execute request.");
                        }
                        break;
                    case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                        Log.e(TAG_LOCATION, "Location settings are inadequate, and cannot be fixed here. Fix in Settings.");
                }
            }
        }).addOnCanceledListener(new OnCanceledListener() {
            @Override
            public void onCanceled() {
                Log.e(TAG_LOCATION, "checkLocationSettings -> onCanceled");
            }
        });
    }

    @Override
    public void onConnectionSuspended(int i) {
        connectGoogleClient();
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        buildGoogleApiClient();
    }

    protected synchronized void buildGoogleApiClient() {
        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(context);
        mSettingsClient = LocationServices.getSettingsClient(context);

        mGoogleApiClient = new GoogleApiClient.Builder(context)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();

        connectGoogleClient();

        mLocationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(LocationResult locationResult) {
                super.onLocationResult(locationResult);
                Log.e(TAG_LOCATION, "Location Received");
                mCurrentLocation = locationResult.getLastLocation();
                onLocationChanged(mCurrentLocation);
            }
        };
    }

    private void connectGoogleClient() {
        GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
        int resultCode = googleAPI.isGooglePlayServicesAvailable(context);
        if (resultCode == ConnectionResult.SUCCESS) {
            mGoogleApiClient.connect();
        }
    }

    @SuppressLint("MissingPermission")
    private void requestLocationUpdate() {
        mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
    }
}

In Activity

Start Service : startService(new Intent(this, BackgroundLocationUpdateService.class));

Stop Service : stopService(new Intent(this, BackgroundLocationUpdateService.class));

In Fragment

Start Service : getActivity().startService(new Intent(getActivity().getBaseContext(), BackgroundLocationUpdateService.class));

Stop Service : getActivity().stopService(new Intent(getActivity(), BackgroundLocationUpdateService.class));

A beginner's guide to SQL database design

I started out with this article

http://en.tekstenuitleg.net/articles/software/database-design-tutorial/intro.html

It's pretty concise compared to reading an entire book and it explains the basics of database design (normalization, types of relationships) very well.

How can I check whether a option already exist in select by JQuery

Although most of other answers worked for me I used .find():

if ($("#yourSelect").find('option[value="value"]').length === 0){
    ...
}

Is JavaScript a pass-by-reference or pass-by-value language?

There's some discussion about the use of the term "pass by reference" in JavaScript here, but to answer your question:

A object is automatically passed by reference, without the need to specifically state it

(From the article mentioned above.)

RelativeLayout center vertical

This is working for me.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rell_main_bg"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#096d74" > 

<ImageView 
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    android:src="@drawable/img_logo_large"
    android:contentDescription="@null" />

</RelativeLayout>

ORA-01008: not all variables bound. They are bound

Came here looking for help as got same error running a statement listed below while going through a Udemy course:

INSERT INTO departments (department_id, department_name)
                  values( &dpet_id, '&dname');  

I'd been able to run statements with substitution variables before. Comment by Charles Burns about possibility of server reaching some threshold while recreating the variables prompted me to log out and restart the SQL Developer. The statement ran fine after logging back in.

Thought I'd share for anyone else venturing here with a limited scope issue as mine.

How to close the current fragment by using Button like the back button?

if you need in 2020

    Objects.requireNonNull(getActivity()).onBackPressed();

What is cURL in PHP?

cURL is a way you can hit a URL from your code to get a HTML response from it. It's used for command line cURL from the PHP language.

<?php
// Step 1
$cSession = curl_init(); 
// Step 2
curl_setopt($cSession,CURLOPT_URL,"http://www.google.com/search?q=curl");
curl_setopt($cSession,CURLOPT_RETURNTRANSFER,true);
curl_setopt($cSession,CURLOPT_HEADER, false); 
// Step 3
$result=curl_exec($cSession);
// Step 4
curl_close($cSession);
// Step 5
echo $result;
?> 

Step 1: Initialize a curl session using curl_init().

Step 2: Set option for CURLOPT_URL. This value is the URL which we are sending the request to. Append a search term curl using parameter q=. Set option for CURLOPT_RETURNTRANSFER. True will tell curl to return the string instead of print it out. Set option for CURLOPT_HEADER, false will tell curl to ignore the header in the return value.

Step 3: Execute the curl session using curl_exec().

Step 4: Close the curl session we have created.

Step 5: Output the return string.

public function curlCall($apiurl, $auth, $rflag)
{
    $ch = curl_init($apiurl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    if($auth == 'auth') { 
        curl_setopt($ch, CURLOPT_USERPWD, "passw:passw");
    } else {
        curl_setopt($ch, CURLOPT_USERPWD, "ss:ss1");
    }
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $dt = curl_exec($ch);        
    curl_close($ch);
    if($rflag != 1) {
        $dt = json_decode($dt,true);        
    }
    return $dt;
}

This is also used for authentication. We can also set the username and password for authentication.

For more functionality, see the user manual or the following tutorial:

http://php.net/manual/en/ref.curl.php
http://www.startutorial.com/articles/view/php-curl

ORA-12154: TNS:could not resolve the connect identifier specified (PLSQL Developer)

  • It did not work so i switched to oracle sql developer and it worked with no problems (making connection under 1 minute).
  • This link gave me an idea connect to MS Access so i created a user in oracle sql developer and the tried to connect to it in Toad and it worked.

Or second solution

you can try to connect using Direct not TNS by providing host and port in the connect screen of Toad

element with the max height from a set of elements

If you want to reuse in multiple places:

var maxHeight = function(elems){
    return Math.max.apply(null, elems.map(function ()
    {
        return $(this).height();
    }).get());
}

Then you can use:

maxHeight($("some selector"));

Fastest way to update 120 Million records

If you have the disk space, you could use SELECT INTO and create a new table. It's minimally logged, so it would go much faster

select t.*, int_field = CAST(-1 as int)
into mytable_new 
from mytable t

-- create your indexes and constraints

GO

exec sp_rename mytable, mytable_old
exec sp_rename mytable_new, mytable

drop table mytable_old

Show hide fragment in android

public void showHideFragment(final Fragment fragment){

    FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.setCustomAnimations(android.R.animator.fade_in,
                    android.R.animator.fade_out);

    if (fragment.isHidden()) {
        ft.show(fragment);
        Log.d("hidden","Show");
    } else {
        ft.hide(fragment);
        Log.d("Shown","Hide");                        
    }

    ft.commit();
}

How to convert an ArrayList containing Integers to primitive int array?

You can convert, but I don't think there's anything built in to do it automatically:

public static int[] convertIntegers(List<Integer> integers)
{
    int[] ret = new int[integers.size()];
    for (int i=0; i < ret.length; i++)
    {
        ret[i] = integers.get(i).intValue();
    }
    return ret;
}

(Note that this will throw a NullPointerException if either integers or any element within it is null.)

EDIT: As per comments, you may want to use the list iterator to avoid nasty costs with lists such as LinkedList:

public static int[] convertIntegers(List<Integer> integers)
{
    int[] ret = new int[integers.size()];
    Iterator<Integer> iterator = integers.iterator();
    for (int i = 0; i < ret.length; i++)
    {
        ret[i] = iterator.next().intValue();
    }
    return ret;
}

Best way to encode text data for XML in Java?

Try this:

String xmlEscapeText(String t) {
   StringBuilder sb = new StringBuilder();
   for(int i = 0; i < t.length(); i++){
      char c = t.charAt(i);
      switch(c){
      case '<': sb.append("&lt;"); break;
      case '>': sb.append("&gt;"); break;
      case '\"': sb.append("&quot;"); break;
      case '&': sb.append("&amp;"); break;
      case '\'': sb.append("&apos;"); break;
      default:
         if(c>0x7e) {
            sb.append("&#"+((int)c)+";");
         }else
            sb.append(c);
      }
   }
   return sb.toString();
}

How can I set the PATH variable for javac so I can manually compile my .java works?

You don't need to do any complex command-line stuff or edit any system code. You simply have to open Computer, showing all of your disks and open properties. From there, go to Advanced System Settings and click Environment Variables. Scroll down in the lower list box and edit Path. Do not erase anything already there. Put a ; after it and then type in your path. To test, open command prompt and do "javac", it should list around 20 programs. You would be finished at that point.

By the way, the command to compile is javac -g not just javac.

Happy coding!

Having links relative to root?

<a href="/fruits/index.html">Back to Fruits List</a>

generate random double numbers in c++

This snippet is straight from Stroustrup's The C++ Programming Language (4th Edition), §40.7; it requires C++11:

#include <functional>
#include <random>

class Rand_double
{
public:
    Rand_double(double low, double high)
    :r(std::bind(std::uniform_real_distribution<>(low,high),std::default_random_engine())){}

    double operator()(){ return r(); }

private:
    std::function<double()> r;
};

#include <iostream>    
int main() {
    // create the random number generator:
    Rand_double rd{0,0.5};

    // print 10 random number between 0 and 0.5
    for (int i=0;i<10;++i){
        std::cout << rd() << ' ';
    }
    return 0;
}

How can I break from a try/catch block without throwing an exception in Java

You can always do it with a break from a loop construct or a labeled break as specified in aioobies answer.

public static void main(String[] args) {
    do {
        try {
            // code..
            if (condition)
                break;
            // more code...
        } catch (Exception e) {

        }
    } while (false);
}

How to submit a form using Enter key in react.js?

Change <button type="button" to <button type="submit". Remove the onClick. Instead do <form className="commentForm" onSubmit={this.onFormSubmit}>. This should catch clicking the button and pressing the return key.

onFormSubmit = e => {
  e.preventDefault();
  const { name, email } = this.state;
  // send to server with e.g. `window.fetch`
}

...

<form onSubmit={this.onFormSubmit}>
  ...
  <button type="submit">Submit</button>
</form>

SQL User Defined Function Within Select

If it's a table-value function (returns a table set) you simply join it as a Table

this function generates one column table with all the values from passed comma-separated list

SELECT * FROM dbo.udf_generate_inlist_to_table('1,2,3,4')

How can I make an image transparent on Android?

android:alpha does this in XML:

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/blah"
    android:alpha=".75"/>

How can I generate a unique ID in Python?

Maybe this work for u

str(uuid.uuid4().fields[-1])[:5]

Bootstrap NavBar with left, center or right aligned items

2021 Update

Bootstrap 5 (beta)

Bootstrap 5 also has a flexbox Navbar, and introduces new RTL support. For this reason the concept of "left" and "right" has been replaced with "start" and "end". Therefore the margin utilities changed for Bootstrap 5 beta:

  • ml-auto => ms-auto
  • mr-auto => me-auto

Bootstrap 4

Now that Bootstrap 4 has flexbox, Navbar alignment is much easier. Here are updated examples for left, right and center in the Bootstrap 4 Navbar, and many other alignment scenarios demonstrated here.

The flexbox, auto-margins, and ordering utility classes can be used to align Navbar content as needed. There are many things to consider including the order and alignment of Navbar items (brand, links, toggler) on both large screens and the mobile/collapsed views. Don't use the grid classes (row,col) for the Navbar.

Here are various examples...

Left, center(brand) and right links:

enter image description here

<nav class="navbar navbar-expand-md navbar-dark bg-dark">
    <div class="navbar-collapse collapse w-100 order-1 order-md-0 dual-collapse2">
        <ul class="navbar-nav mr-auto">
            <li class="nav-item active">
                <a class="nav-link" href="#">Left</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="//codeply.com">Codeply</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#">Link</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#">Link</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#">Link</a>
            </li>
        </ul>
    </div>
    <div class="mx-auto order-0">
        <a class="navbar-brand mx-auto" href="#">Navbar 2</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".dual-collapse2">
            <span class="navbar-toggler-icon"></span>
        </button>
    </div>
    <div class="navbar-collapse collapse w-100 order-3 dual-collapse2">
        <ul class="navbar-nav ml-auto">
            <li class="nav-item">
                <a class="nav-link" href="#">Right</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#">Link</a>
            </li>
        </ul>
    </div>
</nav>

http://codeply.com/go/qhaBrcWp3v


Another BS4 Navbar option with center links and overlay logo image:

center links and overlay logo image

<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
    <div class="navbar-collapse collapse w-100 dual-collapse2 order-1 order-md-0">
        <ul class="navbar-nav ml-auto text-center">
            <li class="nav-item active">
                <a class="nav-link" href="#">Link</a>
            </li>
        </ul>
    </div>
    <div class="mx-auto my-2 order-0 order-md-1 position-relative">
        <a class="mx-auto" href="#">
            <img src="//placehold.it/120/ccff00" class="rounded-circle">
        </a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".dual-collapse2">
            <span class="navbar-toggler-icon"></span>
        </button>
    </div>
    <div class="navbar-collapse collapse w-100 dual-collapse2 order-2 order-md-2">
        <ul class="navbar-nav mr-auto text-center">
            <li class="nav-item">
                <a class="nav-link" href="#">Link</a>
            </li>
        </ul>
    </div>
</nav>

Or, these other Bootstrap 4 alignment scenarios:

brand left, dead center links, (empty right)

Navbar brand left, dead center links


brand and links center, icons left and right

enter image description here


More Bootstrap 4 examples:

toggler left on mobile, brand right
center brand and links on mobile
right align links on desktop, center links on mobile
left links & toggler, center brand, search right


Also see: Bootstrap 4 align navbar items to the right
Bootstrap 4 navbar right align with button that doesn't collapse on mobile
Center an element in Bootstrap 4 Navbar


Bootstrap 3

Option 1 - Brand center, with left/right nav links:

enter image description here

<nav class="navbar navbar-default" role="navigation">
  <div class="navbar-header">
    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </button>    
  </div>
  <a class="navbar-brand" href="#">Brand</a>
  <div class="navbar-collapse collapse">
    <ul class="nav navbar-nav navbar-left">
        <li><a href="#">Left</a></li>
        <li><a href="#about">Left</a></li>
    </ul>
    <ul class="nav navbar-nav navbar-right">
      <li><a href="#about">Right</a></li>
      <li><a href="#contact">Right</a></li>
    </ul>
  </div>
</nav>

.navbar-brand
{
    position: absolute;
    width: 100%;
    left: 0;
    text-align: center;
    margin:0 auto;
}
.navbar-toggle {
    z-index:3;
}

http://bootply.com/98314 (3.x)


Option 2 - Left, center and right nav links:

enter image description here

<nav class="navbar navbar-default" role="navigation">
  <div class="navbar-header">
    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </button>    
  </div>
  <div class="navbar-collapse collapse">
    <ul class="nav navbar-nav">
        <li><a href="#">Left</a></li>
    </ul>
    <ul class="nav navbar-nav navbar-center">
        <li><a href="#">Center</a></li>
        <li><a href="#">Center</a></li>
      <li><a href="#">Center</a></li>
    </ul>
    <ul class="nav navbar-nav navbar-right">
        <li><a href="#">Right</a></li>
    </ul>
  </div>
</nav>

@media (min-width: 768px) {
  .navbar-nav.navbar-center {
    position: absolute;
    left: 50%;
    transform: translatex(-50%);
  }
}

http://bootply.com/SGYC6BWeBK

Option 3 - Center both brand and links

enter image description here

.navbar .navbar-header,
.navbar-collapse {
    float:none;
    display:inline-block;
    vertical-align: top;
}

@media (max-width: 768px) {
    .navbar-collapse  {
        display: block;
    }
}

http://codeply.com/go/1lrdvNH9GI

More examples:

Left brand, center links
Left toggler, center brand

For 3.x also see nav-justified: Bootstrap center navbar


Center Navbar in Bootstrap
Bootstrap 4 align navbar items to the right

MySQL: Can't create/write to file '/tmp/#sql_3c6_0.MYI' (Errcode: 2) - What does it even mean?

I meet this error too when I run a wordpress on my Fedora system.

I googled it, and find a way to fix this.

Maybe this will help you too.

  1. check mysql config : my.cnf

     cat /etc/my.cnf | grep tmpdir
    

    I can't see anything in my my.cnf

  2. add tmpdir=/tmp to my.cnf under [mysqld]

  3. restart web/app and mysql server

    /etc/init.d/mysqld restart

How to uninstall a windows service and delete its files without rebooting

If in .net ( I'm not sure if it works for all windows services)

  • Stop the service (THis may be why you're having a problem.)
  • InstallUtil -u [name of executable]
  • Installutil -i [name of executable]
  • Start the service again...

Unless I'm changing the service's public interface, I often deploy upgraded versions of my services without even unistalling/reinstalling... ALl I do is stop the service, replace the files and restart the service again...

CSS3 Spin Animation

The only answer which gives the correct 359deg:

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(359deg); }
}

&.active {
  animation: spin 1s linear infinite;
}

Here's a useful gradient so you can prove it is spinning (if its a circle):

background: linear-gradient(to bottom, #000000 0%,#ffffff 100%);

Is there a Python equivalent to Ruby's string interpolation?

String interpolation is going to be included with Python 3.6 as specified in PEP 498. You will be able to do this:

name = 'Spongebob Squarepants'
print(f'Who lives in a Pineapple under the sea? \n{name}')

Note that I hate Spongebob, so writing this was slightly painful. :)

The program can't start because MSVCR110.dll is missing from your computer

You can download the required files from the Microsoft website or online or reinstall the Visual studio 2012 to fix this.

PostgreSQL: FOREIGN KEY/ON DELETE CASCADE

A foreign key with a cascade delete means that if a record in the parent table is deleted, then the corresponding records in the child table will automatically be deleted. This is called a cascade delete.

You are saying in a opposite way, this is not that when you delete from child table then records will be deleted from parent table.

UPDATE 1:

ON DELETE CASCADE option is to specify whether you want rows deleted in a child table when corresponding rows are deleted in the parent table. If you do not specify cascading deletes, the default behaviour of the database server prevents you from deleting data in a table if other tables reference it.

If you specify this option, later when you delete a row in the parent table, the database server also deletes any rows associated with that row (foreign keys) in a child table. The principal advantage to the cascading-deletes feature is that it allows you to reduce the quantity of SQL statements you need to perform delete actions.

So it's all about what will happen when you delete rows from Parent table not from child table.

So in your case when user removes entries from CATs table then rows will be deleted from books table. :)

Hope this helps you :)

How do I get the latest version of my code?

To answer your questions there are simply two steps:-

  1. Pull the latest changes from your git repo using git pull
  2. Clean your local working directory having unstaged changes using git checkout -- . .This will show the latest changes in your local repo from your remote git repo. cleaning all the local unstaged changes.

Please note git checkout -- . will discard all your changes in the local working directory. In case you want to discard any change for selective file use git checkout -- <filename>. And in case you don't want to lose your unstaged changes use git stash as it will clean your local working directory of all the unstaged changes while saving it if you need it in the future.

Use Mockito to mock some methods but not others

To directly answer your question, yes, you can mock some methods without mocking others. This is called a partial mock. See the Mockito documentation on partial mocks for more information.

For your example, you can do something like the following, in your test:

Stock stock = mock(Stock.class);
when(stock.getPrice()).thenReturn(100.00);    // Mock implementation
when(stock.getQuantity()).thenReturn(200);    // Mock implementation
when(stock.getValue()).thenCallRealMethod();  // Real implementation

In that case, each method implementation is mocked, unless specify thenCallRealMethod() in the when(..) clause.

There is also a possibility the other way around with spy instead of mock:

Stock stock = spy(Stock.class);
when(stock.getPrice()).thenReturn(100.00);    // Mock implementation
when(stock.getQuantity()).thenReturn(200);    // Mock implementation
// All other method call will use the real implementations

In that case, all method implementation are the real one, except if you have defined a mocked behaviour with when(..).

There is one important pitfall when you use when(Object) with spy like in the previous example. The real method will be called (because stock.getPrice() is evaluated before when(..) at runtime). This can be a problem if your method contains logic that should not be called. You can write the previous example like this:

Stock stock = spy(Stock.class);
doReturn(100.00).when(stock).getPrice();    // Mock implementation
doReturn(200).when(stock).getQuantity();    // Mock implementation
// All other method call will use the real implementations

Another possibility may be to use org.mockito.Mockito.CALLS_REAL_METHODS, such as:

Stock MOCK_STOCK = Mockito.mock( Stock.class, CALLS_REAL_METHODS );

This delegates unstubbed calls to real implementations.


However, with your example, I believe it will still fail, since the implementation of getValue() relies on quantity and price, rather than getQuantity() and getPrice(), which is what you've mocked.

Another possibility is to avoid mocks altogether:

@Test
public void getValueTest() {
    Stock stock = new Stock(100.00, 200);
    double value = stock.getValue();
    assertEquals("Stock value not correct", 100.00*200, value, .00001);
}

Parsing GET request parameters in a URL that contains another URL

You may have to use urlencode on the string 'http://google.com/?var=234&key=234'

How to Retrieve value from JTextField in Java Swing?

What I found helpful is this condition that is below.

String tempEmail = "";
JTextField tf1 = new JTextField();

tf1.addKeyListener(new KeyAdapter(){
    public void keyTyped(KeyEvent evt){
         tempEmail = ((JTextField)evt.getSource()).getText() + String.valueOf(evt.getKeyChar());
    }
});

UILabel - Wordwrap text

Xcode 10, Swift 4

Wrapping the Text for a label can also be done on Storyboard by selecting the Label, and using Attributes Inspector.

Lines = 0 Linebreak = Word Wrap

enter image description here

Trying to retrieve first 5 characters from string in bash error?

The original syntax will work with BASH but not with DASH. On debian systems you might think you are using bash, but maybe dash instead. If /bin/dash/exist then try temporarily renaming dash to something like no.dash, and then create soft a link, aka ln -s /bin/bash /bin/dash and see if that fixes the problem.

HttpClient.GetAsync(...) never returns when using await/async

In my case 'await' never finished because of exception while executing the request, e.g. server not responding, etc. Surround it with try..catch to identify what happened, it'll also complete your 'await' gracefully.

public async Task<Stuff> GetStuff(string id)
{
    string path = $"/api/v2/stuff/{id}";
    try
    {
        HttpResponseMessage response = await client.GetAsync(path);
        if (response.StatusCode == HttpStatusCode.OK)
        {
            string json = await response.Content.ReadAsStringAsync();
            return JsonUtility.FromJson<Stuff>(json);
        }
        else
        {
            Debug.LogError($"Could not retrieve stuff {id}");
        }
    }
    catch (Exception exception)
    {
        Debug.LogError($"Exception when retrieving stuff {exception}");
    }
    return null;
}

Ruby: How to post a file via HTTP as multipart/form-data?

The multipart-post gem works pretty well with Rails 4 Net::HTTP, no other special gem

def model_params
  require_params = params.require(:model).permit(:param_one, :param_two, :param_three, :avatar)
  require_params[:avatar] = model_params[:avatar].present? ? UploadIO.new(model_params[:avatar].tempfile, model_params[:avatar].content_type, model_params[:avatar].original_filename) : nil
  require_params
end

require 'net/http/post/multipart'

url = URI.parse('http://www.example.com/upload')
Net::HTTP.start(url.host, url.port) do |http|
  req = Net::HTTP::Post::Multipart.new(url, model_params)
  key = "authorization_key"
  req.add_field("Authorization", key) #add to Headers
  http.use_ssl = (url.scheme == "https")
  http.request(req)
end

https://github.com/Feuda/multipart-post/tree/patch-1

Export DataTable to Excel with Open Xml SDK in c#

I also wrote a C#/VB.Net "Export to Excel" library, which uses OpenXML and (more importantly) also uses OpenXmlWriter, so you won't run out of memory when writing large files.

Full source code, and a demo, can be downloaded here:

Export to Excel

It's dead easy to use. Just pass it the filename you want to write to, and a DataTable, DataSet or List<>.

CreateExcelFile.CreateExcelDocument(myDataSet, "MyFilename.xlsx");

And if you're calling it from an ASP.Net application, pass it the HttpResponse to write the file out to.

CreateExcelFile.CreateExcelDocument(myDataSet, "MyFilename.xlsx", Response);

Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed

In Windows 10, I solved this problem with the Windows Credential Manager. I found multiple credentials for the NAS unit that I was having trouble with. After deleting both credentials, I was able to access the NAS mapped network drives without a problem.

GitHub authentication failing over https, returning wrong email address

On Windows, you may be silently blocked by your Antivirus or Windows firewall. Temporarily turn off those services and push/pull from remote origin.

Drop rows containing empty cells from a pandas DataFrame

You can use this variation:

import pandas as pd
vals = {
    'name' : ['n1', 'n2', 'n3', 'n4', 'n5', 'n6', 'n7'],
    'gender' : ['m', 'f', 'f', 'f',  'f', 'c', 'c'],
    'age' : [39, 12, 27, 13, 36, 29, 10],
    'education' : ['ma', None, 'school', None, 'ba', None, None]
}
df_vals = pd.DataFrame(vals) #converting dict to dataframe

This will output(** - highlighting only desired rows):

   age education gender name
0   39        ma      m   n1 **
1   12      None      f   n2    
2   27    school      f   n3 **
3   13      None      f   n4
4   36        ba      f   n5 **
5   29      None      c   n6
6   10      None      c   n7

So to drop everything that does not have an 'education' value, use the code below:

df_vals = df_vals[~df_vals['education'].isnull()] 

('~' indicating NOT)

Result:

   age education gender name
0   39        ma      m   n1
2   27    school      f   n3
4   36        ba      f   n5

How can I use querySelector on to pick an input element by name?

Note: if the name includes [ or ] itself, add two backslashes in front of it, like:

<input name="array[child]" ...

document.querySelector("[name=array\\[child\\]]");

How to implement a queue using two stacks?

**Easy JS solution **

  • Note: I took ideas from other people comment

_x000D_
_x000D_
/*_x000D_
_x000D_
enQueue(q,  x)_x000D_
 1) Push x to stack1 (assuming size of stacks is unlimited)._x000D_
_x000D_
deQueue(q)_x000D_
 1) If both stacks are empty then error._x000D_
 2) If stack2 is empty_x000D_
   While stack1 is not empty, push everything from stack1 to stack2._x000D_
 3) Pop the element from stack2 and return it._x000D_
_x000D_
*/_x000D_
class myQueue {_x000D_
    constructor() {_x000D_
        this.stack1 = [];_x000D_
        this.stack2 = [];_x000D_
    }_x000D_
_x000D_
    push(item) {_x000D_
        this.stack1.push(item)_x000D_
    }_x000D_
_x000D_
    remove() {_x000D_
        if (this.stack1.length == 0 && this.stack2.length == 0) {_x000D_
            return "Stack are empty"_x000D_
        }_x000D_
_x000D_
        if (this.stack2.length == 0) {_x000D_
_x000D_
            while (this.stack1.length != 0) {_x000D_
                this.stack2.push(this.stack1.pop())_x000D_
            }_x000D_
        }_x000D_
        return this.stack2.pop()_x000D_
    }_x000D_
_x000D_
_x000D_
    peek() {_x000D_
        if (this.stack2.length == 0 && this.stack1.length == 0) {_x000D_
            return 'Empty list'_x000D_
        }_x000D_
_x000D_
        if (this.stack2.length == 0) {_x000D_
            while (this.stack1.length != 0) {_x000D_
                this.stack2.push(this.stack1.pop())_x000D_
            }_x000D_
        }_x000D_
_x000D_
        return this.stack2[0]_x000D_
    }_x000D_
_x000D_
    isEmpty() {_x000D_
        return this.stack2.length === 0 && this.stack1.length === 0;_x000D_
    }_x000D_
_x000D_
}_x000D_
_x000D_
const q = new myQueue();_x000D_
q.push(1);_x000D_
q.push(2);_x000D_
q.push(3);_x000D_
q.remove()_x000D_
_x000D_
console.log(q)
_x000D_
_x000D_
_x000D_

Flask-SQLalchemy update a row's information

There is a method update on BaseQuery object in SQLAlchemy, which is returned by filter_by.

num_rows_updated = User.query.filter_by(username='admin').update(dict(email='[email protected]')))
db.session.commit()

The advantage of using update over changing the entity comes when there are many objects to be updated.

If you want to give add_user permission to all the admins,

rows_changed = User.query.filter_by(role='admin').update(dict(permission='add_user'))
db.session.commit()

Notice that filter_by takes keyword arguments (use only one =) as opposed to filter which takes an expression.

Simulate a specific CURL in PostMan

A simpler approach would be:

  1. Open POSTMAN
  2. Click on "import" tab on the upper left side.
  3. Select the Raw Text option and paste your cURL command.
  4. Hit import and you will have the command in your Postman builder!
  5. Click Send to post the command

Hope this helps!

How to select all instances of selected region in Sublime Text

On Mac:

?+CTRL+g

However, you can reset any key any way you'd like using "Customize your Sublime Text 2 configuration for awesome coding." for Mac.


On Windows/Linux:

Alt+F3

If anyone has how-tos or articles on this, I'd be more than happy to update.

How to run cron job every 2 hours

The line should read either:

0 0-23/2 * * * /home/username/test.sh

or

0 0,2,4,6,8,10,12,14,16,18,20,22 * * * /home/username/test.sh

Val and Var in Kotlin

VAR is used for creating those variable whose value will change over the course of time in your application. It is same as VAR of swift, whereas VAL is used for creating those variable whose value will not change over the course of time in your application.It is same as LET of swift.

Is there a way to split a widescreen monitor in to two or more virtual monitors?

From what i understand, you can just manage windows using microsoft. hold control and select multiple windows in the taskbar, then right click it and tile whatever way you want. what i've been looking for is a way to actually split a physical monitor into two. so you can run not just windowed prgrams (explorer, firefox, whatever) but full screen programs like games or movies or whatever else you want. this is super useful to fix bugs in full screen programs. im tired of these "windows mangagers" its easier just to click and drag it where you want. and im not OCD about it lining up just right. i just want to split a monitor into two. is that so hard to ask?

Android Studio Run/Debug configuration error: Module not specified

I was trying to open an old GitHub project with the latest android studio that's why got this error. I tried almost all the way that mentions in this post but none of them is work.

In my case, I update my Gradle version with my latest project, and the issue resolved. Use your latest Gradle version to resolve the issue.

enter image description here enter image description here

Arduino IDE can't find ESP8266WiFi.h file

For those who are having trouble with fatal error: ESP8266WiFi.h: No such file or directory, you can install the package manually.

  1. Download the Arduino ESP8266 core from here https://github.com/esp8266/Arduino
  2. Go into library from the downloaded core and grab ESP8266WiFi.
  3. Drag that into your local Arduino/library folder. This can be found by going into preferences and looking at your Sketchbook location

You may still need to have the http://arduino.esp8266.com/stable/package_esp8266com_index.json package installed beforehand, however.

Edit: That wasn't the full issue, you need to make sure you have the correct ESP8266 Board selected before compiling.

Hope this helps others.

Python's most efficient way to choose longest string in list?

From the Python documentation itself, you can use max:

>>> mylist = ['123','123456','1234']
>>> print max(mylist, key=len)
123456

This Row already belongs to another table error when trying to add rows?

foreach (DataRow dr in dtSpecificOrders.rows)
{
   dtSpecificOrders.Rows.Add(dr.ItemArray); 
}

I keep getting "Uncaught SyntaxError: Unexpected token o"

I had a similar problem just now and my solution might help. I'm using an iframe to upload and convert an xml file to json and send it back behind the scenes, and Chrome was adding some garbage to the incoming data that only would show up intermittently and cause the "Uncaught SyntaxError: Unexpected token o" error.

I was accessing the iframe data like this:

$('#load-file-iframe').contents().text()

which worked fine on localhost, but when I uploaded it to the server it stopped working only with some files and only when loading the files in a certain order. I don't really know what caused it, but this fixed it. I changed the line above to

$('#load-file-iframe').contents().find('body').text()

once I noticed some garbage in the HTML response.

Long story short check your raw HTML response data and you might turn something up.

libclntsh.so.11.1: cannot open shared object file.

I have copied all library files from installer media databases/stage/ext/lib to $ORACLE_HOME/lib and it resolved the issue.

Checking if a website is up via Python

You could try to do this with getcode() from urllib

>>> print urllib.urlopen("http://www.stackoverflow.com").getcode()
>>> 200

EDIT: For more modern python, i.e. python3, use:

import urllib.request
print(urllib.request.urlopen("http://www.stackoverflow.com").getcode())
>>> 200

Adding an onclicklistener to listview (android)

listView.setOnItemClickListener(new OnItemClickListener() {

    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Object o = prestListView.getItemAtPosition(position);
        prestationEco str = (prestationEco)o; //As you are using Default String Adapter
        Toast.makeText(getBaseContext(),str.getTitle(),Toast.LENGTH_SHORT).show();
    }
});

What is the difference between old style and new style classes in Python?

Here's a very practical, true/false difference. The only difference between the two versions of the following code is that in the second version Person inherits from object. Other than that, the two versions are identical, but with different results:

  1. Old-style classes

    class Person():
        _names_cache = {}
        def __init__(self,name):
            self.name = name
        def __new__(cls,name):
            return cls._names_cache.setdefault(name,object.__new__(cls,name))
    
    ahmed1 = Person("Ahmed")
    ahmed2 = Person("Ahmed")
    print ahmed1 is ahmed2
    print ahmed1
    print ahmed2
    
    
    >>> False
    <__main__.Person instance at 0xb74acf8c>
    <__main__.Person instance at 0xb74ac6cc>
    >>>
    
    
  2. New-style classes

    class Person(object):
        _names_cache = {}
        def __init__(self,name):
            self.name = name
        def __new__(cls,name):
            return cls._names_cache.setdefault(name,object.__new__(cls,name))
    
    ahmed1 = Person("Ahmed")
    ahmed2 = Person("Ahmed")
    print ahmed2 is ahmed1
    print ahmed1
    print ahmed2
    
    >>> True
    <__main__.Person object at 0xb74ac66c>
    <__main__.Person object at 0xb74ac66c>
    >>>
    

How to set custom JsonSerializerSettings for Json.NET in ASP.NET Web API?

You can specify JsonSerializerSettings for each JsonConvert, and you can set a global default.

Single JsonConvert with an overload:

// Option #1.
JsonSerializerSettings config = new JsonSerializerSettings { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore };
this.json = JsonConvert.SerializeObject(YourObject, Formatting.Indented, config);

// Option #2 (inline).
JsonConvert.SerializeObject(YourObject, Formatting.Indented,
    new JsonSerializerSettings() {
        ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
    }
);

Global Setting with code in Application_Start() in Global.asax.cs:

JsonConvert.DefaultSettings = () => new JsonSerializerSettings {
     Formatting = Newtonsoft.Json.Formatting.Indented,
     ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
};

Reference: https://github.com/JamesNK/Newtonsoft.Json/issues/78

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

The following steps are to reset the password for a user in case you forgot, this would also solve your mentioned error.

First, stop your MySQL:

sudo /etc/init.d/mysql stop

Now start up MySQL in safe mode and skip the privileges table:

sudo mysqld_safe --skip-grant-tables &

Login with root:

mysql -uroot

And assign the DB that needs to be used:

use mysql;

Now all you have to do is reset your root password of the MySQL user and restart the MySQL service:

update user set password=PASSWORD("YOURPASSWORDHERE") where User='root';

flush privileges;

quit and restart MySQL:

quit

sudo /etc/init.d/mysql stop sudo /etc/init.d/mysql start Now your root password should be working with the one you just set, check it with:

mysql -u root -p

Fastest way of finding differences between two files in unix?

You could also try to include md5-hash-sums or similar do determine whether there are any differences at all. Then, only compare files which have different hashes...

How to get IntPtr from byte[] in C#

This should work but must be used within an unsafe context:

byte[] buffer = new byte[255];
fixed (byte* p = buffer)
{
    IntPtr ptr = (IntPtr)p;
    // do you stuff here
}

beware, you have to use the pointer in the fixed block! The gc can move the object once you are not anymore in the fixed block.

PHP import Excel into database (xls & xlsx)

If you save the excel file as a CSV file then you can import it into a mysql database using tools such as PHPMyAdmin

Im not sure if this would help in your situation, but a csv file either manually or programatically would be a lot easier to parse into a database than an excel file I would have thought.

EDIT: I would however suggest looking at the other answers rather than mine since @diEcho answer seems more appropriate.

Select from multiple tables without a join?

select 'test', (select name from employee where id=1) as name, (select name from address where id=2) as address ;

How do I push a new local branch to a remote Git repository and track it too?

To create a new branch by branching off from an existing branch

git checkout -b <new_branch>

and then push this new branch to repository using

git push -u origin <new_branch>

This creates and pushes all local commits to a newly created remote branch origin/<new_branch>

Fundamental difference between Hashing and Encryption algorithms

A hash function could be considered the same as baking a loaf of bread. You start out with inputs (flour, water, yeast, etc...) and after applying the hash function (mixing + baking), you end up with an output: a loaf of bread.

Going the other way is extraordinarily difficult - you can't really separate the bread back into flour, water, yeast - some of that was lost during the baking process, and you can never tell exactly how much water or flour or yeast was used for a particular loaf, because that information was destroyed by the hashing function (aka the oven).

Many different variants of inputs will theoretically produce identical loaves (e.g. 2 cups of water and 1 tsbp of yeast produce exactly the same loaf as 2.1 cups of water and 0.9tsbp of yeast), but given one of those loaves, you can't tell exactly what combo of inputs produced it.

Encryption, on the other hand, could be viewed as a safe deposit box. Whatever you put in there comes back out, as long as you possess the key with which it was locked up in the first place. It's a symmetric operation. Given a key and some input, you get a certain output. Given that output, and the same key, you'll get back the original input. It's a 1:1 mapping.

ImportError: No module named apiclient.discovery

Make sure you only have google-api-python-client installed. If you have apiclient installed, it will cause a collision. So, run the following:

sudo pip uninstall apiclient

Setting default checkbox value in Objective-C?

Documentation on UISwitch says:

[mySwitch setOn:NO]; 

In Interface Builder, select your switch and in the Attributes inspector you'll find State which can be set to on or off.

DIV :after - add content after DIV

Position your <div> absolutely at the bottom and don't forget to give div.A a position: relative - http://jsfiddle.net/TTaMx/

    .A {
        position: relative;
        margin: 40px 0;
        height: 40px;
        width: 200px;
        background: #eee;
    }

    .A:after {
        content: " ";
        display: block;
        background: #c00;
        height: 29px;
        width: 100%;

        position: absolute;
        bottom: -29px;
    }?

When is layoutSubviews called?

have you looked at layoutIfNeeded?

The documentation snippet is below. Does the animation work if you call this method explicitly during the animation?

layoutIfNeeded Lays out the subviews if needed.

- (void)layoutIfNeeded

Discussion Use this method to force the layout of subviews before drawing.

Availability Available in iPhone OS 2.0 and later.

Div vertical scrollbar show

Always : If you always want vertical scrollbar, use overflow-y: scroll;

jsFiddle:

<div style="overflow-y: scroll;">
......
</div>

When needed: If you only want vertical scrollbar when needed, use overflow-y: auto; (You need to specify a height in this case)

jsFiddle:

<div style="overflow-y: auto; height:150px; ">
....
</div>

Set variable value to array of strings

-- create test table "Accounts"
create table Accounts (
  c_ID int primary key
 ,first_name varchar(100)
 ,last_name varchar(100)
 ,city varchar(100)
 );

insert into Accounts values (101, 'Sebastian', 'Volk', 'Frankfurt' );
insert into Accounts values (102, 'Beate',  'Mueller', 'Hamburg' );
insert into Accounts values (103, 'John',  'Walker', 'Washington' );
insert into Accounts values (104, 'Britney', 'Sears', 'Holywood' );
insert into Accounts values (105, 'Sarah', 'Schmidt', 'Mainz' );
insert into Accounts values (106, 'George', 'Lewis', 'New Jersey' );
insert into Accounts values (107, 'Jian-xin', 'Wang', 'Peking' );
insert into Accounts values (108, 'Katrina', 'Khan', 'Bolywood' );

-- declare table variable
declare @tb_FirstName table(name varchar(100));
insert into  @tb_FirstName values ('John'), ('Sarah'), ('George');

SELECT * 
FROM Accounts
WHERE first_name in (select name from @tb_FirstName);

SELECT * 
FROM Accounts
WHERE first_name not in (select name from @tb_FirstName);
go

drop table Accounts;
go

An efficient way to transpose a file in Bash

I was looking for a solution to transpose any kind of matrix (nxn or mxn) with any kind of data (numbers or data) and got the following solution:

Row2Trans=number1
Col2Trans=number2

for ((i=1; $i <= Line2Trans; i++));do
    for ((j=1; $j <=Col2Trans ; j++));do
        awk -v var1="$i" -v var2="$j" 'BEGIN { FS = "," }  ; NR==var1 {print $((var2)) }' $ARCHIVO >> Column_$i
    done
done

paste -d',' `ls -mv Column_* | sed 's/,//g'` >> $ARCHIVO

Get Path from another app (WhatsApp)

It works for me for opening small text file... I didn't try in other file

protected void viewhelper(Intent intent) {
    Uri a = intent.getData();
    if (!a.toString().startsWith("content:")) {
        return;
    }
    //Ok Let's do it
    String content = readUri(a);
    //do something with this content
}

here is the readUri(Uri uri) method

private String readUri(Uri uri) {
    InputStream inputStream = null;
    try {
        inputStream = getContentResolver().openInputStream(uri);
        if (inputStream != null) {
            byte[] buffer = new byte[1024];
            int result;
            String content = "";
            while ((result = inputStream.read(buffer)) != -1) {
                content = content.concat(new String(buffer, 0, result));
            }
            return content;
        }
    } catch (IOException e) {
        Log.e("receiver", "IOException when reading uri", e);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                Log.e("receiver", "IOException when closing stream", e);
            }
        }
    }
    return null;
}

I got it from this repository https://github.com/zhutq/android-file-provider-demo/blob/master/FileReceiver/app/src/main/java/com/demo/filereceiver/MainActivity.java
I modified some code so that it work.

Manifest file:

    <activity android:name=".MainActivity">
        <intent-filter >
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <data android:mimeType="*/*" />
        </intent-filter>
    </activity>

You need to add

@Override
protected void onCreate(Bundle savedInstanceState) {
    /*
     *    Your OnCreate
     */
    Intent intent = getIntent();
    String action = intent.getAction();
    String type = intent.getType();

    //VIEW"
    if (Intent.ACTION_VIEW.equals(action) && type != null) {
        viewhelper(intent); // Handle text being sent
    }
  }

Access an arbitrary element in a dictionary in Python

As others mentioned, there is no "first item", since dictionaries have no guaranteed order (they're implemented as hash tables). If you want, for example, the value corresponding to the smallest key, thedict[min(thedict)] will do that. If you care about the order in which the keys were inserted, i.e., by "first" you mean "inserted earliest", then in Python 3.1 you can use collections.OrderedDict, which is also in the forthcoming Python 2.7; for older versions of Python, download, install, and use the ordered dict backport (2.4 and later) which you can find here.

Python 3.7 Now dicts are insertion ordered.

Summernote image upload

Image Upload for Summernote v0.8.1

for large images

$('#summernote').summernote({
    height: ($(window).height() - 300),
    callbacks: {
        onImageUpload: function(image) {
            uploadImage(image[0]);
        }
    }
});

function uploadImage(image) {
    var data = new FormData();
    data.append("image", image);
    $.ajax({
        url: 'Your url to deal with your image',
        cache: false,
        contentType: false,
        processData: false,
        data: data,
        type: "post",
        success: function(url) {
            var image = $('<img>').attr('src', 'http://' + url);
            $('#summernote').summernote("insertNode", image[0]);
        },
        error: function(data) {
            console.log(data);
        }
    });
}

Postgresql 9.2 pg_dump version mismatch

I had same error and this is how I solved it in my case. This means your postgresql version is 9.2.1 but you have started postgresql service of 9.1.6.

If you run psql postgres you will see:

psql (9.2.1, server 9.1.6)

What I did to solve this problem is:

  1. brew services stop [email protected]
  2. brew services restart [email protected]

Now run psql postgres and you should have: psql (9.2.1)

You can also run brew services list to see the status of your postgres.

Simple way to get element by id within a div tag?

A simple way to do what OP desires in core JS.

document.getElementById(parent.id).children[child.id];

How to read the last row with SQL Server

If you're using MS SQL, you can try:

SELECT TOP 1 * FROM table_Name ORDER BY unique_column DESC 

Could not load file or assembly System.Web.Http.WebHost after published to Azure web site

For me worked adding the following section to web.config file:

<configuration>
...
    <runtime>
    ...
        <dependentAssembly>
            <assemblyIdentity name="System.Web.Http.WebHost" publicKeyToken="31bf3856ad364e35" culture="neutral" />
            <bindingRedirect oldVersion="0.0.0.0-5.1.0.0" newVersion="5.1.0.0" />
        </dependentAssembly>
    ...
    </runtime>
...
</configuration>

This example stands for MVC 5.1. Hope it will help someone to resolve such issue.

Installing python module within code

for installing multiple packages, i am using a setup.py file with following code:

import sys
import subprocess
import pkg_resources

required = {'numpy','pandas','<etc>'} 
installed = {pkg.key for pkg in pkg_resources.working_set}
missing = required - installed


if missing:
    # implement pip as a subprocess:
    subprocess.check_call([sys.executable, '-m', 'pip', 'install',*missing])

What's the best way to loop through a set of elements in JavaScript?

Note that in some cases, you need to loop in reverse order (but then you can use i-- too).

For example somebody wanted to use the new getElementsByClassName function to loop on elements of a given class and change this class. He found that only one out of two elements was changed (in FF3).
That's because the function returns a live NodeList, which thus reflects the changes in the Dom tree. Walking the list in reverse order avoided this issue.

var menus = document.getElementsByClassName("style2");
for (var i = menus.length - 1; i >= 0; i--)
{
  menus[i].className = "style1";
}

In increasing index progression, when we ask the index 1, FF inspects the Dom and skips the first item with style2, which is the 2nd of the original Dom, thus it returns the 3rd initial item!

getting error while updating Composer

Problem :

Problem 1
    - laravel/framework v5.8.38 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.8.38 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.8.38 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - Installation request for laravel/framework (locked at v5.8.38, required as 5.8.*) -> satisfiable by laravel/framework[v5.8.38].

  To enable extensions, verify that they are enabled in your .ini files:
    - C:\xampp\php\php.ini
  You can also run `php --ini` inside terminal to see which files are used by PHP in CLI mode.

Solution :

if you using xampp just remove ' ; ' from

;extension=mbstring

in php.ini , save it, done!

How to create an AVD for Android 4.0

This answer is for creating AVD in Android Studio.

  1. First click on AVD button on your Android Studio top bar.

image 1

  1. In this window click on Create Virtual Device

image 2

  1. Now you will choose hardware profile for AVD and click Next.

image 3

  1. Choose Android Api Version you want in your AVD. Download if no api exist. Click next.

image 4

  1. This is now window for customizing some AVD feature like camera, network, memory and ram size etc. Just keep default and click Finish.

image 5

  1. You AVD is ready, now click on AVD button in Android Studio (same like 1st step). Then you will able to see created AVD in list. Click on Play button on your AVD.

image 6

  1. Your AVD will start soon.

image 7

How to generate random number in Bash?

bash 5.1 introduces a new variable, SRANDOM, which gets its random data from the system's entropy engine and so is not linear and cannot be reseeded to get an identical random sequence. This variable can be used as a substitute for RANDOM for generating more random numbers.

$ echo $((1 + SRANDOM % 10))
4

Can typescript export a function?

To answer the title of your question directly because this comes up in Google first:

YES, TypeScript can export a function!

Here is a direct quote from the TS Documentation:

"Any declaration (such as a variable, function, class, type alias, or interface) can be exported by adding the export keyword."

Reference Link

What is the difference between synchronous and asynchronous programming (in node.js)

Asynchronous programming in JS:

Synchronous

  • Stops execution of further code until this is done.
  • Because it this stoppage of further execution, synchronous code is called 'blocking'. Blocking in the sense that no other code will be executed.

Asynchronous

  • Execution of this is deferred to the event loop, this is a construct in a JS virtual machine which executes asynchronous functions (after the stack of synchronous functions is empty).
  • Asynchronous code is called non blocking because it doesn't block further code from running.

Example:

_x000D_
_x000D_
// This function is synchronous_x000D_
function log(arg) {_x000D_
    console.log(arg)_x000D_
}_x000D_
_x000D_
log(1);_x000D_
_x000D_
// This function is asynchronous_x000D_
setTimeout(() => {_x000D_
    console.log(2)_x000D_
}, 0);_x000D_
_x000D_
log(3)
_x000D_
_x000D_
_x000D_

  • The example logs 1, 3, 2.
  • 2 is logged last because it is inside a asynchronous function which is executed after the stack is empty.

Excel Formula: Count cells where value is date

Here's my solution. If your cells will contain only dates or blanks, just compare it to another date. If the cell can be converted to date, it will be counted.

=COUNTIF(C:C,">1/1/1900")
## Counts all the dates in column C

Caution, cells with numbers will be counted.

How to reference a method in javadoc?

The general format, from the @link section of the javadoc documentation, is:

{@link package.class#member label}

Examples

Method in the same class:

/** See also {@link #myMethod(String)}. */
void foo() { ... }

Method in a different class, either in the same package or imported:

/** See also {@link MyOtherClass#myMethod(String)}. */
void foo() { ... }

Method in a different package and not imported:

/** See also {@link com.mypackage.YetAnotherClass#myMethod(String)}. */
void foo() { ... }

Label linked to method, in plain text rather than code font:

/** See also this {@linkplain #myMethod(String) implementation}. */
void foo() { ... }

A chain of method calls, as in your question. We have to specify labels for the links to methods outside this class, or we get getFoo().Foo.getBar().Bar.getBaz(). But these labels can be fragile during refactoring -- see "Labels" below.

/**
 * A convenience method, equivalent to 
 * {@link #getFoo()}.{@link Foo#getBar() getBar()}.{@link Bar#getBaz() getBaz()}.
 * @return baz
 */
public Baz fooBarBaz()

Labels

Automated refactoring may not affect labels. This includes renaming the method, class or package; and changing the method signature.

Therefore, provide a label only if you want different text than the default.

For example, you might link from human language to code:

/** You can also {@linkplain #getFoo() get the current foo}. */
void setFoo( Foo foo ) { ... }

Or you might link from a code sample with text different than the default, as shown above under "A chain of method calls." However, this can be fragile while APIs are evolving.

Type erasure and #member

If the method signature includes parameterized types, use the erasure of those types in the javadoc @link. For example:

int bar( Collection<Integer> receiver ) { ... }

/** See also {@link #bar(Collection)}. */
void foo() { ... }

Detecting superfluous #includes in C/C++?

Maybe a little late, but I once found a WebKit perl script that did just what you wanted. It'll need some adapting I believe (I'm not well versed in perl), but it should do the trick:

http://trac.webkit.org/browser/branches/old/safari-3-2-branch/WebKitTools/Scripts/find-extra-includes

(this is an old branch because trunk doesn't have the file anymore)

jQuery toggle animation

I dont think adding dual functions inside the toggle function works for a registered click event (Unless I'm missing something)

For example:

$('.btnName').click(function() {
 top.$('#panel').toggle(function() {
   $(this).animate({ 
     // style change
   }, 500);
   },
   function() {
   $(this).animate({ 
     // style change back
   }, 500);
 });

How do I convert from int to String?

It depends on how you want to use your String. This can help:

String total =  Integer.toString(123) + Double.toString(456.789);

get the selected index value of <select> tag in php

$gender = $_POST['gender'];
echo $gender;  

it will echoes the selected value.

sort files by date in PHP

You need to put the files into an array in order to sort and find the last modified file.

$files = array();
if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
           $files[filemtime($file)] = $file;
        }
    }
    closedir($handle);

    // sort
    ksort($files);
    // find the last modification
    $reallyLastModified = end($files);

    foreach($files as $file) {
        $lastModified = date('F d Y, H:i:s',filemtime($file));
        if(strlen($file)-strpos($file,".swf")== 4){
           if ($file == $reallyLastModified) {
             // do stuff for the real last modified file
           }
           echo "<tr><td><input type=\"checkbox\" name=\"box[]\"></td><td><a href=\"$file\" target=\"_blank\">$file</a></td><td>$lastModified</td></tr>";
        }
    }
}

Not tested, but that's how to do it.

When to use dynamic vs. static libraries

A static library gets compiled into the client. A .lib is used at compile time and the contents of the library become part of the consuming executable.

A dynamic library is loaded at runtime and not compiled into the client executable. Dynamic libraries are more flexible as multiple client executables can load a DLL and utilize its functionality. This also keeps the overall size and maintainability of your client code to a minimum.

Open Facebook page from Android app?

To launch facebook page from your app, let urlString = "fb://page/your_fb_page_id"

To launch facebook messenger let urlString = "fb-messenger://user/your_fb_page_id"

FB page id is usually numeric. To get it, goto Find My FB ID input your profile url, something like www.facebook.com/edgedevstudio then click "Find Numberic ID".

Voila, you now have your fb numeric id. replace "your_fb_page_id" with the generated Numeric ID

 val intent = Intent(Intent.ACTION_VIEW, Uri.parse(urlString))
 if (intent.resolveActivity(packageManager) != null) //check if app is available to handle the implicit intent
 startActivity(intent)

Getting list of lists into pandas DataFrame

Call the pd.DataFrame constructor directly:

df = pd.DataFrame(table, columns=headers)
df

   Heading1  Heading2
0         1         2
1         3         4

jQuery remove special characters from string and more

replace(/[^a-z0-9\s]/gi, '') will filter the string down to just alphanumeric values and replace(/[_\s]/g, '-') will replace underscores and spaces with hyphens:

str.replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, '-')

Source for Regex: RegEx for Javascript to allow only alphanumeric

Here is a demo: http://jsfiddle.net/vNfrk/

Browser Timeouts

You can see the default value in Chrome in this link

int64_t g_used_idle_socket_timeout_s = 300 // 5 minutes

In Chrome, as far as I know, there isn't an easy way (as Firefox do) to change the timeout value.

How do I git rm a file without deleting it from disk?

git rm --cached file

should do what you want.

You can read more details at git help rm

Equivalent of shell 'cd' command to change the working directory?

I would use os.chdir like this:

os.chdir("/path/to/change/to")

By the way, if you need to figure out your current path, use os.getcwd().

More here

ASP.NET: Session.SessionID changes between requests

Be sure that you do not have a session timeout that is very short, and also make sure that if you are using cookie based sessions that you are accepting the session.

The FireFox webDeveloperToolbar is helpful at times like this as you can see the cookies set for your application.

List of special characters for SQL LIKE clause

Potential answer for SQL Server

Interesting I just ran a test using LinqPad with SQL Server which should be just running Linq to SQL underneath and it generates the following SQL statement.

Records .Where(r => r.Name.Contains("lkjwer--_~[]"))

-- Region Parameters
DECLARE @p0 VarChar(1000) = '%lkjwer--~_~~~[]%'
-- EndRegion
SELECT [t0].[ID], [t0].[Name]
FROM [RECORDS] AS [t0]
WHERE [t0].[Name] LIKE @p0 ESCAPE '~'

So I haven't tested it yet but it looks like potentially the ESCAPE '~' keyword may allow for automatic escaping of a string for use within a like expression.

How to add/subtract dates with JavaScript?

Something I am using (jquery needed), in my script I need it for the current day, but of course you can edit it accordingly.

HTML:

<label>Date:</label><input name="date" id="dateChange" type="date"/>
<input id="SubtractDay" type="button" value="-" />
<input id="AddDay" type="button" value="+" />

JavaScript:

    var counter = 0;

$("#SubtractDay").click(function() {
    counter--;
    var today = new Date();
    today.setDate(today.getDate() + counter);
    var formattedDate = new Date(today);
    var d = ("0" + formattedDate.getDate()).slice(-2);
    var m = ("0" + (formattedDate.getMonth() + 1)).slice(-2);
    var y = formattedDate.getFullYear();
    $("#dateChange").val(d + "/" + m + "/" + y);
});
$("#AddDay").click(function() {
    counter++;
    var today = new Date();
    today.setDate(today.getDate() + counter);
    var formattedDate = new Date(today);
    var d = ("0" + formattedDate.getDate()).slice(-2);
    var m = ("0" + (formattedDate.getMonth() + 1)).slice(-2);
    var y = formattedDate.getFullYear();
    $("#dateChange").val(d + "/" + m + "/" + y);
});

jsfiddle

Forbidden You don't have permission to access /wp-login.php on this server

Make sure your apache .conf files are correct -- then double check your .htaccess files. In this case, my .htaccess were incorrect! I removed some weird stuff no longer needed and it worked. Tada.

Checking if a folder exists using a .bat file

I think the answer is here (possibly duplicate):

How to test if a file is a directory in a batch script?

IF EXIST %VAR%\NUL ECHO It's a directory

Replace %VAR% with your directory. Please read the original answer because includes details about handling white spaces in the folder name.

As foxidrive said, this might not be reliable on NT class windows. It works for me, but I know it has some limitations (which you can find in the referenced question)

if exist "c:\folder\" echo folder exists 

should be enough for modern windows.

Could not resolve this reference. Could not locate the assembly

I had the same warning in VS 2017. As it turned out in my case I had added a unit test project and needed to set a dependency for the unit test on the DLL it was testing.

Zabbix server is not running: the information displayed may not be current

just get into the zabbix.conf.php

   >$sudo vim /etc/zabbix/web/zabbix.conf.php
   >$ZBX_SERVER      = '**your zabbix ip address or DNS name**';
   >$ZBX_SERVER_PORT = '10051';
   >$ZBX_SERVER_NAME = '**your zabbix hostname**';

just change the ip address you can resolve the error

Zabbix server is not running: the information displayed may not be current

After that restart the zabbix server

 >$sudo service zabbix-server restart

To verify go to Dashboard Administration -> queue there you see data

i resolved my error like this works fine for me.

What is the yield keyword used for in C#?

It is a very simple and easy way to create an enumerable for your object. The compiler creates a class that wraps your method and that implements, in this case, IEnumerable<object>. Without the yield keyword, you'd have to create an object that implements IEnumerable<object>.

Does C# have extension properties?

No they do not exist in C# 3.0 and will not be added in 4.0. It's on the list of feature wants for C# so it may be added at a future date.

At this point the best you can do is GetXXX style extension methods.

How to copy data from another workbook (excel)?

I don't think you need to select anything at all. I opened two blank workbooks Book1 and Book2, put the value "A" in Range("A1") of Sheet1 in Book2, and submitted the following code in the immediate window -

Workbooks(2).Worksheets(1).Range("A1").Copy Workbooks(1).Worksheets(1).Range("A1")

The Range("A1") in Sheet1 of Book1 now contains "A".

Also, given the fact that in your code you are trying to copy from the ActiveWorkbook to "myfile.xls", the order seems to be reversed as the Copy method should be applied to a range in the ActiveWorkbook, and the destination (argument to the Copy function) should be the appropriate range in "myfile.xls".

How to prevent ENTER keypress to submit a web form?

I've spent some time making this cross browser for IE8,9,10, Opera 9+, Firefox 23, Safari (PC) and Safari(MAC)

JSFiddle Example: http://jsfiddle.net/greatbigmassive/ZyeHe/

Base code - Call this function via "onkeypress" attached to your form and pass "window.event" into it.

function stopEnterSubmitting(e) {
    if (e.keyCode == 13) {
        var src = e.srcElement || e.target;
        if (src.tagName.toLowerCase() != "textarea") {
            if (e.preventDefault) {
                e.preventDefault();
            } else {
                e.returnValue = false;
            }
        }
    }
}

How to make primary key as autoincrement for Room Persistence lib

This works for me:

@Entity(tableName = "note_table")
data class Note(
    @ColumnInfo(name="title") var title: String,
    @ColumnInfo(name="description") var description: String = "",
    @ColumnInfo(name="priority") var priority: Int,
    @PrimaryKey(autoGenerate = true) var id: Int = 0//last so that we don't have to pass an ID value or named arguments
)

Note that the id is last to avoid having to use named arguments when creating the entity, before inserting it into Room. Once it's been added to room, use the id when updating the entity.

how to change text in Android TextView

The first line of new text view is unnecessary

t=new TextView(this); 

you can just do this

TextView t = (TextView)findViewById(R.id.TextView01);

as far as a background thread that sleeps here is an example, but I think there is a timer that would be better for this. here is a link to a good example using a timer instead http://android-developers.blogspot.com/2007/11/stitch-in-time.html

    Thread thr = new Thread(mTask);
    thr.start();
}

Runnable mTask = new Runnable() {
    public void run() {
        // just sleep for 30 seconds.
                    try {
                        Thread.sleep(3000);
                        runOnUiThread(done);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
        }
    };

    Runnable done = new Runnable() {
        public void run() {
                   // t.setText("done");
            }
        };

Convert integers to strings to create output filenames at run time

To convert an integer to a string:

integer :: i    
character* :: s    
if (i.LE.9) then
     s=char(48+i)    
else if (i.GE.10) then
     s=char(48+(i/10))// char(48-10*(i/10)+i)    
endif

What is a 'Closure'?

A closure is a function that can reference state in another function. For example, in Python, this uses the closure "inner":

def outer (a):
    b = "variable in outer()"
    def inner (c):
        print a, b, c
    return inner

# Now the return value from outer() can be saved for later
func = outer ("test")
func (1) # prints "test variable in outer() 1

Git - Ignore files during merge

Here git-update-index - Register file contents in the working tree to the index.

git update-index --assume-unchanged <PATH_OF_THE_FILE>

Example:-

git update-index --assume-unchanged somelocation/pom.xml

Changing background color of selected cell?

Swift 5.3

Here I did for a single row without creating a class for the cell.

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if let cell = tableView.cellForRow(at: indexPath) {
        cell.contentView.backgroundColor = #colorLiteral(red: 0.1411764771, green: 0.3960784376, blue: 0.5647059083, alpha: 1)
    }
}
override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    if let cell = tableView.cellForRow(at: indexPath) {
        cell.contentView.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
    }
}

error: This is probably not a problem with npm. There is likely additional logging output above

Following steps solves my problem: Add "C:\Windows\System32\" to your system path variables Run npm eject, Run npm start, Run npm eject, and agian run npm start And it worked

How to convert a plain object into an ES6 Map?

Yes, the Map constructor takes an array of key-value pairs.

Object.entries is a new Object static method available in ES2017 (19.1.2.5).

const map = new Map(Object.entries({foo: 'bar'}));

map.get('foo'); // 'bar'

It's currently implemented in Firefox 46+ and Edge 14+ and newer versions of Chrome

If you need to support older environments and transpilation is not an option for you, use a polyfill, such as the one recommended by georg:

Object.entries = typeof Object.entries === 'function' ? Object.entries : obj => Object.keys(obj).map(k => [k, obj[k]]);

How do I convert speech to text?

Dragon NaturallySpeaking seems to support MP3 input.

If you want an open source version (I think there are some Asterisk integration projects based on this one).

How to dismiss keyboard for UITextView with return key?

For Swift 3, this code allowed me to press outside of the UITextView to dismiss the keyboard.

@IBOutlet weak var comment: UITextView!

   override func viewDidLoad() {
        super.viewDidLoad()

        comment.delegate = self

        let tapGestureRecogniser = UITapGestureRecognizer(target: self, action: #selector(tap))
        view.addGestureRecognizer(tapGestureRecogniser)
    }

    func tap(sender: UITapGestureRecognizer) {
        if comment.isFirstResponder {
            comment.resignFirstResponder()
        }
    }

Tool for comparing 2 binary files in Windows

I prefer to use objcopy to convert to hex, then use diff.

Read the current full URL with React?

window.location.href is what you need. But also if you are using react router you might find useful checking out useLocation and useHistory hooks. Both create an object with a pathname attribute you can read and are useful for a bunch of other stuff. Here's a youtube video explaining react router hooks

Both will give you what you need (without the domain name):

import { useHistory ,useLocation } from 'react-router-dom';
const location = useLocation()
location.pathname

const history = useHistory()
history.location.pathname

How do I escape ampersands in XML so they are rendered as entities in HTML?

&amp; is the way to represent an ampersand in most sections of an XML document.

If you want to have XML displayed within HTML, you need to first create properly encoded XML (which involves changing & to &amp;) and then use that to create properly encoded HTML (which involves again changing & to &amp;). That results in:

&amp;amp;

For a more thorough explanation of XML encoding, see:

What characters do I need to escape in XML documents?

Typescript : Property does not exist on type 'object'

If your object could contain any key/value pairs, you could declare an interface called keyable like :

interface keyable {
    [key: string]: any  
}

then use it as follows :

let countryProviders: keyable[];

or

let countryProviders: Array<keyable>;

How to automatically generate N "distinct" colors?

Everyone seems to have missed the existence of the very useful YUV color space which was designed to represent perceived color differences in the human visual system. Distances in YUV represent differences in human perception. I needed this functionality for MagicCube4D which implements 4-dimensional Rubik's cubes and an unlimited numbers of other 4D twisty puzzles having arbitrary numbers of faces.

My solution starts by selecting random points in YUV and then iteratively breaking up the closest two points, and only converting to RGB when returning the result. The method is O(n^3) but that doesn't matter for small numbers or ones that can be cached. It can certainly be made more efficient but the results appear to be excellent.

The function allows for optional specification of brightness thresholds so as not to produce colors in which no component is brighter or darker than given amounts. IE you may not want values close to black or white. This is useful when the resulting colors will be used as base colors that are later shaded via lighting, layering, transparency, etc. and must still appear different from their base colors.

import java.awt.Color;
import java.util.Random;

/**
 * Contains a method to generate N visually distinct colors and helper methods.
 * 
 * @author Melinda Green
 */
public class ColorUtils {
    private ColorUtils() {} // To disallow instantiation.
    private final static float
        U_OFF = .436f,
        V_OFF = .615f;
    private static final long RAND_SEED = 0;
    private static Random rand = new Random(RAND_SEED);    

    /*
     * Returns an array of ncolors RGB triplets such that each is as unique from the rest as possible
     * and each color has at least one component greater than minComponent and one less than maxComponent.
     * Use min == 1 and max == 0 to include the full RGB color range.
     * 
     * Warning: O N^2 algorithm blows up fast for more than 100 colors.
     */
    public static Color[] generateVisuallyDistinctColors(int ncolors, float minComponent, float maxComponent) {
        rand.setSeed(RAND_SEED); // So that we get consistent results for each combination of inputs

        float[][] yuv = new float[ncolors][3];

        // initialize array with random colors
        for(int got = 0; got < ncolors;) {
            System.arraycopy(randYUVinRGBRange(minComponent, maxComponent), 0, yuv[got++], 0, 3);
        }
        // continually break up the worst-fit color pair until we get tired of searching
        for(int c = 0; c < ncolors * 1000; c++) {
            float worst = 8888;
            int worstID = 0;
            for(int i = 1; i < yuv.length; i++) {
                for(int j = 0; j < i; j++) {
                    float dist = sqrdist(yuv[i], yuv[j]);
                    if(dist < worst) {
                        worst = dist;
                        worstID = i;
                    }
                }
            }
            float[] best = randYUVBetterThan(worst, minComponent, maxComponent, yuv);
            if(best == null)
                break;
            else
                yuv[worstID] = best;
        }

        Color[] rgbs = new Color[yuv.length];
        for(int i = 0; i < yuv.length; i++) {
            float[] rgb = new float[3];
            yuv2rgb(yuv[i][0], yuv[i][1], yuv[i][2], rgb);
            rgbs[i] = new Color(rgb[0], rgb[1], rgb[2]);
            //System.out.println(rgb[i][0] + "\t" + rgb[i][1] + "\t" + rgb[i][2]);
        }

        return rgbs;
    }

    public static void hsv2rgb(float h, float s, float v, float[] rgb) {
        // H is given on [0->6] or -1. S and V are given on [0->1]. 
        // RGB are each returned on [0->1]. 
        float m, n, f;
        int i;

        float[] hsv = new float[3];

        hsv[0] = h;
        hsv[1] = s;
        hsv[2] = v;
        System.out.println("H: " + h + " S: " + s + " V:" + v);
        if(hsv[0] == -1) {
            rgb[0] = rgb[1] = rgb[2] = hsv[2];
            return;
        }
        i = (int) (Math.floor(hsv[0]));
        f = hsv[0] - i;
        if(i % 2 == 0)
            f = 1 - f; // if i is even 
        m = hsv[2] * (1 - hsv[1]);
        n = hsv[2] * (1 - hsv[1] * f);
        switch(i) {
            case 6:
            case 0:
                rgb[0] = hsv[2];
                rgb[1] = n;
                rgb[2] = m;
                break;
            case 1:
                rgb[0] = n;
                rgb[1] = hsv[2];
                rgb[2] = m;
                break;
            case 2:
                rgb[0] = m;
                rgb[1] = hsv[2];
                rgb[2] = n;
                break;
            case 3:
                rgb[0] = m;
                rgb[1] = n;
                rgb[2] = hsv[2];
                break;
            case 4:
                rgb[0] = n;
                rgb[1] = m;
                rgb[2] = hsv[2];
                break;
            case 5:
                rgb[0] = hsv[2];
                rgb[1] = m;
                rgb[2] = n;
                break;
        }
    }


    // From http://en.wikipedia.org/wiki/YUV#Mathematical_derivations_and_formulas
    public static void yuv2rgb(float y, float u, float v, float[] rgb) {
        rgb[0] = 1 * y + 0 * u + 1.13983f * v;
        rgb[1] = 1 * y + -.39465f * u + -.58060f * v;
        rgb[2] = 1 * y + 2.03211f * u + 0 * v;
    }

    public static void rgb2yuv(float r, float g, float b, float[] yuv) {
        yuv[0] = .299f * r + .587f * g + .114f * b;
        yuv[1] = -.14713f * r + -.28886f * g + .436f * b;
        yuv[2] = .615f * r + -.51499f * g + -.10001f * b;
    }

    private static float[] randYUVinRGBRange(float minComponent, float maxComponent) {
        while(true) {
            float y = rand.nextFloat(); // * YFRAC + 1-YFRAC);
            float u = rand.nextFloat() * 2 * U_OFF - U_OFF;
            float v = rand.nextFloat() * 2 * V_OFF - V_OFF;
            float[] rgb = new float[3];
            yuv2rgb(y, u, v, rgb);
            float r = rgb[0], g = rgb[1], b = rgb[2];
            if(0 <= r && r <= 1 &&
                0 <= g && g <= 1 &&
                0 <= b && b <= 1 &&
                (r > minComponent || g > minComponent || b > minComponent) && // don't want all dark components
                (r < maxComponent || g < maxComponent || b < maxComponent)) // don't want all light components

                return new float[]{y, u, v};
        }
    }

    private static float sqrdist(float[] a, float[] b) {
        float sum = 0;
        for(int i = 0; i < a.length; i++) {
            float diff = a[i] - b[i];
            sum += diff * diff;
        }
        return sum;
    }

    private static double worstFit(Color[] colors) {
        float worst = 8888;
        float[] a = new float[3], b = new float[3];
        for(int i = 1; i < colors.length; i++) {
            colors[i].getColorComponents(a);
            for(int j = 0; j < i; j++) {
                colors[j].getColorComponents(b);
                float dist = sqrdist(a, b);
                if(dist < worst) {
                    worst = dist;
                }
            }
        }
        return Math.sqrt(worst);
    }

    private static float[] randYUVBetterThan(float bestDistSqrd, float minComponent, float maxComponent, float[][] in) {
        for(int attempt = 1; attempt < 100 * in.length; attempt++) {
            float[] candidate = randYUVinRGBRange(minComponent, maxComponent);
            boolean good = true;
            for(int i = 0; i < in.length; i++)
                if(sqrdist(candidate, in[i]) < bestDistSqrd)
                    good = false;
            if(good)
                return candidate;
        }
        return null; // after a bunch of passes, couldn't find a candidate that beat the best.
    }


    /**
     * Simple example program.
     */
    public static void main(String[] args) {
        final int ncolors = 10;
        Color[] colors = generateVisuallyDistinctColors(ncolors, .8f, .3f);
        for(int i = 0; i < colors.length; i++) {
            System.out.println(colors[i].toString());
        }
        System.out.println("Worst fit color = " + worstFit(colors));
    }

}

How do DATETIME values work in SQLite?

SQlite does not have a specific datetime type. You can use TEXT, REAL or INTEGER types, whichever suits your needs.

Straight from the DOCS

SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values:

  • TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS").
  • REAL as Julian day numbers, the number of days since noon in Greenwich on November 24, 4714 B.C. according to the proleptic Gregorian calendar.
  • INTEGER as Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC.

Applications can chose to store dates and times in any of these formats and freely convert between formats using the built-in date and time functions.

SQLite built-in Date and Time functions can be found here.

Resolve host name to an ip address

Try tracert to resolve the hostname. IE you have Ip address 8.8.8.8 so you would use; tracert 8.8.8.8

Javascript + Regex = Nothing to repeat error?

You need to double the backslashes used to escape the regular expression special characters. However, as @Bohemian points out, most of those backslashes aren't needed. Unfortunately, his answer suffers from the same problem as yours. What you actually want is:

The backslash is being interpreted by the code that reads the string, rather than passed to the regular expression parser. You want:

"[\\[\\]?*+|{}\\\\()@.\n\r]"

Note the quadrupled backslash. That is definitely needed. The string passed to the regular expression compiler is then identical to @Bohemian's string, and works correctly.

Updating GUI (WPF) using a different thread

As akjoshi and Julio say this is about dispatching an Action to update the GUI on the same thread as the GUI item but from the method that is handling the background data. You can see this code in specific form in akjoshi's answer above. This is a general version.

myTextBlock.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                                   new Action(delegate() 
                                      {
                                      myTextBlock.Text = Convert.ToString(myDataObject.getMeData());
                                      }));

The critical part is to call the dispatcher of your UI object - that ensures you have the correct thread.

From personal experience it seems much easier to create and use the Action inline like this. Declaring it at class level gave me lots of problems with static/non-static contexts.

Difference between a Seq and a List in Scala

In Java terms, Scala's Seq would be Java's List, and Scala's List would be Java's LinkedList.

Note that Seq is a trait, which is equivalent to Java's interface, but with the equivalent of up-and-coming defender methods. Scala's List is an abstract class that is extended by Nil and ::, which are the concrete implementations of List.

So, where Java's List is an interface, Scala's List is an implementation.

Beyond that, Scala's List is immutable, which is not the case of LinkedList. In fact, Java has no equivalent to immutable collections (the read only thing only guarantees the new object cannot be changed, but you still can change the old one, and, therefore, the "read only" one).

Scala's List is highly optimized by compiler and libraries, and it's a fundamental data type in functional programming. However, it has limitations and it's inadequate for parallel programming. These days, Vector is a better choice than List, but habit is hard to break.

Seq is a good generalization for sequences, so if you program to interfaces, you should use that. Note that there are actually three of them: collection.Seq, collection.mutable.Seq and collection.immutable.Seq, and it is the latter one that is the "default" imported into scope.

There's also GenSeq and ParSeq. The latter methods run in parallel where possible, while the former is parent to both Seq and ParSeq, being a suitable generalization for when parallelism of a code doesn't matter. They are both relatively newly introduced, so people doesn't use them much yet.

Using Ansible set_fact to create a dictionary from register results

I think I got there in the end.

The task is like this:

- name: Populate genders
  set_fact:
    genders: "{{ genders|default({}) | combine( {item.item.name: item.stdout} ) }}"
  with_items: "{{ people.results }}"

It loops through each of the dicts (item) in the people.results array, each time creating a new dict like {Bob: "male"}, and combine()s that new dict in the genders array, which ends up like:

{
    "Bob": "male",
    "Thelma": "female"
}

It assumes the keys (the name in this case) will be unique.


I then realised I actually wanted a list of dictionaries, as it seems much easier to loop through using with_items:

- name: Populate genders
  set_fact:
    genders: "{{ genders|default([]) + [ {'name': item.item.name, 'gender': item.stdout} ] }}"
  with_items: "{{ people.results }}"

This keeps combining the existing list with a list containing a single dict. We end up with a genders array like this:

[
    {'name': 'Bob', 'gender': 'male'},
    {'name': 'Thelma', 'gender': 'female'}
]

Regex doesn't work in String.matches()

Your regular expression [a-z] doesn't match dkoe since it only matches Strings of lenght 1. Use something like [a-z]+.

Select by partial string from a pandas DataFrame

There are answers before this which accomplish the asked feature, anyway I would like to show the most generally way:

df.filter(regex=".*STRING_YOU_LOOK_FOR.*")

This way let's you get the column you look for whatever the way is wrote.

( Obviusly, you have to write the proper regex expression for each case )

Laravel - Pass more than one variable to view

Passing multiple variables to a Laravel view

//Passing variable to view using compact method    
$var1=value1;
$var2=value2;
$var3=value3;
return view('viewName', compact('var1','var2','var3'));

//Passing variable to view using with Method
return view('viewName')->with(['var1'=>value1,'var2'=>value2,'var3'=>'value3']);

//Passing variable to view using Associative Array
return view('viewName', ['var1'=>value1,'var2'=>value2,'var3'=>value3]);

Read here about Passing Data to Views in Laravel

How to get WooCommerce order details

WOOCOMMERCE ORDERS IN VERSION 3.0+

Since Woocommerce mega major Update 3.0+ things have changed quite a lot:

Related:
How to get Customer details from Order in WooCommerce?
Get Order items and WC_Order_Item_Product in WooCommerce 3

So the Order items properties will not be accessible as before in a foreach loop and you will have to use these specific getter and setter methods instead.

Using some WC_Order and WC_Abstract_Order methods (example):

// Get an instance of the WC_Order object (same as before)
$order = wc_get_order( $order_id );

$order_id  = $order->get_id(); // Get the order ID
$parent_id = $order->get_parent_id(); // Get the parent order ID (for subscriptions…)

$user_id   = $order->get_user_id(); // Get the costumer ID
$user      = $order->get_user(); // Get the WP_User object

$order_status  = $order->get_status(); // Get the order status (see the conditional method has_status() below)
$currency      = $order->get_currency(); // Get the currency used  
$payment_method = $order->get_payment_method(); // Get the payment method ID
$payment_title = $order->get_payment_method_title(); // Get the payment method title
$date_created  = $order->get_date_created(); // Get date created (WC_DateTime object)
$date_modified = $order->get_date_modified(); // Get date modified (WC_DateTime object)

$billing_country = $order->get_billing_country(); // Customer billing country

// ... and so on ...

For order status as a conditional method (where "the_targeted_status" need to be defined and replaced by an order status to target a specific order status):

if ( $order->has_status('completed') ) {
    // Do something
}

Get and access to the order data properties (in an array of values):

// Get an instance of the WC_Order object
$order = wc_get_order( $order_id );

$order_data = $order->get_data(); // The Order data

$order_id = $order_data['id'];
$order_parent_id = $order_data['parent_id'];
$order_status = $order_data['status'];
$order_currency = $order_data['currency'];
$order_version = $order_data['version'];
$order_payment_method = $order_data['payment_method'];
$order_payment_method_title = $order_data['payment_method_title'];
$order_payment_method = $order_data['payment_method'];
$order_payment_method = $order_data['payment_method'];

## Creation and modified WC_DateTime Object date string ##

// Using a formated date ( with php date() function as method)
$order_date_created = $order_data['date_created']->date('Y-m-d H:i:s');
$order_date_modified = $order_data['date_modified']->date('Y-m-d H:i:s');

// Using a timestamp ( with php getTimestamp() function as method)
$order_timestamp_created = $order_data['date_created']->getTimestamp();
$order_timestamp_modified = $order_data['date_modified']->getTimestamp();

$order_discount_total = $order_data['discount_total'];
$order_discount_tax = $order_data['discount_tax'];
$order_shipping_total = $order_data['shipping_total'];
$order_shipping_tax = $order_data['shipping_tax'];
$order_total = $order_data['total'];
$order_total_tax = $order_data['total_tax'];
$order_customer_id = $order_data['customer_id']; // ... and so on

## BILLING INFORMATION:

$order_billing_first_name = $order_data['billing']['first_name'];
$order_billing_last_name = $order_data['billing']['last_name'];
$order_billing_company = $order_data['billing']['company'];
$order_billing_address_1 = $order_data['billing']['address_1'];
$order_billing_address_2 = $order_data['billing']['address_2'];
$order_billing_city = $order_data['billing']['city'];
$order_billing_state = $order_data['billing']['state'];
$order_billing_postcode = $order_data['billing']['postcode'];
$order_billing_country = $order_data['billing']['country'];
$order_billing_email = $order_data['billing']['email'];
$order_billing_phone = $order_data['billing']['phone'];

## SHIPPING INFORMATION:

$order_shipping_first_name = $order_data['shipping']['first_name'];
$order_shipping_last_name = $order_data['shipping']['last_name'];
$order_shipping_company = $order_data['shipping']['company'];
$order_shipping_address_1 = $order_data['shipping']['address_1'];
$order_shipping_address_2 = $order_data['shipping']['address_2'];
$order_shipping_city = $order_data['shipping']['city'];
$order_shipping_state = $order_data['shipping']['state'];
$order_shipping_postcode = $order_data['shipping']['postcode'];
$order_shipping_country = $order_data['shipping']['country'];

Get the order items and access the data with WC_Order_Item_Product and WC_Order_Item methods:

// Get an instance of the WC_Order object
$order = wc_get_order($order_id);

// Iterating through each WC_Order_Item_Product objects
foreach ($order->get_items() as $item_key => $item ):

    ## Using WC_Order_Item methods ##

    // Item ID is directly accessible from the $item_key in the foreach loop or
    $item_id = $item->get_id();

    ## Using WC_Order_Item_Product methods ##

    $product      = $item->get_product(); // Get the WC_Product object

    $product_id   = $item->get_product_id(); // the Product id
    $variation_id = $item->get_variation_id(); // the Variation id

    $item_type    = $item->get_type(); // Type of the order item ("line_item")

    $item_name    = $item->get_name(); // Name of the product
    $quantity     = $item->get_quantity();  
    $tax_class    = $item->get_tax_class();
    $line_subtotal     = $item->get_subtotal(); // Line subtotal (non discounted)
    $line_subtotal_tax = $item->get_subtotal_tax(); // Line subtotal tax (non discounted)
    $line_total        = $item->get_total(); // Line total (discounted)
    $line_total_tax    = $item->get_total_tax(); // Line total tax (discounted)

    ## Access Order Items data properties (in an array of values) ##
    $item_data    = $item->get_data();

    $product_name = $item_data['name'];
    $product_id   = $item_data['product_id'];
    $variation_id = $item_data['variation_id'];
    $quantity     = $item_data['quantity'];
    $tax_class    = $item_data['tax_class'];
    $line_subtotal     = $item_data['subtotal'];
    $line_subtotal_tax = $item_data['subtotal_tax'];
    $line_total        = $item_data['total'];
    $line_total_tax    = $item_data['total_tax'];

    // Get data from The WC_product object using methods (examples)
    $product        = $item->get_product(); // Get the WC_Product object

    $product_type   = $product->get_type();
    $product_sku    = $product->get_sku();
    $product_price  = $product->get_price();
    $stock_quantity = $product->get_stock_quantity();

endforeach;

So using get_data() method allow us to access to the protected data (associative array mode) …

VBA EXCEL Multiple Nested FOR Loops that Set two variable for expression

I can't get to your google docs file at the moment but there are some issues with your code that I will try to address while answering

Sub stituterangersNEW()
Dim t As Range
Dim x As Range
Dim dify As Boolean
Dim difx As Boolean
Dim time2 As Date
Dim time1 As Date

    'You said time1 doesn't change, so I left it in a singe cell.
    'If that is not correct, you will have to play with this some more.
    time1 = Range("A6").Value

    'Looping through each of our output cells.
    For Each t In Range("B7:E9") 'Change these to match your real ranges.

        'Looping through each departure date/time.
        '(Only one row in your example. This can be adjusted if needed.)
        For Each x In Range("B2:E2") 'Change these to match your real ranges.
            'Check to see if our dep time corresponds to
            'the matching column in our output
            If t.Column = x.Column Then
                'If it does, then check to see what our time value is
                If x > 0 Then
                    time2 = x.Value
                    'Apply the change to the output cell.
                    t.Value = time1 - time2
                    'Exit out of this loop and move to the next output cell.
                    Exit For
                End If
            End If
            'If the columns don't match, or the x value is not a time
            'then we'll move to the next dep time (x)
        Next x
    Next t

End Sub

EDIT

I changed you worksheet to play with (see above for the new Sub). This probably does not suite your needs directly, but hopefully it will demonstrate the conept behind what I think you want to do. Please keep in mind that this code does not follow all the coding best preactices I would recommend (e.g. validating the time is actually a TIME and not some random other data type).

     A                      B                   C                   D                  E
1    LOAD_NUMBER            1                   2                   3                  4
2    DEPARTURE_TIME_DATE    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 20:00                
4    Dry_Refrig 7585.1  0   10099.8 16700
6    1/4/2012 19:30

Using the sub I got this output:

    A           B             C             D             E
7   Friday      1272:00:00    1272:00:00    1272:00:00    1271:30:00
8   Saturday    1272:00:00    1272:00:00    1272:00:00    1271:30:00
9   Thursday    1272:00:00    1272:00:00    1272:00:00    1271:30:00

Basic HTTP authentication with Node and Express 4

Express has removed this functionality and now recommends you use the basic-auth library.

Here's an example of how to use:

var http = require('http')
var auth = require('basic-auth')

// Create server
var server = http.createServer(function (req, res) {
  var credentials = auth(req)

  if (!credentials || credentials.name !== 'aladdin' || credentials.pass !== 'opensesame') {
    res.statusCode = 401
    res.setHeader('WWW-Authenticate', 'Basic realm="example"')
    res.end('Access denied')
  } else {
    res.end('Access granted')
  }
})

// Listen
server.listen(3000)

To send a request to this route you need to include an Authorization header formatted for basic auth.

Sending a curl request first you must take the base64 encoding of name:pass or in this case aladdin:opensesame which is equal to YWxhZGRpbjpvcGVuc2VzYW1l

Your curl request will then look like:

 curl -H "Authorization: Basic YWxhZGRpbjpvcGVuc2VzYW1l" http://localhost:3000/

How to get the mysql table columns data type?

Most answers are duplicates, it might be useful to group them. Basically two simple options have been proposed.

First option

The first option has 4 different aliases, some of which are quite short :

EXPLAIN db_name.table_name;
DESCRIBE db_name.table_name;
SHOW FIELDS FROM db_name.table_name;
SHOW COLUMNS FROM db_name.table_name;

(NB : as an alternative to db_name.table_name, one can use a second FROM : db_name FROM table_name).

This gives something like :

+------------------+--------------+------+-----+---------+-------+
| Field            | Type         | Null | Key | Default | Extra |
+------------------+--------------+------+-----+---------+-------+
| product_id       | int(11)      | NO   | PRI | NULL    |       |
| name             | varchar(255) | NO   | MUL | NULL    |       |
| description      | text         | NO   |     | NULL    |       |
| meta_title       | varchar(255) | NO   |     | NULL    |       |
+------------------+--------------+------+-----+---------+-------+

Second option

The second option is a bit longer :

SELECT
  COLUMN_NAME, DATA_TYPE 
FROM
  INFORMATION_SCHEMA.COLUMNS 
WHERE
  TABLE_SCHEMA = 'db_name'
AND
  TABLE_NAME = 'table_name';

It is also less talkative :

+------------------+-----------+
| column_name      | DATA_TYPE |
+------------------+-----------+
| product_id       | int       |
| name             | varchar   |
| description      | text      |
| meta_title       | varchar   |
+------------------+-----------+

It has the advantage of allowing selection per column, though, using AND COLUMN_NAME = 'column_name' (or like).

how to call scalar function in sql server 2008

For some reason I was not able to use my scalar function until I referenced it using brackets, like so:

select [dbo].[fun_functional_score]('01091400003')

Add items to comboBox in WPF

I think comboBox1.Items.Add("X"); will add string to ComboBox, instead of ComboBoxItem.

The right solution is

ComboBoxItem item = new ComboBoxItem();
item.Content = "A";
comboBox1.Items.Add(item);

How to change the Text color of Menu item in Android?

For changing the text color, you can just set a custom view for the MenuItem, and then you can define the color for the text.

Sample Code : MenuItem.setActionView()

invalid command code ., despite escaping periods, using sed

If you are on a OS X, this probably has nothing to do with the sed command. On the OSX version of sed, the -i option expects an extension argument so your command is actually parsed as the extension argument and the file path is interpreted as the command code.

Try adding the -e argument explicitly and giving '' as argument to -i:

find ./ -type f -exec sed -i '' -e "s/192.168.20.1/new.domain.com/" {} \;

See this.

Seaborn plots not showing up

To avoid confusion (as there seems to be some in the comments). Assuming you are on Jupyter:

%matplotlib inline > displays the plots INSIDE the notebook

sns.plt.show() > displays the plots OUTSIDE of the notebook

%matplotlib inline will OVERRIDE sns.plt.show() in the sense that plots will be shown IN the notebook even when sns.plt.show() is called.

And yes, it is easy to include the line in to your config:

Automatically run %matplotlib inline in IPython Notebook

But it seems a better convention to keep it together with imports in the actual code.

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.

How to change the default port of mysql from 3306 to 3360

try changing the connection port to 8012

open xampp as administrator

Mysql config => my.ini change the port from 3306 to 8012

close and run it again I hope it will work.

Convert Current date to integer

Try This

Calendar currentDay= Calendar.getInstance();
int currDate= currentDay.get(Calendar.DATE);
int currMonth= currentDay.get(Calendar.MONTH);
int currYear= currentDay.get(Calendar.YEAR);
System.out.println(currDate + "-" +  currMonth + "-" + currYear);

an alternative way using LocalDate.

LocalDate today = LocalDate.now();
int currentDate= today.getDayOfMonth();
int currentMonth= today.getMonthValue();
int currentYear= today.getYear()

Create a list from two object lists with linq

You need something like a full outer join. System.Linq.Enumerable has no method that implements a full outer join, so we have to do it ourselves.

var dict1 = list1.ToDictionary(l1 => l1.Name);
var dict2 = list2.ToDictionary(l2 => l2.Name);
    //get the full list of names.
var names = dict1.Keys.Union(dict2.Keys).ToList();
    //produce results
var result = names
.Select( name =>
{
  Person p1 = dict1.ContainsKey(name) ? dict1[name] : null;
  Person p2 = dict2.ContainsKey(name) ? dict2[name] : null;
      //left only
  if (p2 == null)
  {
    p1.Change = 0;
    return p1;
  }
      //right only
  if (p1 == null)
  {
    p2.Change = 0;
    return p2;
  }
      //both
  p2.Change = p2.Value - p1.Value;
  return p2;
}).ToList();

getElementsByClassName not working

If you want to do it by ClassName you could do:

<script type="text/javascript">
function hideTd(className){
    var elements;

    if (document.getElementsByClassName)
    {
        elements = document.getElementsByClassName(className);
    }
    else
    {
        var elArray = [];
        var tmp = document.getElementsByTagName(elements);  
        var regex = new RegExp("(^|\\s)" + className+ "(\\s|$)");
        for ( var i = 0; i < tmp.length; i++ ) {

            if ( regex.test(tmp[i].className) ) {
                elArray.push(tmp[i]);
            }
        }

        elements = elArray;
    }

    for(var i = 0, i < elements.length; i++) {
       if( elements[i].textContent == ''){
          elements[i].style.display = 'none';
       } 
    }

  }
</script>

How to show DatePickerDialog on Button click?

it works for me. if you want to enable future time for choose, you have to delete maximum date. You need to to do like followings.

 btnDate.setOnClickListener(new View.OnClickListener() {
                       @Override
                       public void onClick(View v) {
                              DialogFragment newFragment = new DatePickerFragment();
                                    newFragment.show(getSupportFragmentManager(), "datePicker");
                            }
                        });

            public static class DatePickerFragment extends DialogFragment
                        implements DatePickerDialog.OnDateSetListener {

                    @Override
                    public Dialog onCreateDialog(Bundle savedInstanceState) {
                        final Calendar c = Calendar.getInstance();
                        int year = c.get(Calendar.YEAR);
                        int month = c.get(Calendar.MONTH);
                        int day = c.get(Calendar.DAY_OF_MONTH);
                        DatePickerDialog dialog = new DatePickerDialog(getActivity(), this, year, month, day);
                        dialog.getDatePicker().setMaxDate(c.getTimeInMillis());
                        return  dialog;
                    }

                    public void onDateSet(DatePicker view, int year, int month, int day) {
                       btnDate.setText(ConverterDate.ConvertDate(year, month + 1, day));
                    }
                }

What are the differences between stateless and stateful systems, and how do they impact parallelism?

A stateful server keeps state between connections. A stateless server does not.

So, when you send a request to a stateful server, it may create some kind of connection object that tracks what information you request. When you send another request, that request operates on the state from the previous request. So you can send a request to "open" something. And then you can send a request to "close" it later. In-between the two requests, that thing is "open" on the server.

When you send a request to a stateless server, it does not create any objects that track information regarding your requests. If you "open" something on the server, the server retains no information at all that you have something open. A "close" operation would make no sense, since there would be nothing to close.

HTTP and NFS are stateless protocols. Each request stands on its own.

Sometimes cookies are used to add some state to a stateless protocol. In HTTP (web pages), the server sends you a cookie and then the browser holds the state, only to send it back to the server on a subsequent request.

SMB is a stateful protocol. A client can open a file on the server, and the server may deny other clients access to that file until the client closes it.

How to iterate over associative arrays in Bash

Use this higher order function to prevent the pyramid of doom

foreach(){ 
  arr="$(declare -p $1)" ; eval "declare -A f="${arr#*=}; 
  for i in ${!f[@]}; do $2 "$i" "${f[$i]}"; done
}

example:

$ bar(){ echo "$1 -> $2"; }
$ declare -A foo["flap"]="three four" foo["flop"]="one two"
$ foreach foo bar
flap -> three four
flop -> one two

how to count the total number of lines in a text file using python

here is how you can do it through list comprehension, but this will waste a little bit of your computer's memory as line.strip() has been called twice.

     with open('textfile.txt') as file:
lines =[
            line.strip()
            for line in file
             if line.strip() != '']
print("number of lines =  {}".format(len(lines)))

REST API Token-based Authentication

Let me seperate up everything and solve approach each problem in isolation:

Authentication

For authentication, baseauth has the advantage that it is a mature solution on the protocol level. This means a lot of "might crop up later" problems are already solved for you. For example, with BaseAuth, user agents know the password is a password so they don't cache it.

Auth server load

If you dispense a token to the user instead of caching the authentication on your server, you are still doing the same thing: Caching authentication information. The only difference is that you are turning the responsibility for the caching to the user. This seems like unnecessary labor for the user with no gains, so I recommend to handle this transparently on your server as you suggested.

Transmission Security

If can use an SSL connection, that's all there is to it, the connection is secure*. To prevent accidental multiple execution, you can filter multiple urls or ask users to include a random component ("nonce") in the URL.

url = username:[email protected]/api/call/nonce

If that is not possible, and the transmitted information is not secret, I recommend securing the request with a hash, as you suggested in the token approach. Since the hash provides the security, you could instruct your users to provide the hash as the baseauth password. For improved robustness, I recommend using a random string instead of the timestamp as a "nonce" to prevent replay attacks (two legit requests could be made during the same second). Instead of providing seperate "shared secret" and "api key" fields, you can simply use the api key as shared secret, and then use a salt that doesn't change to prevent rainbow table attacks. The username field seems like a good place to put the nonce too, since it is part of the auth. So now you have a clean call like this:

nonce = generate_secure_password(length: 16);
one_time_key = nonce + '-' + sha1(nonce+salt+shared_key);
url = username:[email protected]/api/call

It is true that this is a bit laborious. This is because you aren't using a protocol level solution (like SSL). So it might be a good idea to provide some kind of SDK to users so at least they don't have to go through it themselves. If you need to do it this way, I find the security level appropriate (just-right-kill).

Secure secret storage

It depends who you are trying to thwart. If you are preventing people with access to the user's phone from using your REST service in the user's name, then it would be a good idea to find some kind of keyring API on the target OS and have the SDK (or the implementor) store the key there. If that's not possible, you can at least make it a bit harder to get the secret by encrypting it, and storing the encrypted data and the encryption key in seperate places.

If you are trying to keep other software vendors from getting your API key to prevent the development of alternate clients, only the encrypt-and-store-seperately approach almost works. This is whitebox crypto, and to date, no one has come up with a truly secure solution to problems of this class. The least you can do is still issue a single key for each user so you can ban abused keys.

(*) EDIT: SSL connections should no longer be considered secure without taking additional steps to verify them.

MySQL select query with multiple conditions

I would use this query:

SELECT
  user_id
FROM
  wp_usermeta 
WHERE 
  (meta_key = 'first_name' AND meta_value = '$us_name') OR 
  (meta_key = 'yearofpassing' AND meta_value = '$us_yearselect') OR 
  (meta_key = 'u_city' AND meta_value = '$us_reg') OR
  (meta_key = 'us_course' AND meta_value = '$us_course')
GROUP BY
  user_id
HAVING
  COUNT(DISTINCT meta_key)=4

this will select all user_id that meets all four conditions.

"Unable to locate tools.jar" when running ant

Make sure you use the root folder of the JDK. Don't add "\lib" to the end of the path, where tools.jar is physically located. It took me an hour to figure that one out. Also, this post will help show you where Ant is looking for tools.jar:

Why does ANT tell me that JAVA_HOME is wrong when it is not?

Relative div height

add this to you CSS:

html, body
{
    height: 100%;
}

working Fiddle

when you say to wrap to be 100%, 100% of what? of its parent (body), so his parent has to have some height.

and the same goes for body, his parent his html. html parent his the viewport.. so, by setting them both to 100%, wrap can also have a percentage height.

also: the elements have some default padding/margin, that causes them to span a little more then the height you applied to them. (causing a scroll bar) you can use

*
{
    padding: 0;
    margin: 0;
}

to disable that.

Look at That Fiddle

What does 'x packages are looking for funding' mean when running `npm install`?

These are Open Source projects (or developers) which can use donations to fund to help support their business.

In npm the command npm fund will list the urls where you can fund

In composer the command composer fund will do the same.

While there are options mentioned above using which one can use to get rid of the funding message, but try to support the cause if you can.

To enable extensions, verify that they are enabled in those .ini files - Vagrant/Ubuntu/Magento 2.0.2

This was the fix for me when trying to install Laravel on a fresh WSL installation:

sudo apt-get install php7.2-gd

sudo apt-get install php7.2-intl

sudo apt-get install php7.2-xsl

sudo apt-get install php7.2-zip

javascript filter array multiple conditions

You can do like this

_x000D_
_x000D_
var filter = {_x000D_
  address: 'England',_x000D_
  name: 'Mark'_x000D_
};_x000D_
var users = [{_x000D_
    name: 'John',_x000D_
    email: '[email protected]',_x000D_
    age: 25,_x000D_
    address: 'USA'_x000D_
  },_x000D_
  {_x000D_
    name: 'Tom',_x000D_
    email: '[email protected]',_x000D_
    age: 35,_x000D_
    address: 'England'_x000D_
  },_x000D_
  {_x000D_
    name: 'Mark',_x000D_
    email: '[email protected]',_x000D_
    age: 28,_x000D_
    address: 'England'_x000D_
  }_x000D_
];_x000D_
_x000D_
_x000D_
users= users.filter(function(item) {_x000D_
  for (var key in filter) {_x000D_
    if (item[key] === undefined || item[key] != filter[key])_x000D_
      return false;_x000D_
  }_x000D_
  return true;_x000D_
});_x000D_
_x000D_
console.log(users)
_x000D_
_x000D_
_x000D_

How to pass a querystring or route parameter to AWS Lambda from Amazon API Gateway

In order to pass parameters to your lambda function you need to create a mapping between the API Gateway request and your lambda function. The mapping is done in the Integration Request -> Mapping templates section of the selected API Gateway resource.

Create a mapping of type application/json, then on the right you will edit (click the pencil) the template.

A mapping template is actually a Velocity template where you can use ifs, loops and of course print variables on it. The template has these variables injected where you can access querystring parameters, request headers, etc. individually. With the following code you can re-create the whole querystring:

{
    "querystring" : "#foreach($key in $input.params().querystring.keySet())#if($foreach.index > 0)&#end$util.urlEncode($key)=$util.urlEncode($input.params().querystring.get($key))#end",
    "body" : $input.json('$')
}

Note: click on the check symbol to save the template. You can test your changes with the "test" button in your resource. But in order to test querystring parameters in the AWS console you will need to define the parameter names in the Method Request section of your resource.

Note: check the Velocity User Guide for more information about the Velocity templating language.

Then in your lambda template you can do the following to get the querystring parsed:

var query = require('querystring').parse(event.querystring)
// access parameters with query['foo'] or query.foo

How to avoid precompiled headers

The .cpp file is configured to use precompiled header, therefore it must be included first (before iostream). For Visual Studio, it's name is usually "stdafx.h".

If there are no stdafx* files in your project, you need to go to this file's options and set it as “Not using precompiled headers”.

How do I check if an HTML element is empty using jQuery?

Here's a jQuery filter based on https://stackoverflow.com/a/6813294/698289

$.extend($.expr[':'], {
  trimmedEmpty: function(el) {
    return !$.trim($(el).html());
  }
});

How to set the font style to bold, italic and underlined in an Android TextView?

This should make your TextView bold, underlined and italic at the same time.

strings.xml

<resources>
    <string name="register"><u><b><i>Copyright</i></b></u></string>
</resources>

To set this String to your TextView, do this in your main.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/textview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:text="@string/register" />

or In JAVA,

TextView textView = new TextView(this);
textView.setText(R.string.register);

Sometimes the above approach will not be helpful when you might have to use Dynamic Text. So in that case SpannableString comes into action.

String tempString="Copyright";
TextView text=(TextView)findViewById(R.id.text);
SpannableString spanString = new SpannableString(tempString);
spanString.setSpan(new UnderlineSpan(), 0, spanString.length(), 0);
spanString.setSpan(new StyleSpan(Typeface.BOLD), 0, spanString.length(), 0);
spanString.setSpan(new StyleSpan(Typeface.ITALIC), 0, spanString.length(), 0);
text.setText(spanString);

OUTPUT

enter image description here

TypeError: $ is not a function when calling jQuery function

This solution worked for me

;(function($){
    // your code
})(jQuery);

Move your code inside the closure and use $ instead of jQuery

I found the above solution in https://magento.stackexchange.com/questions/33348/uncaught-typeerror-undefined-is-not-a-function-when-using-a-jquery-plugin-in-ma

...after searching too much

Returning the product of a list

if you just have numbers in your list:

from numpy import prod
prod(list)

EDIT: as pointed out by @off99555 this does not work for large integer results in which case it returns a result of type numpy.int64 while Ian Clelland's solution based on operator.mul and reduce works for large integer results because it returns long.

jQuery override default validation error message display (Css) Popup/Tooltip like

You can use the errorPlacement option to override the error message display with little css. Because css on its own will not be enough to produce the effect you need.

$(document).ready(function(){
    $("#myForm").validate({
        rules: {
            "elem.1": {
                required: true,
                digits: true
            },
            "elem.2": {
                required: true
            }
        },
        errorElement: "div",
        wrapper: "div",  // a wrapper around the error message
        errorPlacement: function(error, element) {
            offset = element.offset();
            error.insertBefore(element)
            error.addClass('message');  // add a class to the wrapper
            error.css('position', 'absolute');
            error.css('left', offset.left + element.outerWidth());
            error.css('top', offset.top);
        }

    });
});

You can play with the left and top css attributes to show the error message on top, left, right or bottom of the element. For example to show the error on the top:

    errorPlacement: function(error, element) {
        element.before(error);
        offset = element.offset();
        error.css('left', offset.left);
        error.css('top', offset.top - element.outerHeight());
    }

And so on. You can refer to jQuery documentation about css for more options.

Here is the css I used. The result looks exactly like the one you want. With as little CSS as possible:

div.message{
    background: transparent url(msg_arrow.gif) no-repeat scroll left center;
    padding-left: 7px;
}

div.error{
    background-color:#F3E6E6;
    border-color: #924949;
    border-style: solid solid solid none;
    border-width: 2px;
    padding: 5px;
}

And here is the background image you need:

alt text
(source: scriptiny.com)

If you want the error message to be displayed after a group of options or fields. Then group all those elements inside one container a 'div' or a 'fieldset'. Add a special class to all of them 'group' for example. And add the following to the begining of the errorPlacement function:

errorPlacement: function(error, element) {
    if (element.hasClass('group')){
        element = element.parent();
    }
    ...// continue as previously explained

If you only want to handle specific cases you can use attr instead:

if (element.attr('type') == 'radio'){
    element = element.parent();
}

That should be enough for the error message to be displayed next to the parent element.

You may need to change the width of the parent element to be less than 100%.


I've tried your code and it is working perfectly fine for me. Here is a preview: alt text

I just made a very small adjustment to the message padding to make it fit in the line:

div.error {
    padding: 2px 5px;
}

You can change those numbers to increase/decrease the padding on top/bottom or left/right. You can also add a height and width to the error message. If you are still having issues, try to replace the span with a div

<div class="group">
<input type="radio" class="checkbox" value="P" id="radio_P" name="radio_group_name"/>
<label for="radio_P">P</label>
<input type="radio" class="checkbox" value="S" id="radio_S" name="radio_group_name"/>
<label for="radio_S">S</label>
</div>

And then give the container a width (this is very important)

div.group {
    width: 50px; /* or any other value */
}

About the blank page. As I said I tried your code and it is working for me. It might be something else in your code that is causing the issue.

random.seed(): What does it do?

In this case, random is actually pseudo-random. Given a seed, it will generate numbers with an equal distribution. But with the same seed, it will generate the same number sequence every time. If you want it to change, you'll have to change your seed. A lot of people like to generate a seed based on the current time or something.

JavaScript regex for alphanumeric string with length of 3-5 chars

You'd have to define alphanumerics exactly, but

/^(\w{3,5})$/ 

Should match any digit/character/_ combination of length 3-5.

If you also need the dash, make sure to escape it (\-) add it, like this: :

/^([\w\-]{3,5})$/ 

Also: the ^ anchor means that the sequence has to start at the beginning of the line (character string), and the $ that it ends at the end of the line (character string). So your value string mustn't contain anything else, or it won't match.

Execute bash script from URL

Use:

curl -s -L URL_TO_SCRIPT_HERE | bash

For example:

curl -s -L http://bitly/10hA8iC | bash

How do I push amended commit to the remote Git repository?

If you are using Visual Studio Code, you can try this extension to make it easier.

https://marketplace.visualstudio.com/items?itemName=cimdalli.git-commit-amend-push-force

As you can understand from its name, it executes commands consecutively

  • git commit --amend
  • git push --force

git pull displays "fatal: Couldn't find remote ref refs/heads/xxxx" and hangs up

In my case, it happenned for the master branch. Later found that my access to the project was accidentally revoked by the project manager. To cross-check, I visited the review site and couldn't see any commits of the said branch and others for that project.

How to increase Java heap space for a tomcat app

You need to add the following lines in your catalina.sh file.

export CATALINA_OPTS="-Xms512M -Xmx1024M"

UPDATE : catalina.sh content clearly says -

Do not set the variables in this script. Instead put them into a script setenv.sh in CATALINA_BASE/bin to keep your customizations separate.

So you can add above in setenv.sh instead (create a file if it does not exist).

Changing Fonts Size in Matlab Plots

If anyone was wondering how to change the font sizes without messing around with the Matlab default fonts, and change every font in a figure, I found this thread where suggests this:

set(findall(fig, '-property', 'FontSize'), 'FontSize', 10, 'fontWeight', 'bold')

findall is a pretty handy command and in the case above it really finds all the children who have a 'FontSize' property: axes lables, axes titles, pushbuttons, etc.

Hope it helps.

JavaScript module pattern with example

In order to approach to Modular design pattern, you need to understand these concept first:

Immediately-Invoked Function Expression (IIFE):

(function() {
      // Your code goes here 
}());

There are two ways you can use the functions. 1. Function declaration 2. Function expression.

Here are using function expression.

What is namespace? Now if we add the namespace to the above piece of code then

var anoyn = (function() {
}());

What is closure in JS?

It means if we declare any function with any variable scope/inside another function (in JS we can declare a function inside another function!) then it will count that function scope always. This means that any variable in outer function will be read always. It will not read the global variable (if any) with the same name. This is also one of the objective of using modular design pattern avoiding naming conflict.

var scope = "I am global";
function whatismyscope() {
    var scope = "I am just a local";
    function func() {return scope;}
    return func;
}
whatismyscope()()

Now we will apply these three concepts I mentioned above to define our first modular design pattern:

var modularpattern = (function() {
    // your module code goes here
    var sum = 0 ;

    return {
        add:function() {
            sum = sum + 1;
            return sum;
        },
        reset:function() {
            return sum = 0;    
        }  
    }   
}());
alert(modularpattern.add());    // alerts: 1
alert(modularpattern.add());    // alerts: 2
alert(modularpattern.reset());  // alerts: 0

jsfiddle for the code above.

The objective is to hide the variable accessibility from the outside world.

Hope this helps. Good Luck.

SQL using sp_HelpText to view a stored procedure on a linked server

Little addition in answer if you have different user rather then dbo then do like this.

EXEC  [ServerName].[DatabaseName].dbo.sp_HelpText '[user].[storedProcName]'

Inserting the same value multiple times when formatting a string

Depends on what you mean by better. This works if your goal is removal of redundancy.

s='foo'
string='%s bar baz %s bar baz %s bar baz' % (3*(s,))

How to escape double quotes in JSON

if you want to escape double quote in JSON use \\ to escape it.

example if you want to create json of following javascript object

{time: '7 "o" clock'}

then you must write in following way

'{"time":"7 \\"o\\" clock"}'

if we parse it using JSON.parse()

JSON.parse('{"time":"7 \\"o\\" clock"}')

result will be

{time: "7 "o" clock"}

Python Pandas iterate over rows and access column names

The item from iterrows() is not a Series, but a tuple of (index, Series), so you can unpack the tuple in the for loop like so:

for (idx, row) in df.iterrows():
    print(row.loc['A'])
    print(row.A)
    print(row.index)

#0.890618586836
#0.890618586836
#Index(['A', 'B', 'C', 'D'], dtype='object')

How to get first and last day of the current week in JavaScript

Nice suggestion but you got a small problem in lastday. You should change it to:

lastday = new Date(firstday.getTime() + 60 * 60 *24 * 6 * 1000);

Converting to upper and lower case in Java

I consider this simpler than any prior correct answer. I'll also throw in javadoc. :-)

/**
 * Converts the given string to title case, where the first
 * letter is capitalized and the rest of the string is in
 * lower case.
 * 
 * @param s a string with unknown capitalization
 * @return a title-case version of the string
 */
public static String toTitleCase(String s)
{
    if (s.isEmpty())
    {
        return s;
    }
    return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
}

Strings of length 1 do not needed to be treated as a special case because s.substring(1) returns the empty string when s has length 1.

How to copy an object in Objective-C

another.obj = [obj copyWithZone: zone];

I think, that this line causes memory leak, because you access to obj through property which is (I assume) declared as retain. So, retain count will be increased by property and copyWithZone.

I believe it should be:

another.obj = [[obj copyWithZone: zone] autorelease];

or:

SomeOtherObject *temp = [obj copyWithZone: zone];
another.obj = temp;
[temp release]; 

How to switch Python versions in Terminal?

If you have python various versions of python installed,you can launch any of them using pythonx.x.x where x.x.x represents your versions.

How can I cast int to enum?

I prefer a short way using a nullable enum type variable.

var enumValue = (MyEnum?)enumInt;

if (!enumValue.HasValue)
{
    throw new ArgumentException(nameof(enumValue));
}

R: `which` statement with multiple conditions

The && function is not vectorized. You need the & function:

EUR <- PCs[which(PCs$V13 < 9 & PCs$V13 > 3), ]

What's the difference between dependencies, devDependencies and peerDependencies in npm package.json file?

To save a package to package.json as dev dependencies:

npm install "$package" --save-dev

When you run npm install it will install both devDependencies and dependencies. To avoid install devDependencies run:

npm install --production

Creating a JSON dynamically with each input value using jquery

May be this will help, I'd prefer pure JS wherever possible, it improves the performance drastically as you won't have lots of JQuery function calls.

var obj = [];
var elems = $("input[class=email]");

for (i = 0; i < elems.length; i += 1) {
    var id = this.getAttribute('title');
    var email = this.value;
    tmp = {
        'title': id,
        'email': email
    };

    obj.push(tmp);
}

Eclipse "cannot find the tag library descriptor" for custom tags (not JSTL!)

I'm using Spring STS plugin and a Spring webmvc template project. I had to install the Maven m2e plugin first: http://www.eclipse.org/m2e/

And then clean the project. Under Project -> Clean...

How to declare and add items to an array in Python?

In some languages like JAVA you define an array using curly braces as following but in python it has a different meaning:

Java:

int[] myIntArray = {1,2,3};
String[] myStringArray = {"a","b","c"};

However, in Python, curly braces are used to define dictionaries, which needs a key:value assignment as {'a':1, 'b':2}

To actually define an array (which is actually called list in python) you can do:

Python:

mylist = [1,2,3]

or other examples like:

mylist = list()
mylist.append(1)
mylist.append(2)
mylist.append(3)
print(mylist)
>>> [1,2,3]