Programs & Examples On #Microblogging

Getting PEAR to work on XAMPP (Apache/MySQL stack on Windows)

On Windows use the Xampp shell (there is a 'Shell' button in your XAMPP control panel)

then

cd php\pear

to go to 'C:\xampp\php\pear'

then type

pear

java SSL and cert keystore

System.setProperty("javax.net.ssl.trustStore", path_to_your_jks_file);

Why does corrcoef return a matrix?

Consider using matplotlib.cbook pieces

for example:

import matplotlib.cbook as cbook
segments = cbook.pieces(np.arange(20), 3)
for s in segments:
     print s

How to access PHP session variables from jQuery function in a .js file?

This is strictly not speaking using jQuery, but I have found this method easier than using jQuery. There are probably endless methods of achieving this and many clever ones here, but not all have worked for me. However the following method has always worked and I am passing it one in case it helps someone else.

Three javascript libraries are required, createCookie, readCookie and eraseCookie. These libraries are not mine but I began using them about 5 years ago and don't know their origin.

createCookie = function(name, value, days) {
if (days) {
    var date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    var expires = "; expires=" + date.toGMTString();
}
else var expires = "";

document.cookie = name + "=" + value + expires + "; path=/";
}

readCookie = function (name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') c = c.substring(1, c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
eraseCookie = function (name) {
   createCookie(name, "", -1);
}

To call them you need to create a small PHP function, normally as part of your support library, as follows:

<?php
 function createjavaScriptCookie($sessionVarible) {
 $s =  "<script>";
 $s = $s.'createCookie('. '"'. $sessionVarible                 
 .'",'.'"'.$_SESSION[$sessionVarible].'"'. ',"1"'.')';
 $s = $s."</script>";
 echo $s;
}
?>

So to use all you now have to include within your index.php file is

$_SESSION["video_dir"] = "/video_dir/";
createjavaScriptCookie("video_dir");

Now in your javascript library.js you can recover the cookie with the following code:

var videoPath = readCookie("video_dir") +'/'+ video_ID + '.mp4';

I hope this helps.

How do I conditionally add attributes to React components?

Here is an alternative.

var condition = true;

var props = {
  value: 'foo',
  ...( condition && { disabled: true } )
};

var component = <div { ...props } />;

Or its inline version

var condition = true;

var component = (
  <div
    value="foo"
    { ...( condition && { disabled: true } ) } />
);

How to Convert date into MM/DD/YY format in C#

See, here you can get only date by passing a format string. You can get a different date format as per your requirement as given below for current date:

DateTime.Now.ToString("M/d/yyyy");

Result : "9/1/2016"

DateTime.Now.ToString("M-d-yyyy");

Result : "9-1-2016"

DateTime.Now.ToString("yyyy-MM-dd");

Result : "2016-09-01"

DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");

Result : "2016-09-01 09:20:10"

For more details take a look at MSDN reference for Custom Date and Time Format Strings

How can I solve the error LNK2019: unresolved external symbol - function?

For me it works if I add this line below in .vcxproj in the itemGroup cpp file, which is connected to the header file.

<ClCompile Include="file.cpp" />

How to output a comma delimited list in jinja python template?

You want your if check to be:

{% if not loop.last %}
    ,
{% endif %}

Note that you can also shorten the code by using If Expression:

{{ ", " if not loop.last else "" }}

How to get All input of POST in Laravel

its better to use the Dependency than to attache it to the class.

public function add_question(Request $request)
{
    return Request::all();
}

or if you prefer using input variable use

public function add_question(Request $input)
{
    return $input::all();
}

you can now use the global request method provided by laravel

request()

for example to get the first_name of a form input.

request()->first_name
// or
request('first_name')

Batch file to perform start, run, %TEMP% and delete all

If you want to remove all the files in the %TEMP% folder you could just do this:

del %TEMP%\*.* /f /s /q

That will remove everything, any file with any extension (*.*) and do the same for all sub-folders (/s), without prompting you for anything (/q), it will just do it, including read only files (/f).

Hope this helps.

How to use performSelector:withObject:afterDelay: with primitive types in Cocoa?

I find that the quickest (but somewhat dirty) way to do this is by invoking objc_msgSend directly. However, it's dangerous to invoke it directly because you need to read the documentation and make sure that you're using the correct variant for the type of return value and because objc_msgSend is defined as vararg for compiler convenience but is actually implemented as fast assembly glue. Here's some code used to call a delegate method -[delegate integerDidChange:] that takes a single integer argument.

#import <objc/message.h>


SEL theSelector = @selector(integerDidChange:);
if ([self.delegate respondsToSelector:theSelector])
{
    typedef void (*IntegerDidChangeFuncPtrType)(id, SEL, NSInteger);
    IntegerDidChangeFuncPtrType MyFunction = (IntegerDidChangeFuncPtrType)objc_msgSend;
    MyFunction(self.delegate, theSelector, theIntegerThatChanged);
}

This first saves the selector since we're going to refer to it multiple times and it would be easy to create a typo. It then verifies that the delegate actually responds to the selector - it might be an optional protocol. It then creates a function pointer type that specifies the actual signature of the selector. Keep in mind that all Objective-C messages have two hidden first arguments, the object being messaged and the selector being sent. Then we create a function pointer of the appropriate type and set it to point to the underlying objc_msgSend function. Keep in mind that if the return value is a float or struct, you need to use a different variant of objc_msgSend. Finally, send the message using the same machinery that Objective-C uses under the sheets.

When to use the different log levels

I've always considered warning the first log level that for sure means there is a problem (for example, perhaps a config file isn't where it should be and we're going to have to run with default settings). An error implies, to me, something that means the main goal of the software is now impossible and we're going to try to shut down cleanly.

How do I change the android actionbar title and icon

This work for me:

getActionBar().setHomeButtonEnabled(true);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeAsUpIndicator(R.mipmap.baseline_dehaze_white_24);

HTTP POST Returns Error: 417 "Expectation Failed."

System.Net.HttpWebRequest adds the header 'HTTP header "Expect: 100-Continue"' to every request unless you explicitly ask it not to by setting this static property to false:

System.Net.ServicePointManager.Expect100Continue = false;

Some servers choke on that header and send back the 417 error you're seeing.

Give that a shot.

Manifest merger failed : uses-sdk:minSdkVersion 14

In the build.gradle file, It was by default compile 'com.android.support:support-v4:+' so when you build the gradle projecit would consider, com.android.support:support-v4:21.0.0-rc1 because of the recent L developer preview release.

Make changes in the following line and it will resolve the issue. Change

compile 'com.android.support:support-v4:+' 

to

compile 'com.android.support:support-v4:20.+'

Similarly when using v7-appcompat support library, make the change from

compile 'com.android.support:appcompat-v7:+'

to

compile 'com.android.support:appcompat-v7:20.+'.

Letter Count on a string

count_letters=""

number=count_letters.count("")

print number

database vs. flat files

SQL ad hoc query abilities are enough of a reason for me. With a good schema and indexing on the tables, this is fast and effective and will have good performance.

Redirecting a request using servlets and the "setHeader" method not working

As you can see, the response is still HTTP/1.1 200 OK. To indicate a redirect, you need to send back a 302 status code:

response.setStatus(HttpServletResponse.SC_FOUND); // SC_FOUND = 302

Can a html button perform a POST request?

You need to give the button a name and a value.

No control can be submitted without a name, and the content of a button element is the label, not the value.

<form action="" method="post">
    <button name="foo" value="upvote">Upvote</button>
</form>

iPhone/iOS JSON parsing tutorial

As of iOS 5.0 Apple provides the NSJSONSerialization class "to convert JSON to Foundation objects and convert Foundation objects to JSON". No external frameworks to incorporate and according to benchmarks its performance is quite good, significantly better than SBJSON.

Concat a string to SELECT * MySql

You cannot do this on multiple fields. You can also look for this.

How to implement Android Pull-to-Refresh

The easiest way i think is as provided by the android support library:

android.support.v4.widget.SwipeRefreshLayout;

once that is imported then you can have your layout defined as follows:

  <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/refresh"
        android:layout_height="match_parent"
        android:layout_width="match_parent">
    <android.support.v7.widget.RecyclerView
        xmlns:recycler_view="http://schemas.android.com/apk/res-auto"
        android:id="@android:id/list"
        android:theme="@style/Theme.AppCompat.Light"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/button_material_light"
        >

    </android.support.v7.widget.RecyclerView>
</android.support.v4.widget.SwipeRefreshLayout>

I assume that you use recycler view instead of listview. However, listview still works so you just need to replace recyclerview with listview and update the references in the java code (Fragment).

In your activity fragment, you first implement the interface, SwipeRefreshLayout.OnRefreshListener: i,e

public class MySwipeFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener{
private SwipeRefreshLayout swipeRefreshLayout;

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_item, container, false);
        swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.refresh);
        swipeRefreshLayout.setOnRefreshListener(this);
}


 @Override
  public void onRefresh(){
     swipeRefreshLayout.setRefreshing(true);
     refreshList();
  }
  refreshList(){
    //do processing to get new data and set your listview's adapter, maybe  reinitialise the loaders you may be using or so
   //when your data has finished loading, cset the refresh state of the view to false
   swipeRefreshLayout.setRefreshing(false);

   }
}

Hope this helps the masses

How to rollback just one step using rake db:migrate

Roll back the most recent migration:

rake db:rollback

Roll back the n most recent migrations:

rake db:rollback STEP=n

You can find full instructions on the use of Rails migration tasks for rake on the Rails Guide for running migrations.


Here's some more:

  • rake db:migrate - Run all migrations that haven't been run already
  • rake db:migrate VERSION=20080906120000 - Run all necessary migrations (up or down) to get to the given version
  • rake db:migrate RAILS_ENV=test - Run migrations in the given environment
  • rake db:migrate:redo - Roll back one migration and run it again
  • rake db:migrate:redo STEP=n - Roll back the last n migrations and run them again
  • rake db:migrate:up VERSION=20080906120000 - Run the up method for the given migration
  • rake db:migrate:down VERSION=20080906120000 - Run the down method for the given migration

And to answer your question about where you get a migration's version number from:

The version is the numerical prefix on the migration's filename. For example, to migrate to version 20080906120000 run

$ rake db:migrate VERSION=20080906120000

(From Running Migrations in the Rails Guides)

Error :Request header field Content-Type is not allowed by Access-Control-Allow-Headers

As hinted at by this post Error in chrome: Content-Type is not allowed by Access-Control-Allow-Headers just add the additional header to your web.config like so...

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
  </customHeaders>
</httpProtocol>

WebView and Cookies on Android

CookieManager.getInstance().setAcceptCookie(true); Normally it should work if your webview is already initialized

or try this:

CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
cookieManager.setAcceptCookie(true);

CSS for the "down arrow" on a <select> element?

No, the down arrow is a browser element. It's built in [and different] in every browser. You can, however, replace the select box with a custom drop down box using javascript.

Jan Hancic mentioned a jQuery plugin to do just that.

gcc error: wrong ELF class: ELFCLASS64

I think that coreset.o was compiled for 64-bit, and you are linking it with a 32-bit computation.o.

You can try to recompile computation.c with the '-m64' flag of gcc(1)

How to remove focus from single editText

i had a similar problem with the editText, which gained focus since the activity was started. this problem i fixed easily like this:

you add this piece of code into the layout that contains the editText in xml:

    android:id="@+id/linearlayout" 
    android:focusableInTouchMode="true"

dont forget the android:id, without it i've got an error.

the other problem i had with the editText is that once it gain the first focus, the focus never disappeared. this is a piece of my code in java, it has an editText and a button that captures the text in the editText:

    editText=(EditText) findViewById(R.id.et1);
    tvhome= (TextView)findViewById(R.id.tv_home);
    etBtn= (Button) findViewById(R.id.btn_homeadd);
    etBtn.setOnClickListener(new View.OnClickListener() 
    {   
        @Override
        public void onClick(View v)
        {
            tvhome.setText( editText.getText().toString() );

            //** this code is for hiding the keyboard after pressing the button
            View view = Settings.this.getCurrentFocus();
            if (view != null) 
            {  
                InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
            }
            //**

            editText.getText().clear();//clears the text
            editText.setFocusable(false);//disables the focus of the editText 
            Log.i("onCreate().Button.onClickListener()", "et.isfocused= "+editText.isFocused());
        }
    });
    editText.setOnClickListener(new View.OnClickListener() 
    {
        @Override
        public void onClick(View v) 
        {
            if(v.getId() == R.id.et1)
            {
                v.setFocusableInTouchMode(true);// when the editText is clicked it will gain focus again

                //** this code is for enabling the keyboard at the first click on the editText
                if(v.isFocused())//the code is optional, because at the second click the keyboard shows by itself
                {
                    InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.showSoftInput(v, InputMethodManager.SHOW_IMPLICIT);
                }
                //**

                Log.i("onCreate().EditText.onClickListener()", "et.isfocused= "+v.isFocused());
            }
            else
                Log.i("onCreate().EditText.onClickListener()", "the listener did'nt consume the event");
        }
    });

hope it will help to some of you!

How to request Location Permission at runtime

Location permission privacy change in Android 10 or Android Q.

We have to define additional ACCESS_BACKGROUND_LOCATION permission if user wants to access their current location in background so user needs to granted permission runtime also in requestPermission()

If we are using lower than Android 10 device then ACCESS_BACKGROUND_LOCATION permission allow automatically with ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION permission

This tabular format might be easy to understand what if we don't specify ACCESS_BACKGROUND_LOCATION in manifest file.

enter image description here

AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" /> // here we defined ACCESS_BACKGROUND_LOCATION for Android 10 device

MainActivity.java
Call checkRunTimePermission() in onCreate() or onResume()

public void checkRunTimePermission() {
   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || 
             ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED||
             ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_BACKGROUND_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                gpsTracker = new GPSTracker(context);

        } else {
                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION},
                        10);
        }
   } else {
            gpsTracker = new GPSTracker(context); //GPSTracker is class that is used for retrieve user current location
   }
}

 @Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == 10) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            gpsTracker = new GPSTracker(context);
        } else {
            if (!ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.ACCESS_FINE_LOCATION)) {
                // If User Checked 'Don't Show Again' checkbox for runtime permission, then navigate user to Settings
                AlertDialog.Builder dialog = new AlertDialog.Builder(context);
                dialog.setTitle("Permission Required");
                dialog.setCancelable(false);
                dialog.setMessage("You have to Allow permission to access user location");
                dialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent i = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.fromParts("package",
                                context.getPackageName(), null));
                        //i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivityForResult(i, 1001);
                    }
                });
                AlertDialog alertDialog = dialog.create();
                alertDialog.show();
            }
            //code for deny
        }
    }
}

@Override
public void startActivityForResult(Intent intent, int requestCode) {
    super.startActivityForResult(intent, requestCode);
    switch (requestCode) {
        case 1001:
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED ||
                        ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED 
                        || ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_BACKGROUND_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                    gpsTracker = new GPSTracker(context);
                    if (gpsTracker.canGetLocation()) {
                        latitude = gpsTracker.getLatitude();
                        longitude = gpsTracker.getLongitude();
                    }
                } else {
                    requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.ACCESS_BACKGROUND_LOCATION},10);
                }
            }
            break;
        default:
            break;
    }
}

build.gradle (app level)

android {
    compileSdkVersion 29 //should be >= 29
    buildToolsVersion "29.0.2"
    useLibrary 'org.apache.http.legacy'
    defaultConfig {
        applicationId "com.example.runtimepermission"
        minSdkVersion 21
        targetSdkVersion 29 //should be >= 29
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        vectorDrawables.useSupportLibrary = true
    }
}

Here you can find GPSTracker.java file code

check null,empty or undefined angularjs

You can also do a simple check using function,

$scope.isNullOrEmptyOrUndefined = function (value) {
    return !value;
}

How to pass all arguments passed to my bash script to a function of mine?

It's worth mentioning that you can specify argument ranges with this syntax.

function example() {
    echo "line1 ${@:1:1}"; #First argument
    echo "line2 ${@:2:1}"; #Second argument
    echo "line3 ${@:3}"; #Third argument onwards
}

I hadn't seen it mentioned.

Set Focus After Last Character in Text Box

<script type="text/javascript">
    $(function(){
        $('#areaCode,#firstNum,#secNum').keyup(function(e){
            if($(this).val().length==$(this).attr('maxlength'))
                $(this).next(':input').focus()
        })
    })
    </script>

<body>

<input type="text" id="areaCode" name="areaCode" maxlength="3" value="" size="3" />- 
<input type="text" id="firstNum" name="firstNum" maxlength="3" value="" size="3" />- 
<input type="text" id="secNum" name=" secNum " maxlength="4" value="" size="4" />

</body>

Textarea that can do syntax highlighting on the fly?

Here is the response I've done to a similar question (Online Code Editor) on programmers:

First, you can take a look to this article:
Wikipedia - Comparison of JavaScript-based source code editors.

For more, here is some tools that seem to fit with your request:

  • EditArea - Demo as FileEditor who is a Yii Extension - (Apache Software License, BSD, LGPL)

    Here is EditArea, a free javascript editor for source code. It allow to write well formated source code with line numerotation, tab support, search & replace (with regexp) and live syntax highlighting (customizable).

  • CodePress - Demo of Joomla! CodePress Plugin - (LGPL) - It doesn't work in Chrome and it looks like development has ceased.

    CodePress is web-based source code editor with syntax highlighting written in JavaScript that colors text in real time while it's being typed in the browser.

  • CodeMirror - One of the many demo - (MIT-style license + optional commercial support)

    CodeMirror is a JavaScript library that can be used to create a relatively pleasant editor interface for code-like content - computer programs, HTML markup, and similar. If a mode has been written for the language you are editing, the code will be coloured, and the editor will optionally help you with indentation

  • Ace Ajax.org Cloud9 Editor - Demo - (Mozilla tri-license (MPL/GPL/LGPL))

    Ace is a standalone code editor written in JavaScript. Our goal is to create a web based code editor that matches and extends the features, usability and performance of existing native editors such as TextMate, Vim or Eclipse. It can be easily embedded in any web page and JavaScript application. Ace is developed as the primary editor for Cloud9 IDE and the successor of the Mozilla Skywriter (Bespin) Project.

SQL selecting rows by most recent date with two unique columns

So this isn't what the requester was asking for but it is the answer to "SQL selecting rows by most recent date".

Modified from http://wiki.lessthandot.com/index.php/Returning_The_Maximum_Value_For_A_Row

SELECT t.chargeId, t.chargeType, t.serviceMonth FROM( 
    SELECT chargeId,MAX(serviceMonth) AS serviceMonth
    FROM invoice
    GROUP BY chargeId) x 
    JOIN invoice t ON x.chargeId =t.chargeId
    AND x.serviceMonth = t.serviceMonth

How to get Exception Error Code in C#

Building on Preet Sangha's solution, the following should safely cover the scenario where you're working with a large solution with the potential for several Inner Exceptions.

 try
 {
     object result = processClass.InvokeMethod("Create", methodArgs);
 }
 catch (Exception e)
 {
     // Here I was hoping to get an error code.
     if (ExceptionContainsErrorCode(e, 10004))
     {
         // Execute desired actions
     }
 }

...

private bool ExceptionContainsErrorCode(Exception e, int ErrorCode)
{
    Win32Exception winEx = e as Win32Exception;
    if (winEx != null && ErrorCode == winEx.ErrorCode) 
        return true;

    if (e.InnerException != null) 
        return ExceptionContainsErrorCode(e.InnerException, ErrorCode);

    return false;
}

This code has been unit tested.

I won't harp too much on the need for coming to appreciate and implement good practice when it comes to Exception Handling by managing each expected Exception Type within their own blocks.

Python functions call by reference

There are essentially three kinds of 'function calls':

  • Pass by value
  • Pass by reference
  • Pass by object reference

Python is a PASS-BY-OBJECT-REFERENCE programming language.

Firstly, it is important to understand that a variable, and the value of the variable (the object) are two seperate things. The variable 'points to' the object. The variable is not the object. Again:

THE VARIABLE IS NOT THE OBJECT

Example: in the following line of code:

>>> x = []

[] is the empty list, x is a variable that points to the empty list, but x itself is not the empty list.

Consider the variable (x, in the above case) as a box, and 'the value' of the variable ([]) as the object inside the box.

PASS BY OBJECT REFERENCE (Case in python):

Here, "Object references are passed by value."

def append_one(li):
    li.append(1)
x = [0]
append_one(x)
print x

Here, the statement x = [0] makes a variable x (box) that points towards the object [0].

On the function being called, a new box li is created. The contents of li are the SAME as the contents of the box x. Both the boxes contain the same object. That is, both the variables point to the same object in memory. Hence, any change to the object pointed at by li will also be reflected by the object pointed at by x.

In conclusion, the output of the above program will be:

[0, 1]

Note:

If the variable li is reassigned in the function, then li will point to a separate object in memory. x however, will continue pointing to the same object in memory it was pointing to earlier.

Example:

def append_one(li):
    li = [0, 1]
x = [0]
append_one(x)
print x

The output of the program will be:

[0]

PASS BY REFERENCE:

The box from the calling function is passed on to the called function. Implicitly, the contents of the box (the value of the variable) is passed on to the called function. Hence, any change to the contents of the box in the called function will be reflected in the calling function.

PASS BY VALUE:

A new box is created in the called function, and copies of contents of the box from the calling function is stored into the new boxes.

Hope this helps.

Importing variables from another file?

Marc response is correct. Actually, you can print the memory address for the variables print(hex(id(libvar)) and you can see the addresses are different.

# mylib.py
libvar = None
def lib_method():
    global libvar
    print(hex(id(libvar)))

# myapp.py
from mylib import libvar, lib_method
import mylib

lib_method()
print(hex(id(libvar)))
print(hex(id(mylib.libvar)))

How return error message in spring mvc @Controller

Evaluating the error response from another service invocated...

This was my solution for evaluating the error:

try {
        return authenticationFeign.signIn(userDto, dataRequest);
    }catch(FeignException ex){

        //ex.status();

        if(ex.status() == HttpStatus.UNAUTHORIZED.value()){
            System.out.println("is a error 401");
            return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
        }
        return new ResponseEntity<>(HttpStatus.OK);

    }

How to fix the datetime2 out-of-range conversion error using DbContext and SetInitializer?

Based on user @andygjp's answer, its better if you override the base Db.SaveChanges() method and add a function to override any date which does not fall between SqlDateTime.MinValue and SqlDateTime.MaxValue.

Here is the sample code

public class MyDb : DbContext
{
    public override int SaveChanges()
    {
        UpdateDates();
        return base.SaveChanges();
    }

    private void UpdateDates()
    {
        foreach (var change in ChangeTracker.Entries().Where(x => (x.State == EntityState.Added || x.State == EntityState.Modified)))
        {
            var values = change.CurrentValues;
            foreach (var name in values.PropertyNames)
            {
                var value = values[name];
                if (value is DateTime)
                {
                    var date = (DateTime)value;
                    if (date < SqlDateTime.MinValue.Value)
                    {
                        values[name] = SqlDateTime.MinValue.Value;
                    }
                    else if (date > SqlDateTime.MaxValue.Value)
                    {
                        values[name] = SqlDateTime.MaxValue.Value;
                    }
                }
            }
        }
    }
}

Taken from the user @sky-dev's comment on https://stackoverflow.com/a/11297294/9158120

Using app.config in .Net Core

It is possible to use your usual System.Configuration even in .NET Core 2.0 on Linux. Try this test example:

  1. Created a .NET Standard 2.0 Library (say MyLib.dll)
  2. Added the NuGet package System.Configuration.ConfigurationManager v4.4.0. This is needed since this package isn't covered by the meta-package NetStandard.Library v2.0.0 (I hope that changes)
  3. All your C# classes derived from ConfigurationSection or ConfigurationElement go into MyLib.dll. For example MyClass.cs derives from ConfigurationSection and MyAccount.cs derives from ConfigurationElement. Implementation details are out of scope here but Google is your friend.
  4. Create a .NET Core 2.0 app (e.g. a console app, MyApp.dll). .NET Core apps end with .dll rather than .exe in Framework.
  5. Create an app.config in MyApp with your custom configuration sections. This should obviously match your class designs in #3 above. For example:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="myCustomConfig" type="MyNamespace.MyClass, MyLib" />
  </configSections>
  <myCustomConfig>
    <myAccount id="007" />
  </myCustomConfig>
</configuration>

That's it - you'll find that the app.config is parsed properly within MyApp and your existing code within MyLib works just fine. Don't forget to run dotnet restore if you switch platforms from Windows (dev) to Linux (test).

Additional workaround for test projects

If you're finding that your App.config is not working in your test projects, you might need this snippet in your test project's .csproj (e.g. just before the ending </Project>). It basically copies App.config into your output folder as testhost.dll.config so dotnet test picks it up.

  <!-- START: This is a buildtime work around for https://github.com/dotnet/corefx/issues/22101 -->
  <Target Name="CopyCustomContent" AfterTargets="AfterBuild">
    <Copy SourceFiles="App.config" DestinationFiles="$(OutDir)\testhost.dll.config" />
  </Target>
  <!-- END: This is a buildtime work around for https://github.com/dotnet/corefx/issues/22101 -->

How do I get the path of the Python script I am running in?

os.path.realpath(__file__) will give you the path of the current file, resolving any symlinks in the path. This works fine on my mac.

Basic Ajax send/receive with node.js

RESTful API (Route):

rtr.route('/testing')
.get((req, res)=>{
    res.render('test')
})
.post((req, res, next)=>{
       res.render('test')
})

AJAX Code:

$(function(){
$('#anyid').on('click', function(e){
    e.preventDefault()
    $.ajax({
        url: '/testing',
        method: 'GET',
        contentType: 'application/json',
        success: function(res){
            console.log('GET Request')
        }
    })
})

$('#anyid').on('submit', function(e){
    e.preventDefault()
    $.ajax({
        url: '/testing',
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({
            info: "put data here to pass in JSON format."
        }),
        success: function(res){
            console.log('POST Request')
        }
    })
})
})

Adding subscribers to a list using Mailchimp's API v3

If you Want to run Batch Subscribe on a List using Mailchimp API . Then you can use the below function.

    /**
     * Mailchimp API- List Batch Subscribe added function
     *
     * @param array  $data   Passed you data as an array format.
     * @param string $apikey your mailchimp api key.
     *
     * @return mixed
     */
    function batchSubscribe(array $data, $apikey)
    {
        $auth          = base64_encode('user:' . $apikey);
        $json_postData = json_encode($data);
        $ch            = curl_init();
        $dataCenter    = substr($apikey, strpos($apikey, '-') + 1);
        $curlopt_url   = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/batches/';
        curl_setopt($ch, CURLOPT_URL, $curlopt_url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
            'Authorization: Basic ' . $auth));
        curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/3.0');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json_postData);
        $result = curl_exec($ch);
        return $result;
    }

Function Use And Data format for Batch Operations:

<?php
$apikey  = 'Your MailChimp Api Key';
$list_id = 'Your list ID';
$servername = 'localhost';
$username   = 'Youre DB username';
$password   = 'Your DB password';
$dbname     = 'Your DB Name';
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die('Connection failed: ' . $conn->connect_error);
}
$sql       = 'SELECT * FROM emails';// your SQL Query goes here
$result    = $conn->query($sql);
$finalData = [];
if ($result->num_rows > 0) {
    // output data of each row
    while ($row = $result->fetch_assoc()) {
        $individulData = array(
            'apikey'        => $apikey,
            'email_address' => $row['email'],
            'status'        => 'subscribed',
            'merge_fields'  => array(
                'FNAME' => 'eastwest',
                'LNAME' => 'rehab',
            )
        );
        $json_individulData        = json_encode($individulData);
        $finalData['operations'][] =
            array(
                "method" => "POST",
                "path"   => "/lists/$list_id/members/",
                "body"   => $json_individulData
            );
    }
}
$api_response = batchSubscribe($finalData, $apikey);
print_r($api_response);
$conn->close();

Also, You can found this code in my Github gist. GithubGist Link

Reference Documentation: Official

Error "The input device is not a TTY"

I believe you need to be in a TTY for docker to be able to allocate a TTY (the -t option). Jenkins executes its jobs not in a TTY.

Having said that, the script you are running within Jenkins you may also want to run locally. In that case it can be really convenient to have a TTY allocated so you can send signals like ctrl+c when running it locally.

To fix this make your script optionally use the -t option, like so:

test -t 1 && USE_TTY="-t" 
docker run ${USE_TTY} ...

Why is <deny users="?" /> included in the following example?

Example 1 is for asp.net applications using forms authenication. This is common practice for internet applications because user is unauthenticated until it is authentcation against some security module.

Example 2 is for asp.net application using windows authenication. Windows Authentication uses Active Directory to authenticate users. The will prevent access to your application. I use this feature on intranet applications.

Check if value exists in column in VBA

If you want to do this without VBA, you can use a combination of IF, ISERROR, and MATCH.

So if all values are in column A, enter this formula in column B:

=IF(ISERROR(MATCH(12345,A:A,0)),"Not Found","Value found on row " & MATCH(12345,A:A,0))

This will look for the value "12345" (which can also be a cell reference). If the value isn't found, MATCH returns "#N/A" and ISERROR tries to catch that.

If you want to use VBA, the quickest way is to use a FOR loop:

Sub FindMatchingValue()
    Dim i as Integer, intValueToFind as integer
    intValueToFind = 12345
    For i = 1 to 500    ' Revise the 500 to include all of your values
        If Cells(i,1).Value = intValueToFind then 
            MsgBox("Found value on row " & i)
            Exit Sub
        End If
    Next i

    ' This MsgBox will only show if the loop completes with no success
    MsgBox("Value not found in the range!")  
End Sub

You can use Worksheet Functions in VBA, but they're picky and sometimes throw nonsensical errors. The FOR loop is pretty foolproof.

How to bind WPF button to a command in ViewModelBase?

 <Grid >
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Button Command="{Binding ClickCommand}" Width="100" Height="100" Content="wefwfwef"/>
</Grid>

the code behind for the window:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new ViewModelBase();
    }
}

The ViewModel:

public class ViewModelBase
{
    private ICommand _clickCommand;
    public ICommand ClickCommand
    {
        get
        {
            return _clickCommand ?? (_clickCommand = new CommandHandler(() => MyAction(), ()=> CanExecute));
        }
    }
     public bool CanExecute
     {
        get
        {
            // check if executing is allowed, i.e., validate, check if a process is running, etc. 
            return true/false;
        }
     }

    public void MyAction()
    {

    }
}

Command Handler:

 public class CommandHandler : ICommand
{
    private Action _action;
    private Func<bool> _canExecute;

    /// <summary>
    /// Creates instance of the command handler
    /// </summary>
    /// <param name="action">Action to be executed by the command</param>
    /// <param name="canExecute">A bolean property to containing current permissions to execute the command</param>
    public CommandHandler(Action action, Func<bool> canExecute)
    {
        _action = action;
        _canExecute = canExecute;
    }

    /// <summary>
    /// Wires CanExecuteChanged event 
    /// </summary>
    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    /// <summary>
    /// Forcess checking if execute is allowed
    /// </summary>
    /// <param name="parameter"></param>
    /// <returns></returns>
    public bool CanExecute(object parameter)
    {
        return _canExecute.Invoke();
    }

    public void Execute(object parameter)
    {
        _action();
    }
}

I hope this will give you the idea.

Where can I find the Tomcat 7 installation folder on Linux AMI in Elastic Beanstalk?

  • If you want to find the webapp folder, it may be over here:

/var/lib/tomcat7/webapps/

  • But you also can type this to find it:

find / -name 'tomcat_version' -type d

Partly cherry-picking a commit with Git

Use git format-patch to slice out the part of the commit you care about and git am to apply it to another branch

git format-patch <sha> -- path/to/file
git checkout other-branch
git am *.patch

How to scroll to top of the page in AngularJS?

Don't forget you can also use pure JavaScript to deal with this situation, using:

window.scrollTo(x-coord, y-coord);

Find multiple files and rename them in Linux

classic solution:

for f in $(find . -name "*dbg*"); do mv $f $(echo $f | sed 's/_dbg//'); done

How do I remove an object from an array with JavaScript?

var apps = [{id:34,name:'My App',another:'thing'},{id:37,name:'My New App',another:'things'}];

// get index of object with id:37

var removeIndex = apps.map(function(item) { return item.id; }).indexOf(37);

// remove object

apps.splice(removeIndex, 1);

Using ffmpeg to change framerate

Simply specify the desired framerate in "-r " option before the input file:

ffmpeg -y -r 24 -i seeing_noaudio.mp4 seeing.mp4

Options affect the next file AFTER them. "-r" before an input file forces to reinterpret its header as if the video was encoded at the given framerate. No recompression is necessary. There was a small utility avifrate.exe to patch avi file headers directly to change the framerate. ffmpeg command above essentially does the same, but has to copy the entire file.

How to import classes defined in __init__.py

Edit, since i misunderstood the question:

Just put the Helper class in __init__.py. Thats perfectly pythonic. It just feels strange coming from languages like Java.

YouTube embedded video: set different thumbnail

It's possible using jQuery it depends on your site load time you can adjust your timeout. It can be your custom image or you can use youtube image maxres1.jpg, maxres2.jpg or maxres3.jpg

var newImage = 'http://i.ytimg.com/vi/[Video_ID]/maxres1.jpg';
window.setTimeout(function() {
jQuery('div > div.video-container-thumb > div > a > img').attr('src',newImage );
}, 300);

Converting serial port data to TCP/IP in a Linux environment

You can create a serial-over-LAN (SOL) connection by using socat. It can be used to 'forward' a ttyS to another machine so it appears as a local one or you can access it via a TCP/IP port.

Can not deserialize instance of java.lang.String out of START_OBJECT token

Resolved the problem using Jackson library. Prints are called out of Main class and all POJO classes are created. Here is the code snippets.

MainClass.java

public class MainClass {
  public static void main(String[] args) throws JsonParseException, 
       JsonMappingException, IOException {

String jsonStr = "{\r\n" + "    \"id\": 2,\r\n" + " \"socket\": \"0c317829-69bf- 
             43d6-b598-7c0c550635bb\",\r\n"
            + " \"type\": \"getDashboard\",\r\n" + "    \"data\": {\r\n"
            + "     \"workstationUuid\": \"ddec1caa-a97f-4922-833f- 
            632da07ffc11\"\r\n" + " },\r\n"
            + " \"reply\": true\r\n" + "}";

    ObjectMapper mapper = new ObjectMapper();

    MyPojo details = mapper.readValue(jsonStr, MyPojo.class);

    System.out.println("Value for getFirstName is: " + details.getId());
    System.out.println("Value for getLastName  is: " + details.getSocket());
    System.out.println("Value for getChildren is: " + 
      details.getData().getWorkstationUuid());
    System.out.println("Value for getChildren is: " + details.getReply());

}

MyPojo.java

public class MyPojo {
    private String id;

    private Data data;

    private String reply;

    private String socket;

    private String type;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public Data getData() {
        return data;
    }

    public void setData(Data data) {
        this.data = data;
    }

    public String getReply() {
        return reply;
    }

    public void setReply(String reply) {
        this.reply = reply;
    }

    public String getSocket() {
        return socket;
    }

    public void setSocket(String socket) {
        this.socket = socket;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    } 
}

Data.java

public class Data {
    private String workstationUuid;

    public String getWorkstationUuid() {
        return workstationUuid;
    }

    public void setWorkstationUuid(String workstationUuid) {
        this.workstationUuid = workstationUuid;
    }   
}

RESULTS:

Value for getFirstName is: 2
Value for getLastName  is: 0c317829-69bf-43d6-b598-7c0c550635bb
Value for getChildren is: ddec1caa-a97f-4922-833f-632da07ffc11
Value for getChildren is: true

How do I terminate a thread in C++11?

@Howard Hinnant's answer is both correct and comprehensive. But it might be misunderstood if it's read too quickly, because std::terminate() (whole process) happens to have the same name as the "terminating" that @Alexander V had in mind (1 thread).

Summary: "terminate 1 thread + forcefully (target thread doesn't cooperate) + pure C++11 = No way."

How to convert file to base64 in JavaScript?

JavaScript btoa() function can be used to convert data into base64 encoded string

"SDK Platform Tools component is missing!"

Here is another alternative. Download it directly here: http://androidsdkoffline.blogspot.com.ng/p/android-sdk-tools.html.

The present version as of this writing is Android SDK Tools 25.1.7. Unzip it when the download is done and place it in your sdk folder. You can then download other missing files directly from the SDK Manager.

Setting default permissions for newly created files and sub-directories under a directory in Linux?

It's ugly, but you can use the setfacl command to achieve exactly what you want.

On a Solaris machine, I have a file that contains the acls for users and groups. Unfortunately, you have to list all of the users (at least I couldn't find a way to make this work otherwise):

user::rwx
user:user_a:rwx
user:user_b:rwx
...
group::rwx
mask:rwx
other:r-x
default:user:user_a:rwx
default:user:user_b:rwx
....
default:group::rwx
default:user::rwx
default:mask:rwx
default:other:r-x

Name the file acl.lst and fill in your real user names instead of user_X.

You can now set those acls on your directory by issuing the following command:

setfacl -f acl.lst /your/dir/here

How to add values in a variable in Unix shell scripting?

read num1
read num2
sum=`expr $num1 + $num2`
echo $sum

How do I add FTP support to Eclipse?

have you checked RSE (Remote System Explorer) ? I think it's pretty close to what you want to achieve.

a blog post about it, with screenshots

Python Binomial Coefficient

Here is a function that recursively calculates the binomial coefficients using conditional expressions

def binomial(n,k):
    return 1 if k==0 else (0 if n==0 else binomial(n-1, k) + binomial(n-1, k-1))

How to list files using dos commands?

If you just want to get the file names and not directory names then use :

dir /b /a-d > file.txt

Why does this code using random strings print "hello world"?

It is about "seed". Same seeds give the same result.

Use tab to indent in textarea

The above answers all wipe undo history. For anyone looking for a solution that doesn't do that, I spent the last hour coding up the following for Chrome:

jQuery.fn.enableTabs = function(TAB_TEXT){
    // options
    if(!TAB_TEXT)TAB_TEXT = '\t';
    // text input event for character insertion
    function insertText(el, text){
        var te = document.createEvent('TextEvent');
        te.initTextEvent('textInput', true, true, null, text, 9, "en-US");
        el.dispatchEvent(te);
    }
    // catch tab and filter selection
    jQuery(this).keydown(function(e){
        if((e.which || e.keyCode)!=9)return true;
        e.preventDefault();
        var contents = this.value,
            sel_start = this.selectionStart,
            sel_end = this.selectionEnd,
            sel_contents_before = contents.substring(0, sel_start),
            first_line_start_search = sel_contents_before.lastIndexOf('\n'),
            first_line_start = first_line_start_search==-1 ? 0 : first_line_start_search+1,
            tab_sel_contents = contents.substring(first_line_start, sel_end),
            tab_sel_contents_find = (e.shiftKey?new RegExp('\n'+TAB_TEXT, 'g'):new RegExp('\n', 'g')),
            tab_sel_contents_replace = (e.shiftKey?'\n':'\n'+TAB_TEXT);
            tab_sel_contents_replaced = (('\n'+tab_sel_contents)
                .replace(tab_sel_contents_find, tab_sel_contents_replace))
                .substring(1),
            sel_end_new = first_line_start+tab_sel_contents_replaced.length;
        this.setSelectionRange(first_line_start, sel_end);
        insertText(this, tab_sel_contents_replaced);
        this.setSelectionRange(first_line_start, sel_end_new);
    });
};

In short, tabs are inserted at the beginning of the selected lines.

JSFiddle: http://jsfiddle.net/iausallc/5Lnabspr/11/

Gist: https://gist.github.com/iautomation/e53647be326cb7d7112d

Example usage: $('textarea').enableTabs('\t')

Cons: Only works on Chrome as is.

Linux: Which process is causing "device busy" when doing umount?

You should use the fuser command.

Eg. fuser /dev/cdrom will return the pid(s) of the process using /dev/cdrom.

If you are trying to unmount, you can kill theses process using the -k switch (see man fuser).

JavaScript Form Submit - Confirm or Cancel Submission Dialog Box

A simple inline JavaScript confirm would suffice:

<form onsubmit="return confirm('Do you really want to submit the form?');">

No need for an external function unless you are doing validation, which you can do something like this:

<script>
function validate(form) {

    // validation code here ...


    if(!valid) {
        alert('Please correct the errors in the form!');
        return false;
    }
    else {
        return confirm('Do you really want to submit the form?');
    }
}
</script>
<form onsubmit="return validate(this);">

Get full path of a file with FileUpload Control

Check this post under FileUpload Control

Additionally, the “Include local directory path when uploading files” URLAction has been set to "Disable" for the Internet Zone. This change prevents leakage of potentially sensitive local file-system information to the Internet. For instance, rather than submitting the full path C:\users\ericlaw\documents\secret\image.png, Internet Explorer 8 will now submit only the filename image.png.

Its an option under Internet security that can be enabled

ERROR 1044 (42000): Access denied for user ''@'localhost' to database 'db'

You might want to try the full login command:

mysql -h host -u root -p 

where host would be 127.0.0.1.

Do this just to make sure cooperation exists.

Using mysql -u root -p allows me to do a a lot of database searching, but refuses any database creation due to a path setting.

How to use sbt from behind proxy?

To provide one answer that will work for all Windows-users:

Add the following to your sbtconfig.txt (C:\Program Files (x86)\sbt\conf)

-Dhttp.proxyHost=XXXXXXX -Dhttp.proxyPort=YYYY -Dhttp.proxySet=true -Dhttps.proxyHost=XXXXXXX -Dhttps.proxyPort=YYYY -Dhttps.proxySet=true

Replace both XXXXXXX with your proxyHost, and both YYYY with your proxyPort.

If you get the error "Could not find or load main class" you need to set your JAVA_HOME:

set JAVA_HOME=C:\Progra~1\Java\jdkxxxxxx

When on 64-bit windows, use:

Progra~1 = 'Program Files'

Progra~2 = 'Program Files(x86)'

npm check and update package if needed

NPM commands to update or fix vulnerabilities in some dependency manifest files

  • Use below command to check outdated or vulnerabilities in your node modules.

    npm audit

  • If any vulnerabilities found, use below command to fix all issues.

    npm audit fix

  • If it doesn't work for you then try

    npm audit fix -f, this command will almost fix all vulnerabilities. Some dependencies or devDependencies are locked in package-lock.json file, so we use -f flag to force update them.

  • If you don't want to use force audit fix then you can manually fix your dependencies versions by changing them in package-lock.json and package.json file. Then run

npm update && npm upgrade

Using CSS to insert text

Just code it like this:

.OwnerJoe {
  //other things here
  &:before{
    content: "Joe's Task: ";
  }
}

org.xml.sax.SAXParseException: Content is not allowed in prolog

I followed the instructions found here and i got the same error.

I tried several things to solve it (ie changing the encoding, typing the XML file rather than copy-pasting it ect) in Notepad and XML Notepad but nothing worked.

The problem got solved when I edited and saved my XML file in Notepad++ (encoding --> utf-8 without BOM)

What is null in Java?

The null keyword is a literal that represents a null reference, one that does not refer to any object. null is the default value of reference-type variables.

Also maybe have a look at

null : Java Glossary

How to create multiple output paths in Webpack config

You can now (as of Webpack v5.0.0) specify a unique output path for each entry using the new "descriptor" syntax (https://webpack.js.org/configuration/entry-context/#entry-descriptor) –

module.exports = {
  entry: {
    home: { import: './home.js', filename: 'unique/path/1/[name][ext]' },
    about: { import: './about.js', filename: 'unique/path/2/[name][ext]' }
  }
};

"Parse Error : There is a problem parsing the package" while installing Android application

Instead of shooting in the dark, get the reason for this error by installing it via adb:

adb -s emulator-5555 install ~/path-to-your-apk/com.app.apk

Replace emulator-5555 with your device name. You can obtain a list using:

adb devices

Upon failing, it will give a reason. Common reasons and their fixes:

  1. INSTALL_PARSE_FAILED_NO_CERTIFICATES: Reference
  2. INSTALL_FAILED_UPDATE_INCOMPATIBLE: Reference

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

const myObj = { a:1, b:2, c:3 }

Get all values:

  • the shortest way:

    • const myValues = Object.values(myObj)
  • const myValues = Object.keys(myObj).map(key => myObj[key])

Why I can't access remote Jupyter Notebook server?

if you are using Conda environment, you should set up config file again. And file location will be something like this. I did not setup config file after I created env in Conda and that was my connection problem.

C:\Users\syurt\AppData\Local\Continuum\anaconda3\envs\myenv\share\jupyter\jupyter_notebook_config.py

How to convert date format to milliseconds?

date.setTime(milliseconds);

this is for set milliseconds in date

long milli = date.getTime();

This is for get time in milliseconds.

Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT

HTML text-overflow ellipsis detection

Answer from italo is very good! However let me refine it a little:

function isEllipsisActive(e) {
   var tolerance = 2; // In px. Depends on the font you are using
   return e.offsetWidth + tolerance < e.scrollWidth;
}

Cross browser compatibility

If, in fact, you try the above code and use console.log to print out the values of e.offsetWidth and e.scrollWidth, you will notice, on IE, that, even when you have no text truncation, a value difference of 1px or 2px is experienced.

So, depending on the font size you use, allow a certain tolerance!

what is the difference between XSD and WSDL

If someone is looking for analogy , this answer might be helpful.

WSDL is like 'SHOW TABLE STATUS' command in mysql. It defines all the elements(request type, response type, format of URL to hit request,etc.,) which should be part of XML. By definition I mean: 1) Names of request or response 2) What should be treated as input , what should be treated as output.

XSD is like DESCRIBE command in mysql. It tells what all variables and their types, a request and response contains.

Mysql Compare two datetime fields

You can use the following SQL to compare both date and time -

Select * From temp where mydate > STR_TO_DATE('2009-06-29 04:00:44', '%Y-%m-%d %H:%i:%s');

Attached mysql output when I used same SQL on same kind of table and field that you mentioned in the problem-

enter image description here

It should work perfect.

How to run SUDO command in WinSCP to transfer files from Windows to linux

I do have the same issue, and I am not sure whether it is possible or not,

tried the above solutions are not worked for me.

for a workaround, I am going with moving the files to my HOME directory, editing and replacing the files with SSH.

Call web service in excel

Yes You Can!

I worked on a project that did that (see comment). Unfortunately no code samples from that one, but googling revealed these:

How you can integrate data from several Web services using Excel and VBA

STEP BY STEP: Consuming Web Services through VBA (Excel or Word)

VBA: Consume Soap Web Services

Create JSON object dynamically via JavaScript (Without concate strings)

JavaScript

var myObj = {
   id: "c001",
   name: "Hello Test"
}

Result(JSON)

{
   "id": "c001",
   "name": "Hello Test"
}

From inside of a Docker container, how do I connect to the localhost of the machine?

None of the answers worked for me when using Docker Toolbox on Windows 10 Home, but 10.0.2.2 did, since it uses VirtualBox which exposes the host to the VM on this address.

UIScrollView scroll to bottom programmatically

Swift:

You could use an extension like this:

extension UIScrollView {
    func scrollsToBottom(animated: Bool) {
        let bottomOffset = CGPoint(x: 0, y: contentSize.height - bounds.size.height)
        setContentOffset(bottomOffset, animated: animated)
    }
}

Use:

scrollView.scrollsToBottom(animated: true)

How to select distinct rows in a datatable and store into an array

string[] TobeDistinct = {"Name","City","State"};
DataTable dtDistinct = GetDistinctRecords(DTwithDuplicate, TobeDistinct);

//Following function will return Distinct records for Name, City and State column.
public static DataTable GetDistinctRecords(DataTable dt, string[] Columns)
{
    DataTable dtUniqRecords = new DataTable();
    dtUniqRecords = dt.DefaultView.ToTable(true, Columns);
    return dtUniqRecords;
}

Eclipse: How do you change the highlight color of the currently selected method/expression?

1 - right click the highlight whose color you want to change

2 - select "Properties" in the popup menu

3 - choose the new color (as coobird suggested)

This solution is easy because you dont have to search for the highlight by its name ("Ocurrence" or "Write Ocurrence" etc), just right click and the appropriate window is shown.

Java, Shifting Elements in an Array

Manipulating arrays in this way is error prone, as you've discovered. A better option may be to use a LinkedList in your situation. With a linked list, and all Java collections, array management is handled internally so you don't have to worry about moving elements around. With a LinkedList you just call remove and then addLast and the you're done.

jQuery location href

I think you are looking for:

window.location = 'http://someUrl.com';

It's not jQuery; it's pure JavaScript.

What is the difference between a Relational and Non-Relational Database?

In layman terms it's strongly structured vs unstructured, which implies that you have different degrees of adaptability for your DB. Differences arise in indexation particularly as you need to ensure that a certain reference index can link to a another item -> this a relation. The more strict structure of relational DB comes from this requirement.

To note that NosDB apaprently provides both relational and non relational DBs and a way to query both http://www.alachisoft.com/nosdb/sql-cheat-sheet.html

Fuzzy matching using T-SQL

do it this way

         create table person(
         personid int identity(1,1) primary key,
         firstname varchar(20),
         lastname varchar(20),
         addressindex int,
         sound varchar(10)
         )

and later on create a trigger

         create trigger trigoninsert for dbo.person
         on insert 
         as
         declare @personid int;
         select @personid=personid from inserted;
         update person
         set sound=soundex(firstname) where personid=@personid;

now what i can do is i can create a procedure which looks something like this

         create procedure getfuzzi(@personid int)
          as
         declare @sound varchar(10);
         set @sound=(select sound from person where personid=@personid;
         select personid,firstname,lastname,addressindex from person
         where sound=@sound

this will return you all the names that are nearly in match with the names provided by for a particular personid

SQLite UPSERT / UPDATE OR INSERT

The problem with all presented answers it complete lack of taking triggers (and probably other side effects) into account. Solution like

INSERT OR IGNORE ...
UPDATE ...

leads to both triggers executed (for insert and then for update) when row does not exist.

Proper solution is

UPDATE OR IGNORE ...
INSERT OR IGNORE ...

in that case only one statement is executed (when row exists or not).

How do I compile jrxml to get jasper?

with maven it is automatic:

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>jasperreports-maven-plugin</artifactId>
  <configuration>
    <outputDirectory>target/${project.artifactId}/WEB-INF/reports</outputDirectory>
  </configuration>
  <executions>
    <execution>
      <phase>prepare-package</phase>
      <inherited>false</inherited>
      <goals>
         <goal>compile-reports</goal>
      </goals>
    </execution>
  </executions>
  <dependencies>
    <dependency>
       <groupId>net.sf.jasperreports</groupId>
       <artifactId>jasperreports</artifactId>
       <version>3.7.6</version> 
    </dependency>
    <dependency>
       <groupId>log4j</groupId>
       <artifactId>log4j</artifactId>
       <version>1.2.16</version>
       <type>jar</type>
     </dependency>
  </dependencies>
</plugin>

How to randomize Excel rows

I usually do as you describe:
Add a separate column with a random value (=RAND()) and then perform a sort on that column.

Might be more complex and prettyer ways (using macros etc), but this is fast enough and simple enough for me.

Which way is best for creating an object in JavaScript? Is `var` necessary before an object property?

Majorly there are 3 ways of creating Objects-

Simplest one is using object literals.

const myObject = {}

Though this method is the simplest but has a disadvantage i.e if your object has behaviour(functions in it),then in future if you want to make any changes to it you would have to change it in all the objects.

So in that case it is better to use Factory or Constructor Functions.(anyone that you like)

Factory Functions are those functions that return an object.e.g-

function factoryFunc(exampleValue){
   return{
      exampleProperty: exampleValue 
   }
}

Constructor Functions are those functions that assign properties to objects using "this" keyword.e.g-

function constructorFunc(exampleValue){
   this.exampleProperty= exampleValue;
}
const myObj= new constructorFunc(1);

What is FCM token in Firebase?

FirebaseInstanceIdService is now deprecated. you should get the Token in the onNewToken method in the FirebaseMessagingService.

Check out the docs

TypeScript and array reduce function

It's actually the JavaScript array reduce function rather than being something specific to TypeScript.

As described in the docs: Apply a function against an accumulator and each value of the array (from left-to-right) as to reduce it to a single value.

Here's an example which sums up the values of an array:

_x000D_
_x000D_
let total = [0, 1, 2, 3].reduce((accumulator, currentValue) => accumulator + currentValue);_x000D_
console.log(total);
_x000D_
_x000D_
_x000D_

The snippet should produce 6.

How does Go update third-party packages?

Since the question mentioned third-party libraries and not all packages then you probably want to fall back to using wildcards.

A use case being: I just want to update all my packages that are obtained from the Github VCS, then you would just say:

go get -u github.com/... // ('...' being the wildcard). 

This would go ahead and only update your github packages in the current $GOPATH

Same applies for within a VCS too, say you want to only upgrade all the packages from ogranizaiton A's repo's since as they have released a hotfix you depend on:

go get -u github.com/orgA/...

How can I change the color of my prompt in zsh (different from normal text)?

man zshall and search for PROMPT EXPANSION

After reading the existing answers here, several of them are conflicting. I've tried the various approaches on systems running zsh 4.2 and 5+ and found that the reason these answers are conflicting is that they do not say which version of ZSH they are targeted at. Different versions use different syntax for this and some of them require various autoloads.

So, the best bet is probably to man zshall and search for PROMPT EXPANSION to find out all the rules for your particular installation of zsh. Note in the comments, things like "I use Ubuntu 11.04 or 10.4 or OSX" Are not very meaningful as it's unclear which version of ZSH you are using. Ubuntu 11.04 does not imply a newer version of ZSH than ubuntu 10.04. There may be any number of reasons that an older version was installed. For that matter a newer version of ZSH does not imply which syntax to use without knowing which version of ZSH it is.

Php $_POST method to get textarea value

Try to use different id and name parameters, currently you have same here. Please visit the link below for the same, this might be help you :

Issue using $_POST with a textarea

How to convert PDF files to images

You can use Ghostscript to convert PDF to images.

To use Ghostscript from .NET you can take a look at Ghostscript.NET library (managed wrapper around the Ghostscript library).

To produce image from the PDF by using Ghostscript.NET, take a look at RasterizerSample.

To combine multiple images into the single image, check out this sample: http://www.niteshluharuka.com/2012/08/combine-several-images-to-form-a-single-image-using-c/#

How to find which columns contain any NaN value in Pandas dataframe

i use these three lines of code to print out the column names which contain at least one null value:

for column in dataframe:
    if dataframe[column].isnull().any():
       print('{0} has {1} null values'.format(column, dataframe[column].isnull().sum()))

Is it possible to decrypt SHA1

SHA1 is a one way hash. So you can not really revert it.

That's why applications use it to store the hash of the password and not the password itself.

Like every hash function SHA-1 maps a large input set (the keys) to a smaller target set (the hash values). Thus collisions can occur. This means that two values of the input set map to the same hash value.

Obviously the collision probability increases when the target set is getting smaller. But vice versa this also means that the collision probability decreases when the target set is getting larger and SHA-1's target set is 160 bit.

Jeff Preshing, wrote a very good blog about Hash Collision Probabilities that can help you to decide which hash algorithm to use. Thanks Jeff.

In his blog he shows a table that tells us the probability of collisions for a given input set.

Hash Collision Probabilities Table

As you can see the probability of a 32-bit hash is 1 in 2 if you have 77163 input values.

A simple java program will show us what his table shows:

public class Main {

    public static void main(String[] args) {
        char[] inputValue = new char[10];

        Map<Integer, String> hashValues = new HashMap<Integer, String>();

        int collisionCount = 0;

        for (int i = 0; i < 77163; i++) {
            String asString = nextValue(inputValue);
            int hashCode = asString.hashCode();
            String collisionString = hashValues.put(hashCode, asString);
            if (collisionString != null) {
                collisionCount++;
                System.out.println("Collision: " + asString + " <-> " + collisionString);
            }
        }

        System.out.println("Collision count: " + collisionCount);
    }

    private static String nextValue(char[] inputValue) {
        nextValue(inputValue, 0);

        int endIndex = 0;
        for (int i = 0; i < inputValue.length; i++) {
            if (inputValue[i] == 0) {
                endIndex = i;
                break;
            }
        }

        return new String(inputValue, 0, endIndex);
    }

    private static void nextValue(char[] inputValue, int index) {
        boolean increaseNextIndex = inputValue[index] == 'z';

        if (inputValue[index] == 0 || increaseNextIndex) {
            inputValue[index] = 'A';
        } else {
            inputValue[index] += 1;
        }

        if (increaseNextIndex) {
            nextValue(inputValue, index + 1);
        }

    }

}

My output end with:

Collision: RvV <-> SWV
Collision: SvV <-> TWV
Collision: TvV <-> UWV
Collision: UvV <-> VWV
Collision: VvV <-> WWV
Collision: WvV <-> XWV
Collision count: 35135

It produced 35135 collsions and that's the nearly the half of 77163. And if I ran the program with 30084 input values the collision count is 13606. This is not exactly 1 in 10, but it is only a probability and the example program is not perfect, because it only uses the ascii chars between A and z.

Let's take the last reported collision and check

System.out.println("VvV".hashCode());
System.out.println("WWV".hashCode());

My output is

86390
86390

Conclusion:

If you have a SHA-1 value and you want to get the input value back you can try a brute force attack. This means that you have to generate all possible input values, hash them and compare them with the SHA-1 you have. But that will consume a lot of time and computing power. Some people created so called rainbow tables for some input sets. But these do only exist for some small input sets.

And remember that many input values map to a single target hash value. So even if you would know all mappings (which is impossible, because the input set is unbounded) you still can't say which input value it was.

Command-line Git on Windows

In the latest version (v2.19 for Windows when I'm writing), if you choose the option "Use git in Windows command prompt" (or sth similar, please read the options carefully when you install git), you should be able to use git commands in windows command prompt or windows powershell without any additional setting. Just remember to restart the command line tool after you install git.

Remove last 3 characters of string or number in javascript

you just need to divide the Date Time stamp by 1000 like:

var a = 1437203995000;
a = (a)/1000;

Change URL parameters

2020 Solution: sets the variable or removes iti if you pass null or undefined to the value.

var setSearchParam = function(key, value) {
    if (!window.history.pushState) {
        return;
    }

    if (!key) {
        return;
    }

    var url = new URL(window.location.href);
    var params = new window.URLSearchParams(window.location.search);
    if (value === undefined || value === null) {
        params.delete(key);
    } else {
        params.set(key, value);
    }

    url.search = params;
    url = url.toString();
    window.history.replaceState({url: url}, null, url);
}

Build a simple HTTP server in C

Use platform specific socket functions to encapsulate the HTTP protocol, just like guys behind Apache did.

Permanently add a directory to PYTHONPATH?

You could add the path via your pythonrc file, which defaults to ~/.pythonrc on linux. ie.

import sys
sys.path.append('/path/to/dir')

You could also set the PYTHONPATH environment variable, in a global rc file, such ~/.profile on mac or linux, or via Control Panel -> System -> Advanced tab -> Environment Variables on windows.

How to fix request failed on channel 0

PTY allocation request failed on channel 0

There is a limit of 256 pseudo terminals on a system. Maybe you have an application that is leaking pseudo terminals. Use

lsof /dev/pts/*

to see what processes have open pseudo-terminals

shell request failed on channel 0

I was getting this error (without PTY allocation error). It turns out that one of my applications (QtCreator 3.0.?) was leaking Zombie processes. Other users were able to log in so I might have been hitting my per user process quota (if there is such a thing). I've updated to QtCreator 3.3. So far so good.

How are "mvn clean package" and "mvn clean install" different?

Package & install are various phases in maven build lifecycle. package phase will execute all phases prior to that & it will stop with packaging the project as a jar. Similarly install phase will execute all prior phases & finally install the project locally for other dependent projects.

For understanding maven build lifecycle please go through the following link https://ayolajayamaha.blogspot.in/2014/05/difference-between-mvn-clean-install.html

Giving graphs a subtitle in matplotlib

Just use TeX ! This works :

title(r"""\Huge{Big title !} \newline \tiny{Small subtitle !}""")

EDIT: To enable TeX processing, you need to add the "usetex = True" line to matplotlib parameters:

fig_size = [12.,7.5]
params = {'axes.labelsize': 8,
      'text.fontsize':   6,
      'legend.fontsize': 7,
      'xtick.labelsize': 6,
      'ytick.labelsize': 6,
      'text.usetex': True,       # <-- There 
      'figure.figsize': fig_size,
      }
rcParams.update(params)

I guess you also need a working TeX distribution on your computer. All details are given at this page:

http://matplotlib.org/users/usetex.html

The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication

In my case the reason was some wrong certificate that could not be loaded. I found out about it from the Event Viewer, under System:

A fatal error occurred when attempting to access the TLS server credential private key. The error code returned from the cryptographic module is 0x8009030D. The internal error state is 10001.

Uncaught Error: Unexpected module 'FormsModule' declared by the module 'AppModule'. Please add a @Pipe/@Directive/@Component annotation

Things you can add to declarations: [] in modules

  • Pipe
  • Directive
  • Component

Pro Tip: The error message explains it - Please add a @Pipe/@Directive/@Component annotation.

calling java methods in javascript code

When it is on server side, use web services - maybe RESTful with JSON.

  • create a web service (for example with Tomcat)
  • call its URL from JavaScript (for example with JQuery or dojo)

When Java code is in applet you can use JavaScript bridge. The bridge between the Java and JavaScript programming languages, known informally as LiveConnect, is implemented in Java plugin. Formerly Mozilla-specific LiveConnect functionality, such as the ability to call static Java methods, instantiate new Java objects and reference third-party packages from JavaScript, is now available in all browsers.

Below is example from documentation. Look at methodReturningString.

Java code:

public class MethodInvocation extends Applet {
    public void noArgMethod() { ... }
    public void someMethod(String arg) { ... }
    public void someMethod(int arg) { ... }
    public int  methodReturningInt() { return 5; }
    public String methodReturningString() { return "Hello"; }
    public OtherClass methodReturningObject() { return new OtherClass(); }
}

public class OtherClass {
    public void anotherMethod();
}

Web page and JavaScript code:

<applet id="app"
        archive="examples.jar"
        code="MethodInvocation" ...>
</applet>
<script language="javascript">
    app.noArgMethod();
    app.someMethod("Hello");
    app.someMethod(5);
    var five = app.methodReturningInt();
    var hello = app.methodReturningString();
    app.methodReturningObject().anotherMethod();
</script>

How to show/hide an element on checkbox checked/unchecked states using jQuery?

Try this

<script>
    $().ready(function(){
        $('.coupon_question').live('click',function() 
        {
            if ($('.coupon_question').is(':checked')) {
                $(".answer").show();
            } else {
                $(".answer").hide();
            } 
        });
    });
</script>

How to initialize an array of objects in Java

thePlayers[i] = new Player(i); I just deleted the i inside Player(i); and it worked.

so the code line should be:

thePlayers[i] = new Player9();

Add external libraries to CMakeList.txt c++

I would start with upgrade of CMAKE version.

You can use INCLUDE_DIRECTORIES for header location and LINK_DIRECTORIES + TARGET_LINK_LIBRARIES for libraries

INCLUDE_DIRECTORIES(your/header/dir)
LINK_DIRECTORIES(your/library/dir)
rosbuild_add_executable(kinectueye src/kinect_ueye.cpp)
TARGET_LINK_LIBRARIES(kinectueye lib1 lib2 lib2 ...)

note that lib1 is expanded to liblib1.so (on Linux), so use ln to create appropriate links in case you do not have them

How to pass a view's onClick event to its parent on Android?

Put

android:duplicateParentState="true"

in child then the views get its drawable state (focused, pressed, etc.) from its direct parent rather than from itself. you can set onclick for parent and it call on child clicked

"The file "MyApp.app" couldn't be opened because you don't have permission to view it" when running app in Xcode 6 Beta 4

I've fixed it by cleaning a build folder. Just went to 'Product' menu and Option+Click 'Clean'. After that a problem was resolved.

How to replace (or strip) an extension from a filename in Python?

I'm surprised nobody has mentioned pathlib's with_name. This solution works with multiple extensions (i.e. it replaces all of the extensions.)

import pathlib

p = pathlib.Path('/some/path/somefile.txt')
p = p.with_name(p.stem).with_suffix('.jpg')

How to get the string size in bytes?

Use strlen to get the length of a null-terminated string.

sizeof returns the length of the array not the string. If it's a pointer (char *s), not an array (char s[]), it won't work, since it will return the size of the pointer (usually 4 bytes on 32-bit systems). I believe an array will be passed or returned as a pointer, so you'd lose the ability to use sizeof to check the size of the array.

So, only if the string spans the entire array (e.g. char s[] = "stuff"), would using sizeof for a statically defined array return what you want (and be faster as it wouldn't need to loop through to find the null-terminator) (if the last character is a null-terminator, you will need to subtract 1). If it doesn't span the entire array, it won't return what you want.

An alternative to all this is actually storing the size of the string.

how to get login option for phpmyadmin in xampp

If you wish to go to the login page of phpmyadmin, click the "exit" button (the second one from left to right under the main logo "phpmyadmin").

Corrupted Access .accdb file: "Unrecognized Database Format"

After much struggle with this same issue I was able to solve the problem by installing the 32 bit version of the 2010 Access Database Engine. For some reason the 64bit version generates this error...

Python: avoid new line with print command

You simply need to do:

print 'lakjdfljsdf', # trailing comma

However in:

print 'lkajdlfjasd', 'ljkadfljasf'

There is implicit whitespace (ie ' ').

You also have the option of:

import sys
sys.stdout.write('some data here without a new line')

Javascript seconds to minutes and seconds

Moment.js

If you are using Moment.js then you can use there built in Duration object

const duration = moment.duration(4825, 'seconds');

const h = duration.hours(); // 1
const m = duration.minutes(); // 20
const s = duration.seconds(); // 25

IIS: Idle Timeout vs Recycle

IIS now has

Idle Time-out Action : Suspend setting

Suspending is just freezes the process and it is much more efficient than the destroying the process.

HREF="" automatically adds to current page URL (in PHP). Can't figure it out

In any case, your code will generate invalid markup: You shouldn't wrap block contents in a link. tags don't work like this. If you want this effect you should use js or create an absolutely positioned link above the content (z-index). More on this here: Make a div into a link.

You should make sure to validate your code when it renders: http://validator.w3.org

"The stylesheet was not loaded because its MIME type, "text/html" is not "text/css"

In Ubuntu In the conf file: /etc/apache2/sites-enabled/your-file.conf

change

AddHandler application/x-httpd-php .js .xml .htc .css

to:

AddHandler application/x-httpd-php .js .xml .htc

VSCode cannot find module '@angular/core' or any other modules

If you did what I (foolishly) did... Which was drag and drop a component folder into my project then you'll probably be able to solve it by doing what I did to fix it.

Explanation: Basically, by some means Angualar CLI must tell InteliJ what @angular means. If you just plop the file in your project without using the Angular CLI i.e. ng g componentName --module=app.module then Angular CLI doesn't know to update this reference so IntelliJ has no idea what it is.

Approach: Trigger the Angular CLI to update references of @angular. I currently know only one way to do this...

Implementation: Add a new component at the same level as the component your having issues with. ng g tempComponent --module=app.module This should force the Angular CLI to run and update these references in the project. Now just delete the tempComponent you just created and don't forget to remove any reference to it in app.module.

Hope this helps someone else out.

internet explorer 10 - how to apply grayscale filter?

Use this jQuery plugin https://gianlucaguarini.github.io/jQuery.BlackAndWhite/

That seems to be the only one cross-browser solution. Plus it has a nice fade in and fade out effect.

$('.bwWrapper').BlackAndWhite({
    hoverEffect : true, // default true
    // set the path to BnWWorker.js for a superfast implementation
    webworkerPath : false,
    // to invert the hover effect
    invertHoverEffect: false,
    // this option works only on the modern browsers ( on IE lower than 9 it remains always 1)
    intensity:1,
    speed: { //this property could also be just speed: value for both fadeIn and fadeOut
        fadeIn: 200, // 200ms for fadeIn animations
        fadeOut: 800 // 800ms for fadeOut animations
    },
    onImageReady:function(img) {
        // this callback gets executed anytime an image is converted
    }
});

Inverse of a matrix using numpy

Another way to do this is to use the numpy matrix class (rather than a numpy array) and the I attribute. For example:

>>> m = np.matrix([[2,3],[4,5]])
>>> m.I
matrix([[-2.5,  1.5],
       [ 2. , -1. ]])

How do I create a new Git branch from an old commit?

git checkout -b NEW_BRANCH_NAME COMMIT_ID

This will create a new branch called 'NEW_BRANCH_NAME' and check it out.

("check out" means "to switch to the branch")

git branch NEW_BRANCH_NAME COMMIT_ID

This just creates the new branch without checking it out.


in the comments many people seem to prefer doing this in two steps. here's how to do so in two steps:

git checkout COMMIT_ID
# you are now in the "detached head" state
git checkout -b NEW_BRANCH_NAME

Update OpenSSL on OS X with Homebrew

If you're using Homebrew /usr/local/bin should already be at the front of $PATH or at least come before /usr/bin. If you now run brew link --force openssl in your terminal window, open a new one and run which openssl in it. It should now show openssl under /usr/local/bin.

Oracle comparing timestamp with date

to_date format worked for me. Please consider the date formats: MON-, MM, ., -.

t.start_date >= to_date('14.11.2016 04:01:39', 'DD.MM.YYYY HH24:MI:SS')
t.start_date <=to_date('14.11.2016 04:10:07', 'DD.MM.YYYY HH24:MI:SS')

How to check all versions of python installed on osx and centos

Here is a cleaner way to show them (technically without symbolic links):

ls -1 /usr/bin/python* | grep '[2-3].[0-9]$'

Where grep filters the output of ls that that has that numeric pattern at the end ($).

Or using find:

find /usr/bin/python* ! -type l

Which shows all the different (!) of symbolic link type (-type l).

How to Query an NTP Server using C#?

I know the topic is quite old, but such tools are always handy. I've used the resources above and created a version of NtpClient which allows asynchronously to acquire accurate time, instead of event based.

 /// <summary>
/// Represents a client which can obtain accurate time via NTP protocol.
/// </summary>
public class NtpClient
{
    private readonly TaskCompletionSource<DateTime> _resultCompletionSource;

    /// <summary>
    /// Creates a new instance of <see cref="NtpClient"/> class.
    /// </summary>
    public NtpClient()
    {
        _resultCompletionSource = new TaskCompletionSource<DateTime>();
    }

    /// <summary>
    /// Gets accurate time using the NTP protocol with default timeout of 45 seconds.
    /// </summary>
    /// <returns>Network accurate <see cref="DateTime"/> value.</returns>
    public async Task<DateTime> GetNetworkTimeAsync()
    {
        return await GetNetworkTimeAsync(TimeSpan.FromSeconds(45));
    }

    /// <summary>
    /// Gets accurate time using the NTP protocol with default timeout of 45 seconds.
    /// </summary>
    /// <param name="timeoutMs">Operation timeout in milliseconds.</param>
    /// <returns>Network accurate <see cref="DateTime"/> value.</returns>
    public async Task<DateTime> GetNetworkTimeAsync(int timeoutMs)
    {
        return await GetNetworkTimeAsync(TimeSpan.FromMilliseconds(timeoutMs));
    }

    /// <summary>
    /// Gets accurate time using the NTP protocol with default timeout of 45 seconds.
    /// </summary>
    /// <param name="timeout">Operation timeout.</param>
    /// <returns>Network accurate <see cref="DateTime"/> value.</returns>
    public async Task<DateTime> GetNetworkTimeAsync(TimeSpan timeout)
    {
        using (var socket = new DatagramSocket())
        using (var ct = new CancellationTokenSource(timeout))
        {
            ct.Token.Register(() => _resultCompletionSource.TrySetCanceled());

            socket.MessageReceived += OnSocketMessageReceived;
            //The UDP port number assigned to NTP is 123
            await socket.ConnectAsync(new HostName("pool.ntp.org"), "123");
            using (var writer = new DataWriter(socket.OutputStream))
            {
                // NTP message size is 16 bytes of the digest (RFC 2030)
                var ntpBuffer = new byte[48];

                // Setting the Leap Indicator, 
                // Version Number and Mode values
                // LI = 0 (no warning)
                // VN = 3 (IPv4 only)
                // Mode = 3 (Client Mode)
                ntpBuffer[0] = 0x1B;

                writer.WriteBytes(ntpBuffer);
                await writer.StoreAsync();
                var result = await _resultCompletionSource.Task;
                return result;
            }
        }
    }

    private void OnSocketMessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
    {
        try
        {
            using (var reader = args.GetDataReader())
            {
                byte[] response = new byte[48];
                reader.ReadBytes(response);
                _resultCompletionSource.TrySetResult(ParseNetworkTime(response));
            }
        }
        catch (Exception ex)
        {
            _resultCompletionSource.TrySetException(ex);
        }
    }

    private static DateTime ParseNetworkTime(byte[] rawData)
    {
        //Offset to get to the "Transmit Timestamp" field (time at which the reply 
        //departed the server for the client, in 64-bit timestamp format."
        const byte serverReplyTime = 40;

        //Get the seconds part
        ulong intPart = BitConverter.ToUInt32(rawData, serverReplyTime);

        //Get the seconds fraction
        ulong fractPart = BitConverter.ToUInt32(rawData, serverReplyTime + 4);

        //Convert From big-endian to little-endian
        intPart = SwapEndianness(intPart);
        fractPart = SwapEndianness(fractPart);

        var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);

        //**UTC** time
        DateTime networkDateTime = (new DateTime(1900, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)).AddMilliseconds((long)milliseconds);
        return networkDateTime;
    }

    // stackoverflow.com/a/3294698/162671
    private static uint SwapEndianness(ulong x)
    {
        return (uint)(((x & 0x000000ff) << 24) +
                       ((x & 0x0000ff00) << 8) +
                       ((x & 0x00ff0000) >> 8) +
                       ((x & 0xff000000) >> 24));
    }
}

Usage:

var ntp = new NtpClient();
var accurateTime = await ntp.GetNetworkTimeAsync(TimeSpan.FromSeconds(10));

How to extract closed caption transcript from YouTube video?

There is a free python tool called YouTube transcript API

You can use it in scripts or as a command line tool:

pip install youtube_transcript_api

Keep a line of text as a single line - wrap the whole line or none at all

You could also put non-breaking spaces (&nbsp;) in lieu of the spaces so that they're forced to stay together.

How do I wrap this line of text
-&nbsp;asked&nbsp;by&nbsp;Peter&nbsp;2&nbsp;days&nbsp;ago

One or more types required to compile a dynamic expression cannot be found. Are you missing references to Microsoft.CSharp.dll and System.Core.dll?

None of these worked for me.

My class libraries were definitely all referencing both System.Core and Microsoft.CSharp. Web Application was 4.0 and couldn't upgrade to 4.5 due to support issues.

I was encountering the error compiling a razor template using the Razor Engine, and only encountering it intermittently, like after web application has been restarted.

The solution that worked for me was manually loading the assembly then reattempting the same operation...

        bool retry = true;
        while (retry)
        {
            try
            {
                string textTemplate = File.ReadAllText(templatePath);
                Razor.CompileWithAnonymous(textTemplate, templateFileName);
                retry = false;
            }
            catch (TemplateCompilationException ex)
            {
                LogTemplateException(templatePath, ex);
                retry = false;

                if (ex.Errors.Any(e  => e.ErrorNumber == "CS1969"))
                {
                    try
                    {
                        _logger.InfoFormat("Attempting to manually load the Microsoft.CSharp.RuntimeBinder.Binder");
                        Assembly csharp = Assembly.Load("Microsoft.CSharp, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
                        Type type = csharp.GetType("Microsoft.CSharp.RuntimeBinder.Binder");
                        retry = true;
                    }
                    catch(Exception exLoad)
                    {
                        _logger.Error("Failed to manually load runtime binder", exLoad);
                    }
                }

                if (!retry)
                    throw;
            }
        }

Hopefully this might help someone else out there.

R: numeric 'envir' arg not of length one in predict()

There are several problems here:

  1. The newdata argument of predict() needs a predictor variable. You should thus pass it values for Coupon, instead of Total, which is the response variable in your model.

  2. The predictor variable needs to be passed in as a named column in a data frame, so that predict() knows what the numbers its been handed represent. (The need for this becomes clear when you consider more complicated models, having more than one predictor variable).

  3. For this to work, your original call should pass df in through the data argument, rather than using it directly in your formula. (This way, the name of the column in newdata will be able to match the name on the RHS of the formula).

With those changes incorporated, this will work:

model <- lm(Total ~ Coupon, data=df)
new <- data.frame(Coupon = df$Coupon)
predict(model, newdata = new, interval="confidence")

Why powershell does not run Angular commands?

open windows powershell, run as administrater and SetExecution policy as Unrestricted then it will work.

How to create an android app using HTML 5

The WebIntoApp.com V.2 allows you to convert HTML5 / JS / CSS into a mobile app for Android APK (free) and iOS.

(I'm the author)

ASP.NET Bundles how to disable minification

Search for EnableOptimizations keyword in your project

So if you find

BundleTable.EnableOptimizations = true;

turn it false.

This does disable minification, And it also disables bundling entirely

How does origin/HEAD get set?

Disclaimer: this is an update to Cascabel's answer, which I'm writing to save the curious some time.

I tried in vain to replicate (in Git 2.0.1) the remote HEAD is ambiguous message that Cascabel mentions in his answer; so I did a bit of digging (by cloning https://github.com/git/git and searching the log). It used to be that

Determining HEAD is ambiguous since it is done by comparing SHA1s.

In the case of multiple matches we return refs/heads/master if it
matches, else we return the first match we encounter. builtin-remote
needs all matches returned to it, so add a flag for it to request such.

(Commit 4229f1fa325870d6b24fe2a4c7d2ed5f14c6f771, dated Feb 27, 2009, found with git log --reverse --grep="HEAD is ambiguous")

However, the ambiguity in question has since been lifted:

One long-standing flaw in the pack transfer protocol used by "git
clone" was that there was no way to tell the other end which branch
"HEAD" points at, and the receiving end needed to guess.  A new
capability has been defined in the pack protocol to convey this
information so that cloning from a repository with more than one
branches pointing at the same commit where the HEAD is at now
reliably sets the initial branch in the resulting repository.

(Commit 9196a2f8bd46d36a285bdfa03b4540ed3f01f671, dated Nov 8, 2013, found with git log --grep="ambiguous" --grep="HEAD" --all-match)

Edit (thanks to torek):

$ git name-rev --name-only 9196a2f8bd46d36a285bdfa03b4540ed3f01f671
tags/v1.8.4.3~3

This means that, if you're using Git v1.8.4.3 or later, you shouldn't run into any ambiguous-remote-HEAD problem.

JSON encode MySQL results

Code:

$rows = array();

while($r = mysqli_fetch_array($result,MYSQL_ASSOC)) {

 $row_array['result'] = $r;

  array_push($rows,$row_array); // here we push every iteration to an array otherwise you will get only last iteration value
}

echo json_encode($rows);

How to clear the Entry widget after a button is pressed in Tkinter?

Simply define a function and set the value of your Combobox to empty/null or whatever you want. Try the following.

def Reset():
    cmb.set("")

here, cmb is a variable in which you have assigned the Combobox. Now call that function in a button such as,

btn2 = ttk.Button(root, text="Reset",command=Reset)

Open button in new window?

If you strictly want to stick to using button,Then simply create an open window function as follows:

    <script>
function myfunction() {
    window.open("mynewpage.html");
}
</script>

Then in your html do the following with your button:

Join

So you would have something like this:

 <body>
    <script>
function joinfunction() {
    window.open("mynewpage.html");
}
</script>
<button  onclick="myfunction()" type="button" class="btn btn-default subs-btn">Join</button>

XML shape drawable not rendering desired color

I had a similar problem and found that if you remove the size definition, it works for some reason.

Remove:

<size
    android:width="60dp"
    android:height="40dp" />

from the shape.

Let me know if this works!

Android M - check runtime permission - how to determine if the user checked "Never ask again"?

Here is a nice and easy method to check the current permission status:

    @Retention(RetentionPolicy.SOURCE)
    @IntDef({GRANTED, DENIED, BLOCKED_OR_NEVER_ASKED })
    public @interface PermissionStatus {}

    public static final int GRANTED = 0;
    public static final int DENIED = 1;
    public static final int BLOCKED_OR_NEVER_ASKED = 2;

    @PermissionStatus 
    public static int getPermissionStatus(Activity activity, String androidPermissionName) {
        if(ContextCompat.checkSelfPermission(activity, androidPermissionName) != PackageManager.PERMISSION_GRANTED) {
            if(!ActivityCompat.shouldShowRequestPermissionRationale(activity, androidPermissionName)){
                return BLOCKED_OR_NEVER_ASKED;
            }
            return DENIED;
        }
        return GRANTED;
    }

Caveat: returns BLOCKED_OR_NEVER_ASKED the first app start, before the user accepted/denied the permission through the user prompt (on sdk 23+ devices)

Update:

The Android support library now also seems to have a very similar class android.support.v4.content.PermissionChecker which contains a checkSelfPermission() which returns:

public static final int PERMISSION_GRANTED = 0;
public static final int PERMISSION_DENIED = -1;
public static final int PERMISSION_DENIED_APP_OP = -2;

Best radio-button implementation for IOS

Just want to sum up, there might be 4 ways.

  • If you don't have much space, add a click event for text or button, then show UIPickerView:

UIPickerView

or open a new table view control with a check mark:

UITableView

  • If there is more space, add a table view directly to your main view:

enter image description here

  • The final solution is using UISegmentedControl:

enter image description here

Hope this helps.

Is there a way to set background-image as a base64 encoded image?

Had the same problem with base64. For anyone in the future with the same problem:

url = "data:image/png;base64,iVBORw0KGgoAAAAAAAAyCAYAAAAUYybjAAAgAElE...";

This would work executed from console, but not from within a script:

$img.css("background-image", "url('" + url + "')");

But after playing with it a bit, I came up with this:

var img = new Image();
img.src = url;
$img.css("background-image", "url('" + img.src + "')");

No idea why it works with a proxy image, but it does. Tested on Firefox Dev 37 and Chrome 40.

Hope it helps someone.

EDIT

Investigated a little bit further. It appears that sometimes base64 encoding (at least in my case) breaks with CSS because of line breaks present in the encoded value (in my case value was generated dynamically by ActionScript).

Simply using e.g.:

$img.css("background-image", "url('" + url.replace(/(\r\n|\n|\r)/gm, "") + "')");

works too, and even seems to be faster by a few ms than using a proxy image.

Stop Excel from automatically converting certain text values to dates

In my case, "Sept8" in a csv file generated using R was converted into "8-Sept" by Excel 2013. The problem was solved by using write.xlsx2() function in the xlsx package to generate the output file in xlsx format, which can be loaded by Excel without unwanted conversion. So, if you are given a csv file, you can try loading it into R and converting it into xlsx using the write.xlsx2() function.

How do I increase modal width in Angular UI Bootstrap?

I found it easier to just take over the template from Bootstrap-ui. I have left the commented HTML still in-place to show what I changed.

Overwrite their default template:

<script type="text/ng-template" id="myDlgTemplateWrapper.html">
    <div tabindex="-1" role="dialog" class="modal fade" ng-class="{in: animate}" 
         ng-style="{'z-index': 1050 + index*10, display: 'block'}" ng-click="close($event)"> 
        <!-- <div class="modal-dialog"
            ng-class="{'modal-sm': size == 'sm', 'modal-lg': size == 'lg'}"
            >
            <div class="modal-content"  modal-transclude></div>
        </div>--> 

        <div modal-transclude>
            <!-- Your content goes here -->
        </div>
    </div>
</script>

Modify your dialog template (note the wrapper DIVs containing "modal-dialog" class and "modal-content" class):

<script type="text/ng-template" id="myModalContent.html">
    <div class="modal-dialog {{extraDlgClass}}"
         style="width: {{width}}; max-width: {{maxWidth}}; min-width: {{minWidth}}; ">
        <div class="modal-content">
            <div class="modal-header bg-primary">
                <h3>I am a more flexible modal!</h3>
            </div>
            <div class="modal-body"
                 style="min-height: {{minHeight}}; height: {{height}}; max-height {{maxHeight}}; ">
                <p>Make me any size you want</p>
            </div>
            <div class="modal-footer">
                <button class="btn btn-primary" ng-click="ok()">OK</button>
                <button class="btn btn-warning" ng-click="cancel()">Cancel</button>
            </div>
        </div>
    </div>
</script>

And then call the modal with whatever CSS class or style parameters you wish to change (assuming you have already defined "app" somewhere else):

<script type="text/javascript">
    app.controller("myTest", ["$scope", "$modal", function ($scope, $modal)
    {
        //  Adjust these with your parameters as needed

        $scope.extraDlgClass = undefined;

        $scope.width = "70%";
        $scope.height = "200px";
        $scope.maxWidth = undefined;
        $scope.maxHeight = undefined;
        $scope.minWidth = undefined;
        $scope.minHeight = undefined;

        $scope.open = function ()
        {
            $scope.modalInstance = $modal.open(
            {
                backdrop: 'static',
                keyboard: false,
                modalFade: true,

                templateUrl: "myModalContent.html",
                windowTemplateUrl: "myDlgTemplateWrapper.html",
                scope: $scope,
                //size: size,   - overwritten by the extraDlgClass below (use 'modal-lg' or 'modal-sm' if desired)

                extraDlgClass: $scope.extraDlgClass,

                width: $scope.width,
                height: $scope.height,
                maxWidth: $scope.maxWidth,
                maxHeight: $scope.maxHeight,
                minWidth: $scope.minWidth,
                minHeight: $scope.minHeight
            });

            $scope.modalInstance.result.then(function ()
            {
                console.log('Modal closed at: ' + new Date());
            },
            function ()
            {
                console.log('Modal dismissed at: ' + new Date());
            });
        };

        $scope.ok = function ($event)
        {
            if ($event)
                $event.preventDefault();
            $scope.modalInstance.close("OK");
        };

        $scope.cancel = function ($event)
        {
            if ($event)
                $event.preventDefault();
            $scope.modalInstance.dismiss('cancel');
        };

        $scope.openFlexModal = function ()
        {
            $scope.open();
        }

    }]);
</script>

Add an "open" button and fire away.

    <button ng-controller="myTest" class="btn btn-default" type="button" ng-click="openFlexModal();">Open Flex Modal!</button>

Now you can add whatever extra class you want, or simply change width/height sizes as necessary.

I further enclosed it within a wrapper directive, which is should be trivial from this point forward.

Cheers.

In LaTeX, how can one add a header/footer in the document class Letter?

After I removed

\usepackage{fontspec}% font selecting commands 
\usepackage{xunicode}% unicode character macros 
\usepackage{xltxtra} % some fixes/extras 

it seems to have worked "correctly".

It may be worth noting that the headers and footers only appear from page 2 onwards. Although I've tried the fix for this given in the fancyhdr documentation, I can't get it to work either.

FYI: MikTeX 2.7 under Vista

Regex date validation for yyyy-mm-dd

This will match yyyy-mm-dd and also yyyy-m-d:

^\d{4}\-(0?[1-9]|1[012])\-(0?[1-9]|[12][0-9]|3[01])$

Regular expression visualization

If you're looking for an exact match for yyyy-mm-dd then try this

^\d{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01])$

or use this one if you need to find a date inside a string like The date is 2017-11-30

\d{4}\-(0?[1-9]|1[012])\-(0?[1-9]|[12][0-9]|3[01])*

https://regex101.com/r/acvpss/1

Launch Image does not show up in my iOS App

One way is to also add "Launch Screen" (LaunchScreen.xib), paste the image into UIImageView and then set it to "Horizontal Center in Container" and "Vertical Center in Container" in "Align" if you are using Auto Layout.

Screen: http://i.stack.imgur.com/CfnHT.png

Don't forget to put LaunchScreen.xib into "Launch Screen File".

Detect viewport orientation, if orientation is Portrait display alert message advising user of instructions

You can also use window.matchMedia, which I use and prefer as it closely resembles CSS syntax:

if (window.matchMedia("(orientation: portrait)").matches) {
   // you're in PORTRAIT mode
}

if (window.matchMedia("(orientation: landscape)").matches) {
   // you're in LANDSCAPE mode
}

Tested on iPad 2.

Error sending json in POST to web API service

  1. You have to must add header property Content-Type:application/json
  2. When you define any POST request method input parameter that should be annotated as [FromBody], e.g.:

    [HttpPost]
    public HttpResponseMessage Post([FromBody]ActivityResult ar)
    {
      return new HttpResponseMessage(HttpStatusCode.OK);
    }
    
  3. Any JSON input data must be raw data.

javascript Unable to get property 'value' of undefined or null reference

The issue is how you're attempting to get the value. Things like...

if ( document.frm_new_user_request.u_isid.value == '' )

won't work. You need to find the element you want to get the value of first. It's not quite like a server side language where you can type in an object's reference name and a period to get or assign values.

document.getElementById('[id goes here]').value;

will work. Note: JavaScript is case-sensitive

I would recommend using:

var variablename = document.getElementById('[id goes here]');

or

var variablename = document.getElementById('[id goes here]').value;

Centering a canvas

Wrapping it with div should work. I tested it in Firefox, Chrome on Fedora 13 (demo).

#content {
   width: 95%;
   height: 95%;
   margin: auto;
}

#myCanvas {
   width: 100%;
   height: 100%;
   border: 1px solid black;
}

And the canvas should be enclosed in tag

<div id="content">
    <canvas id="myCanvas">Your browser doesn't support canvas tag</canvas>
</div>

Let me know if it works. Cheers.

WPF global exception handler

As mentioned above

Application.Current.DispatcherUnhandledException will not catch exceptions that are thrown from another thread then the main thread.

That actual depend on how the thread was created

One case that is not handled by Application.Current.DispatcherUnhandledException is System.Windows.Forms.Timer for which Application.ThreadException can be used to handle these if you run Forms on other threads than the main thread you will need to set Application.ThreadException from each such thread

How to turn on/off MySQL strict mode in localhost (xampp)?

In my case, I need to add:

sql_mode="STRICT_TRANS_TABLES"

under [mysqld] in the file my.ini located in C:\xampp\mysql\bin.

Using Jquery AJAX function with datatype HTML

var datos = $("#id_formulario").serialize();
$.ajax({         
    url: "url.php",      
    type: "POST",                   
    dataType: "html",                 
    data: datos,                 
    success: function (prueba) { 
        alert("funciona!");
    }//FIN SUCCES

});//FIN  AJAX

How to set 777 permission on a particular folder?

777 is a permission in Unix based system with full read/write/execute permission to owner, group and everyone.. in general we give this permission to assets which are not much needed to be hidden from public on a web server, for example images..

You said I am using windows 7. if that means that your web server is Windows based then you should login to that and right click the folder and set permissions to everyone and if you are on a windows client and server is unix/linux based then use some ftp software and in the parent directory right click and change the permission for the folder.

If you want permission to be set on sub-directories too then usually their is option to set permission recursively use that.

And, if you feel like doing it from command line the use putty and login to server and go to the parent directory includes and write the following command

chmod 0777 module_installation/

for recursive

chmod -R 0777 module_installation/

Hope this will help you

JAX-WS client : what's the correct path to access the local WSDL?

Thanks a ton for Bhaskar Karambelkar's answer which explains in detail and fixed my issue. But also I would like to re phrase the answer in three simple steps for someone who is in a hurry to fix

  1. Make your wsdl local location reference as wsdlLocation= "http://localhost/wsdl/yourwsdlname.wsdl"
  2. Create a META-INF folder right under the src. Put your wsdl file/s in a folder under META-INF, say META-INF/wsdl
  3. Create an xml file jax-ws-catalog.xml under META-INF as below

    <catalog xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog" prefer="system"> <system systemId="http://localhost/wsdl/yourwsdlname.wsdl" uri="wsdl/yourwsdlname.wsdl" /> </catalog>

Now package your jar. No more reference to the local directory, it's all packaged and referenced within

MongoDB inserts float when trying to insert integer

Well, it's JavaScript, so what you have in 'value' is a Number, which can be an integer or a float. But there's not really a difference in JavaScript. From Learning JavaScript:

The Number Data Type

Number data types in JavaScript are floating-point numbers, but they may or may not have a fractional component. If they don’t have a decimal point or fractional component, they’re treated as integers—base-10 whole numbers in a range of –253 to 253.

Windows could not start the Apache2 on Local Computer - problem

There is some other program listening on port 80, usual suspects are

  1. Skype (Listens on port 80)
  2. NOD32 (Add Apache to the IMON exceptions' list for it to allow apache to bind)
  3. Some other antivirus (Same as above)

Way to correct it is either shutting down the program that's using the port 80 or configure it to use a different port or configure Apache to listen on a different port with the Listen directive in httpd.conf. In the case of antivirus configure the antivirus to allow Apache to bind on the port you have chosen.

Way to diagnose which app, if any, has bound to port 80 is run the netstat with those options, look for :80 next to the local IP address (second column) and find the PID (last column). Then, on the task manager you can find which process has the PID you got in the previous step. (You might need to add the PID column on the task manager)

C:\Users\vinko>netstat -ao -p tcp

Conexiones activas

  Proto  Dirección local          Dirección remota        Estado           PID
  TCP    127.0.0.1:1110         127.0.0.1:51373        TIME_WAIT       0
  TCP    127.0.0.1:1110         127.0.0.1:51379        TIME_WAIT       0
  TCP    127.0.0.1:1110         127.0.0.1:51381        ESTABLISHED     388
  TCP    127.0.0.1:1110         127.0.0.1:51382        TIME_WAIT       0
  TCP    127.0.0.1:1110         127.0.0.1:51479        TIME_WAIT       0
  TCP    127.0.0.1:1110         127.0.0.1:51481        TIME_WAIT       0
  TCP    127.0.0.1:1110         127.0.0.1:51483        TIME_WAIT       0
  TCP    127.0.0.1:1110         127.0.0.1:51485        ESTABLISHED     388
  TCP    127.0.0.1:1110         127.0.0.1:51487        TIME_WAIT       0
  TCP    127.0.0.1:1110         127.0.0.1:51489        ESTABLISHED     388
  TCP    127.0.0.1:51381        127.0.0.1:1110         ESTABLISHED     5168
  TCP    127.0.0.1:51485        127.0.0.1:1110         ESTABLISHED     5168
  TCP    127.0.0.1:51489        127.0.0.1:1110         ESTABLISHED     5168
  TCP    127.0.0.1:59264        127.0.0.1:59265        ESTABLISHED     5168
  TCP    127.0.0.1:59265        127.0.0.1:59264        ESTABLISHED     5168
  TCP    127.0.0.1:59268        127.0.0.1:59269        ESTABLISHED     5168
  TCP    127.0.0.1:59269        127.0.0.1:59268        ESTABLISHED     5168
  TCP    192.168.1.34:51278     192.168.1.33:445       ESTABLISHED     4
  TCP    192.168.1.34:51383     67.199.15.132:80       ESTABLISHED     388
  TCP    192.168.1.34:51486     66.102.9.18:80         ESTABLISHED     388
  TCP    192.168.1.34:51490     74.125.4.20:80         ESTABLISHED     388

If you want to Disable Skype from listening on port 80 and 443, you can follow the link http://www.mydigitallife.info/disable-skype-from-using-opening-and-listening-on-port-80-and-443-on-local-computer/

"Server Tomcat v7.0 Server at localhost failed to start" without stack trace while it works in terminal

To resolve this issue, you have to delete the .snap file located in the directory:

<workspace-directory>\.metadata\.plugins\org.eclipse.core.resources

After deleting this file, you could start Eclipse with no problem.

What good are SQL Server schemas?

development - each of our devs get their own schema as a sandbox to play in.

Sort a Map<Key, Value> by values

Simple way to sort any map in Java 8 and above

Map<String, Object> mapToSort = new HashMap<>();

List<Map.Entry<String, Object>> list = new LinkedList<>(mapToSort.entrySet());

Collections.sort(list, Comparator.comparing(o -> o.getValue().getAttribute()));

HashMap<String, Object> sortedMap = new LinkedHashMap<>();
for (Map.Entry<String, Object> map : list) {
   sortedMap.put(map.getKey(), map.getValue());
}

if you are using Java 7 and below

Map<String, Object> mapToSort = new HashMap<>();

List<Map.Entry<String, Object>> list = new LinkedList<>(mapToSort.entrySet());

Collections.sort(list, new Comparator<Map.Entry<String, Object>>() {
    @Override
    public int compare(Map.Entry<String, Object> o1, Map.Entry<String, Object> o2) {
       return o1.getValue().getAttribute().compareTo(o2.getValue().getAttribute());      
    }
});

HashMap<String, Object> sortedMap = new LinkedHashMap<>();
for (Map.Entry<String, Object> map : list) {
   sortedMap.put(map.getKey(), map.getValue());
}

How to add "class" to host element?

Another problem is that CSS has to be defined outside component scope, breaking component encapsulation

This is not true. With scss (SASS) you can easily style the component (itself;host) as so:

:host {
    display: block;
    position: absolute;
    width: 100%;
    height: 100%;
    pointer-events: none;
    visibility: hidden;

    &.someClass {
        visibility: visible;
    }
}

This way the encapsulation is "unbroken".

How to decode a Base64 string?

Isn't encoding taking the text TO base64 and decoding taking base64 BACK to text? You seem be mixing them up here. When I decode using this online decoder I get:

BASE64: blahblah
UTF8: nVnV

not the other way around. I can't reproduce it completely in PS though. See sample below:

PS > [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String("blahblah"))
nV?nV?

PS > [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("nVnV"))
blZuVg==

EDIT I believe you're using the wrong encoder for your text. The encoded base64 string is encoded from UTF8(or ASCII) string.

PS > [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String("YmxhaGJsYWg="))
blahblah

PS > [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String("YmxhaGJsYWg="))
????

PS > [System.Text.Encoding]::ASCII.GetString([System.Convert]::FromBase64String("YmxhaGJsYWg="))
blahblah

ctypes - Beginner

Firstly: The >>> code you see in python examples is a way to indicate that it is Python code. It's used to separate Python code from output. Like this:

>>> 4+5
9

Here we see that the line that starts with >>> is the Python code, and 9 is what it results in. This is exactly how it looks if you start a Python interpreter, which is why it's done like that.

You never enter the >>> part into a .py file.

That takes care of your syntax error.

Secondly, ctypes is just one of several ways of wrapping Python libraries. Other ways are SWIG, which will look at your Python library and generate a Python C extension module that exposes the C API. Another way is to use Cython.

They all have benefits and drawbacks.

SWIG will only expose your C API to Python. That means you don't get any objects or anything, you'll have to make a separate Python file doing that. It is however common to have a module called say "wowza" and a SWIG module called "_wowza" that is the wrapper around the C API. This is a nice and easy way of doing things.

Cython generates a C-Extension file. It has the benefit that all of the Python code you write is made into C, so the objects you write are also in C, which can be a performance improvement. But you'll have to learn how it interfaces with C so it's a little bit extra work to learn how to use it.

ctypes have the benefit that there is no C-code to compile, so it's very nice to use for wrapping standard libraries written by someone else, and already exists in binary versions for Windows and OS X.

How do you make div elements display inline?

Having read this question and the answers a couple of times, all I can do is assume that there's been quite a bit of editing going on, and my suspicion is that you've been given the incorrect answer based on not providing enough information. My clue comes from the use of br tag.

Apologies to Darryl. I read class="inline" as style="display: inline". You have the right answer, even if you do use semantically questionable class names ;-)

The miss use of br to provide structural layout rather than for textual layout is far too prevalent for my liking.

If you're wanting to put more than inline elements inside those divs then you should be floating those divs rather than making them inline.

Floated divs:

===== ======= ==   **** ***** ******   +++++ ++++
===== ==== =====   ******** ***** **   ++ +++++++
=== ======== ===   ******* **** ****   
===== ==== =====                       +++++++ ++
====== == ======

Inline divs:

====== ==== ===== ===== == ==== *** ******* ***** ***** 
**** ++++ +++ ++ ++++ ++ +++++++ +++ ++++

If you're after the former, then this is your solution and lose those br tags:

<div style="float: left;" >
  <p>block level content or <span>inline content</span>.</p>
  <p>block level content or <span>inline content</span>.</p>
</div>
<div style="float: left;" >
  <p>block level content or <span>inline content</span>.</p>
  <p>block level content or <span>inline content</span>.</p>
</div>
<div style="float: left;" >
  <p>block level content or <span>inline content</span>.</p>
  <p>block level content or <span>inline content</span>.</p>
</div>

note that the width of these divs is fluid, so feel free to put widths on them if you want to control the behavior.

Thanks, Steve

SEVERE: ContainerBase.addChild: start:org.apache.catalina.LifecycleException: Failed to start error

I had the same error statement following a "Failed to access resource" error message:

Command

#cat callflow-java-logger-1.log.0

Output

Dec 09, 2015 8:09:03 AM org.apache.catalina.loader.WebappLoader startInternal
SEVERE: LifecycleException 
java.io.IOException: Failed to access resource /WEB-INF/lib/ojdbc14.jar

In my case the solution was changing the connector permissions

-rw------- 1 owner creator size date ojdbc14.jar

This file in question wasn't initially located at /WEB-INF/lib, which was probably due to how BIRT works. It can be tricky if you are dealing with a higher number of files.

Set background color in PHP?

You better use CSS for that, after all, this is what CSS is for. If you don't want to do that, go with Dorwand's answer.

Cannot make a static reference to the non-static method

getText is a member of the your Activity so it must be called when "this" exists. Your static variable is initialized when your class is loaded before your Activity is created.

Since you want the variable to be initialized from a Resource string then it cannot be static. If you want it to be static you can initialize it with the String value.

Can I set the height of a div based on a percentage-based width?

This can actually be done with only CSS, but the content inside the div must be absolutely positioned. The key is to use padding as a percentage and the box-sizing: border-box CSS attribute:

_x000D_
_x000D_
div {_x000D_
  border: 1px solid red;_x000D_
  width: 40%;_x000D_
  padding: 40%;_x000D_
  box-sizing: border-box;_x000D_
  position: relative;_x000D_
}_x000D_
p {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
}
_x000D_
<div>_x000D_
  <p>Some unnecessary content.</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Adjust percentages to your liking. Here is a JSFiddle

"Debug certificate expired" error in Eclipse Android plugins

For windows xp go to C:\Documents and Settings\%userprofile%\.android and delete debug.keystore file, restart the eclipse and now your project get build without error.

Example path:

C:\Documents and Settings\raja.ap\.android\

read-here-for-more.

how to add background image to activity?

and dont forget to clean your project after writing these lines you`ll a get an error in your xml file until you´ve cleaned your project in eclipse: Project->Clean...

Jackson serialization: ignore empty values (or null)

Also you can try to use

@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)

if you are dealing with jackson with version below 2+ (1.9.5) i tested it, you can easily use this annotation above the class. Not for specified for the attributes, just for class decleration.

Javascript extends class

Douglas Crockford has some very good explanations of inheritance in JavaScript:

  1. prototypal inheritance: the 'natural' way to do things in JavaScript
  2. classical inheritance: closer to what you find in most OO languages, but kind of runs against the grain of JavaScript

Add horizontal scrollbar to html table

This is an improvement of Serge Stroobandt's answer and works perfectly. It solves the issue of the table not filling the whole page width if it has less columns.

<style> 
 .table_wrapper{
    display: block;
    overflow-x: auto;
    white-space: nowrap;
}
</style>

<div class="table_wrapper">
<table>
...
</table>
</div>

How to add additional fields to form before submit?

$('#form').append('<input type="text" value="'+yourValue+'" />');

How to resolve : Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core"

Try to add like this:

<%@taglib uri="http://java.sun.com/jstl/core" prefix="c"%>

instead of having

<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

UUID max character length

Section 3 of RFC4122 provides the formal definition of UUID string representations. It's 36 characters (32 hex digits + 4 dashes).

Sounds like you need to figure out where the invalid 60-char IDs are coming from and decide 1) if you want to accept them, and 2) what the max length of those IDs might be based on whatever API is used to generate them.

Task<> does not contain a definition for 'GetAwaiter'

The Problem Occur Because the application I was using and the dll i added to my application both have different Versions.

Add this Package- Install-Package Microsoft.Bcl.Async -Version 1.0.168

ADDING THIS PACKAGE async Code becomes Compatible in version 4.0 as well, because Async only work on applications whose Versions are more than or equal to 4.5

how to console.log result of this ajax call?

In Chrome, right click in the console and check 'preserve log on navigation'.

Re-order columns of table in Oracle

Since the release of Oracle 12c it is now easier to rearrange columns logically.

Oracle 12c added support for making columns invisible and that feature can be used to rearrange columns logically.

Quote from the documentation on invisible columns:

When you make an invisible column visible, the column is included in the table's column order as the last column.

Example

Create a table:

CREATE TABLE t (
    a INT,
    b INT,
    d INT,
    e INT
);

Add a column:

ALTER TABLE t ADD (c INT);

Move the column to the middle:

ALTER TABLE t MODIFY (d INVISIBLE, e INVISIBLE);
ALTER TABLE t MODIFY (d VISIBLE, e VISIBLE);

DESCRIBE t;

Name
----
A
B
C
D
E

Credits

I learned about this from an article by Tom Kyte on new features in Oracle 12c.

SVN undo delete before commit

1) do

svn revert . --recursive

2) parse output for errors like

"Failed to revert 'dir1/dir2' -- try updating instead."

3) call svn up for each of error directories:

svn up dir1/dir2

Android scale animation on view

Resize using helper methods and start-repeat-end handlers like this:

resize(
    view1,
    1.0f,
    0.0f,
    1.0f,
    0.0f,
    0.0f,
    0.0f,
    150,
    null,
    null,
    null);

  return null;
}

Helper methods:

/**
 * Resize a view.
 */
public static void resize(
  View view,
  float fromX,
  float toX,
  float fromY,
  float toY,
  float pivotX,
  float pivotY,
  int duration) {

  resize(
    view,
    fromX,
    toX,
    fromY,
    toY,
    pivotX,
    pivotY,
    duration,
    null,
    null,
    null);
}

/**
 * Resize a view with handlers.
 *
 * @param view     A view to resize.
 * @param fromX    X scale at start.
 * @param toX      X scale at end.
 * @param fromY    Y scale at start.
 * @param toY      Y scale at end.
 * @param pivotX   Rotate angle at start.
 * @param pivotY   Rotate angle at end.
 * @param duration Animation duration.
 * @param start    Actions on animation start. Otherwise NULL.
 * @param repeat   Actions on animation repeat. Otherwise NULL.
 * @param end      Actions on animation end. Otherwise NULL.
 */
public static void resize(
  View view,
  float fromX,
  float toX,
  float fromY,
  float toY,
  float pivotX,
  float pivotY,
  int duration,
  Callable start,
  Callable repeat,
  Callable end) {

  Animation animation;

  animation =
    new ScaleAnimation(
      fromX,
      toX,
      fromY,
      toY,
      Animation.RELATIVE_TO_SELF,
      pivotX,
      Animation.RELATIVE_TO_SELF,
      pivotY);

  animation.setDuration(
    duration);

  animation.setInterpolator(
    new AccelerateDecelerateInterpolator());

  animation.setFillAfter(true);

  view.startAnimation(
    animation);

  animation.setAnimationListener(new AnimationListener() {

    @Override
    public void onAnimationStart(Animation animation) {

      if (start != null) {
        try {

          start.call();

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

    }

    @Override
    public void onAnimationEnd(Animation animation) {

      if (end != null) {
        try {

          end.call();

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

    @Override
    public void onAnimationRepeat(
      Animation animation) {

      if (repeat != null) {
        try {

          repeat.call();

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

XMLHttpRequest blocked by CORS Policy

I believe sideshowbarker 's answer here has all the info you need to fix this. If your problem is just No 'Access-Control-Allow-Origin' header is present on the response you're getting, you can set up a CORS proxy to get around this. Way more info on it in the linked answer

What's the best way to detect a 'touch screen' device using JavaScript?

this ways works for me, it wait for first user interaction to make sure they're on touch devices

var touchEnabled = false;
$(document.body).one('touchstart',
    function(e){
        touchEnabled=true;
        $(document.documentElement).addClass("touch");
        // other touch related init 
        //
    }
);

How to change dot size in gnuplot

The pointsize command scales the size of points, but does not affect the size of dots.

In other words, plot ... with points ps 2 will generate points of twice the normal size, but for plot ... with dots ps 2 the "ps 2" part is ignored.

You could use circular points (pt 7), which look just like dots.