Programs & Examples On #Member variables

Getting Image from API in Angular 4/5+?

There is no need to use angular http, you can get with js native functions

_x000D_
_x000D_
// you will ned this function to fetch the image blob._x000D_
async function getImage(url, fileName) {_x000D_
     // on the first then you will return blob from response_x000D_
    return await fetch(url).then(r => r.blob())_x000D_
    .then((blob) => { // on the second, you just create a file from that blob, getting the type and name that intend to inform_x000D_
         _x000D_
        return new File([blob], fileName+'.'+   blob.type.split('/')[1]) ;_x000D_
    });_x000D_
}_x000D_
_x000D_
// example url_x000D_
var url = 'https://img.freepik.com/vetores-gratis/icone-realista-quebrado-vidro-fosco_1284-12125.jpg';_x000D_
_x000D_
// calling the function_x000D_
getImage(url, 'your-name-image').then(function(file) {_x000D_
_x000D_
    // with file reader you will transform the file in a data url file;_x000D_
    var reader = new FileReader();_x000D_
    reader.readAsDataURL(file);_x000D_
    reader.onloadend = () => {_x000D_
    _x000D_
    // just putting the data url to img element_x000D_
        document.querySelector('#image').src = reader.result ;_x000D_
    }_x000D_
})
_x000D_
<img src="" id="image"/>
_x000D_
_x000D_
_x000D_

How do I add a newline to a TextView in Android?

This solved my problem.

stringVar.replaceAll("\\\\n", "\\\n");

Which font is used in Visual Studio Code Editor and how to change fonts?

On Windows, the default settings are as follow (I never installed Monaco nor Menlo)

{
    "editor.fontFamily": "Consolas",
    "editor.fontSize": 14,
    "editor.lineHeight": 19
}

Settings fontSize to 12 and lineHeight to 16 closely approximate Visual Studio set to Consolas with 10pt size. I could not get an exact match (VS Code font is slightly bolder) but close enough.

How to embed a PDF viewer in a page?

I would really opt for FlowPaper, especially their new Elements mode that can be found here : https://flowpaper.com/demo/

It flattens the PDFs significantly at the same time as keeping text sharp which means that it will load much faster on mobile devices

Push item to associative array in PHP

i use php5.6

code:

$person = ["name"=>"mohammed", "age"=>30];

$person['addr'] = "Sudan";

print_r($person) 

output

Array( ["name"=>"mohammed", "age"=>30, "addr"=>"Sudan"] )

jQuery posting valid json in request body

An actual JSON request would look like this:

data: '{"command":"on"}',

Where you're sending an actual JSON string. For a more general solution, use JSON.stringify() to serialize an object to JSON, like this:

data: JSON.stringify({ "command": "on" }),

To support older browsers that don't have the JSON object, use json2.js which will add it in.


What's currently happening is since you have processData: false, it's basically sending this: ({"command":"on"}).toString() which is [object Object]...what you see in your request.

Reactive forms - disabled attribute

You can enable/disable a form control by using the following methods:

control.disable() or control.enable()

If that did not work for you can use a directive

import { NgControl } from '@angular/forms';

@Directive({
  selector: '[disableControl]'
})
export class DisableControlDirective {

  @Input() set disableControl( condition : boolean ) {
    const action = condition ? 'disable' : 'enable';
    this.ngControl.control[action]();
  }

  constructor( private ngControl : NgControl ) {
  }

}

Then you could use it like this

<input [formControl]="formControl" [disableControl]="disable">
<button (click)="disable = true">Disable</button>
<button (click)="disable = false">Enable</button>

This technique is described here:

https://netbasal.com/disabling-form-controls-when-working-with-reactive-forms-in-angular-549dd7b42110

Hope it helps

How do I display the current value of an Android Preference in the Preference summary?

Since in androidx Preference class has the SummaryProvider interface, it can be done without OnSharedPreferenceChangeListener. Simple implementations are provided for EditTextPreference and ListPreference. Building on EddieB's answer it can look like this. Tested on androidx.preference:preference:1.1.0-alpha03.

package com.example.util.timereminder.ui.prefs;

import android.os.Bundle;

import com.example.util.timereminder.R;

import androidx.preference.EditTextPreference;
import androidx.preference.ListPreference;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.PreferenceGroup;

/**
 * Displays different preferences.
 */
public class PrefsFragmentExample extends PreferenceFragmentCompat {

    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        addPreferencesFromResource(R.xml.preferences);

        initSummary(getPreferenceScreen());
    }

    /**
     * Walks through all preferences.
     *
     * @param p The starting preference to search from.
     */
    private void initSummary(Preference p) {
        if (p instanceof PreferenceGroup) {
            PreferenceGroup pGrp = (PreferenceGroup) p;
            for (int i = 0; i < pGrp.getPreferenceCount(); i++) {
                initSummary(pGrp.getPreference(i));
            }
        } else {
            setPreferenceSummary(p);
        }
    }

    /**
     * Sets up summary providers for the preferences.
     *
     * @param p The preference to set up summary provider.
     */
    private void setPreferenceSummary(Preference p) {
        // No need to set up preference summaries for checkbox preferences because
        // they can be set up in xml using summaryOff and summary On
        if (p instanceof ListPreference) {
            p.setSummaryProvider(ListPreference.SimpleSummaryProvider.getInstance());
        } else if (p instanceof EditTextPreference) {
            p.setSummaryProvider(EditTextPreference.SimpleSummaryProvider.getInstance());
        }
    }
}

Running a shell script through Cygwin on Windows

One more thing - if You edited the shell script in some Windows text editor, which produces the \r\n line-endings, cygwin's bash wouldn't accept those \r. Just run dos2unix testit.sh before executing the script:

C:\cygwin\bin\dos2unix testit.sh
C:\cygwin\bin\bash testit.sh

Twitter API returns error 215, Bad Authentication Data

The answer by Gruik worked for me in the below thread.

{Excerpt | Zend_Service_Twitter - Make API v1.1 ready}

with ZF 1.12.3 the workaround is to pass consumerKey and consumerSecret in oauthOptions option, not directrly in the options.

    $options = array(
        'username' => /*...*/,
        'accessToken' => /*...*/,
        'oauthOptions' => array(
            'consumerKey' => /*...*/,
            'consumerSecret' => /*...*/,
        )
    );

Node.js Web Application examples/tutorials

Update

Dav Glass from Yahoo has given a talk at YuiConf2010 in November which is now available in Video from.

He shows to great extend how one can use YUI3 to render out widgets on the server side an make them work with GET requests when JS is disabled, or just make them work normally when it's active.

He also shows examples of how to use server side DOM to apply style sheets before rendering and other cool stuff.

The demos can be found on his GitHub Account.

The part that's missing IMO to make this really awesome, is some kind of underlying storage of the widget state. So that one can visit the page without JavaScript and everything works as expected, then they turn JS on and now the widget have the same state as before but work without page reloading, then throw in some saving to the server + WebSockets to sync between multiple open browser.... and the next generation of unobtrusive and gracefully degrading ARIA's is born.

Original Answer

Well go ahead and built it yourself then.

Seriously, 90% of all WebApps out there work fine with a REST approach, of course you could do magical things like superior user tracking, tracking of downloads in real time, checking which parts of videos are being watched etc.

One problem is scalability, as soon as you have more then 1 Node process, many (but not all) of the benefits of having the data stored between requests go away, so you have to make sure that clients always hit the same process. And even then, bigger things will yet again need a database layer.

Node.js isn't the solution to everything, I'm sure people will build really great stuff in the future, but that needs some time, right now many are just porting stuff over to Node to get things going.

What (IMHO) makes Node.js so great, is the fact that it streamlines the Development process, you have to write less code, it works perfectly with JSON, you loose all that context switching.

I mainly did gaming experiments so far, but I can for sure say that there will be many cool multi player (or even MMO) things in the future, that use both HTML5 and Node.js.

Node.js is still gaining traction, it's not even near to the RoR Hype some years ago (just take a look at the Node.js tag here on SO, hardly 4-5 questions a day).

Rome (or RoR) wasn't built over night, and neither will Node.js be.

Node.js has all the potential it needs, but people are still trying things out, so I'd suggest you to join them :)

How to activate "Share" button in android app?

Share Any File as below ( Kotlin ) :
first create a folder named xml in the res folder and create a new XML Resource File named provider_paths.xml and put the below code inside it :

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <files-path
        name="files"
        path="."/>

    <external-path
        name="external_files"
        path="."/>
</paths>

now go to the manifests folder and open the AndroidManifest.xml and then put the below code inside the <application> tag :

<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
    android:name="android.support.FILE_PROVIDER_PATHS"
    android:resource="@xml/provider_paths" /> // provider_paths.xml file path in this example
</provider>

now you put the below code in the setOnLongClickListener :

share_btn.setOnClickListener {
    try {
        val file = File("pathOfFile")
        if(file.exists()) {
            val uri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", file)
            val intent = Intent(Intent.ACTION_SEND)
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            intent.setType("*/*")
            intent.putExtra(Intent.EXTRA_STREAM, uri)
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent)
        }
    } catch (e: java.lang.Exception) {
        e.printStackTrace()
        toast("Error")
    }
}

Defining and using a variable in batch file

Consider also using SETX - it will set variable on user or machine (available for all users) level though the variable will be usable with the next opening of the cmd.exe ,so often it can be used together with SET :

::setting variable for the current user
if not defined My_Var (
  set "My_Var=My_Value"
  setx My_Var My_Value
)

::setting machine defined variable
if not defined Global_Var (
  set "Global_Var=Global_Value"
  SetX Global_Var Global_Value /m
)

You can also edit directly the registry values:

User Variables: HKEY_CURRENT_USER\Environment

System Variables: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment

Which will allow to avoid some restrictions of SET and SETX like the variables containing = in their names.

Loop through files in a folder using VBA?

Try this one. (LINK)

Private Sub CommandButton3_Click()

Dim FileExtStr As String
Dim FileFormatNum As Long
Dim xWs As Worksheet
Dim xWb As Workbook
Dim FolderName As String
Application.ScreenUpdating = False
Set xWb = Application.ThisWorkbook
DateString = Format(Now, "yyyy-mm-dd hh-mm-ss")
FolderName = xWb.Path & "\" & xWb.Name & " " & DateString
MkDir FolderName
For Each xWs In xWb.Worksheets
    xWs.Copy
    If Val(Application.Version) < 12 Then
        FileExtStr = ".xls": FileFormatNum = -4143
    Else
        Select Case xWb.FileFormat
            Case 51:
                FileExtStr = ".xlsx": FileFormatNum = 51
            Case 52:
                If Application.ActiveWorkbook.HasVBProject Then
                    FileExtStr = ".xlsm": FileFormatNum = 52
                Else
                    FileExtStr = ".xlsx": FileFormatNum = 51
                End If
            Case 56:
                FileExtStr = ".xls": FileFormatNum = 56
            Case Else:
                FileExtStr = ".xlsb": FileFormatNum = 50
        End Select
    End If
    xFile = FolderName & "\" & Application.ActiveWorkbook.Sheets(1).Name & FileExtStr
    Application.ActiveWorkbook.SaveAs xFile, FileFormat:=FileFormatNum
    Application.ActiveWorkbook.Close False
Next
MsgBox "You can find the files in " & FolderName
Application.ScreenUpdating = True

End Sub

What is the difference between "word-break: break-all" versus "word-wrap: break-word" in CSS

From the respective W3 specifications —which happen to be pretty unclear due to a lack of context— one can deduce the following:

  • word-break: break-all is for breaking up foreign, non-CJK (say Western) words in CJK (Chinese, Japanese or Korean) character writings.
  • word-wrap: break-word is for word breaking in a non-mixed (let us say solely Western) language.

At least, these were W3's intentions. What actually happened was a major cock-up with browser incompatibilities as a result. Here is an excellent write-up of the various problems involved.

The following code snippet may serve as a summary of how to achieve word wrapping using CSS in a cross browser environment:

-ms-word-break: break-all;
 word-break: break-all;

 /* Non standard for webkit */
 word-break: break-word;

-webkit-hyphens: auto;
   -moz-hyphens: auto;
    -ms-hyphens: auto;
        hyphens: auto;

Git: "please tell me who you are" error

I spent lots of hours on it when I call PHP script to init and commit to git. And I found the work flow should be as:

  1. git init
  2. git config user.name "someone"
  3. git config user.email "[email protected]"
  4. git add *
  5. git commit -m "some init msg"

If you swap [23] and 1, the config will not work at all.

I wish this will do some help.

How to make type="number" to positive numbers only

With text type of input you can use this for a better validation,

return (event.keyCode? (event.keyCode == 69 ? false : event.keyCode >= 48 && event.keyCode <= 57) : (event.charCode >= 48 && event.charCode <= 57))? true : event.preventDefault();

Trigger insert old values- values that was updated

    createTRIGGER [dbo].[Table] ON [dbo].[table] 
FOR UPDATE
AS
    declare @empid int;
    declare @empname varchar(100);
    declare @empsal decimal(10,2);
    declare @audit_action varchar(100);
    declare @old_v varchar(100)

    select @empid=i.Col_Name1 from inserted i;  
    select @empname=i.Col_Name2  from inserted i;   
    select @empsal=i.Col_Name2 from inserted i;
    select @old_v=d.Col_Name from deleted d

    if update(Col_Name1)
        set @audit_action='Updated Record -- After Update Trigger.';
    if update(Col_Name2)
        set @audit_action='Updated Record -- After Update Trigger.';

    insert into Employee_Test_Audit1(Col_name1,Col_name2,Col_name3,Col_name4,Col_name5,Col_name6(Old_values)) 
    values(@empid,@empname,@empsal,@audit_action,getdate(),@old_v);

    PRINT '----AFTER UPDATE Trigger fired-----.'

Java - Convert integer to string

Always use either String.valueOf(number) or Integer.toString(number).

Using "" + number is an overhead and does the following:

StringBuilder sb = new StringBuilder();
sb.append("");
sb.append(number);
return sb.toString();

How can I select random files from a directory in bash?

This is an even later response to @gniourf_gniourf's late answer, which I just upvoted because it's by far the best answer, twice over. (Once for avoiding eval and once for safe filename handling.)

But it took me a few minutes to untangle the "not very well documented" feature(s) this answer uses. If your Bash skills are solid enough that you saw immediately how it works, then skip this comment. But I didn't, and having untangled it I think it's worth explaining.

Feature #1 is the shell's own file globbing. a=(*) creates an array, $a, whose members are the files in the current directory. Bash understands all the weirdnesses of filenames, so that list is guaranteed correct, guaranteed escaped, etc. No need to worry about properly parsing textual file names returned by ls.

Feature #2 is Bash parameter expansions for arrays, one nested within another. This starts with ${#ARRAY[@]}, which expands to the length of $ARRAY.

That expansion is then used to subscript the array. The standard way to find a random number between 1 and N is to take the value of random number modulo N. We want a random number between 0 and the length of our array. Here's the approach, broken into two lines for clarity's sake:

LENGTH=${#ARRAY[@]}
RANDOM=${a[RANDOM%$LENGTH]}

But this solution does it in a single line, removing the unnecessary variable assignment.

Feature #3 is Bash brace expansion, although I have to confess I don't entirely understand it. Brace expansion is used, for instance, to generate a list of 25 files named filename1.txt, filename2.txt, etc: echo "filename"{1..25}".txt".

The expression inside the subshell above, "${a[RANDOM%${#a[@]}]"{1..42}"}", uses that trick to produce 42 separate expansions. The brace expansion places a single digit in between the ] and the }, which at first I thought was subscripting the array, but if so it would be preceded by a colon. (It would also have returned 42 consecutive items from a random spot in the array, which is not at all the same thing as returning 42 random items from the array.) I think it's just making the shell run the expansion 42 times, thereby returning 42 random items from the array. (But if someone can explain it more fully, I'd love to hear it.)

The reason N has to be hardcoded (to 42) is that brace expansion happens before variable expansion.

Finally, here's Feature #4, if you want to do this recursively for a directory hierarchy:

shopt -s globstar
a=( ** )

This turns on a shell option that causes ** to match recursively. Now your $a array contains every file in the entire hierarchy.

Creating hard and soft links using PowerShell

Try junction.exe

The Junction command line utility from SysInternals makes creating and deleting junctions easy.

Further reading

  • MS Terminology: soft != symbolic
    Microsoft uses "soft link" as another name for "junction".
    However: a "symbolic link" is something else entirely.
    See MSDN: Hard Links and Junctions in Windows.
    (This is in direct contradiction to the general usage of those terms where "soft link" and "symbolic link" ("symlink") DO mean the same thing.)

How to remove the focus from a TextBox in WinForms?

using System.Windows.Input

Keyboard.ClearFocus();

How do I resize a Google Map with JavaScript after it has loaded?

for Google Maps v3, you need to trigger the resize event differently:

google.maps.event.trigger(map, "resize");

See the documentation for the resize event (you'll need to search for the word 'resize'): http://code.google.com/apis/maps/documentation/v3/reference.html#event


Update

This answer has been here a long time, so a little demo might be worthwhile & although it uses jQuery, there's no real need to do so.

_x000D_
_x000D_
$(function() {
  var mapOptions = {
    zoom: 8,
    center: new google.maps.LatLng(-34.397, 150.644)
  };
  var map = new google.maps.Map($("#map-canvas")[0], mapOptions);

  // listen for the window resize event & trigger Google Maps to update too
  $(window).resize(function() {
    // (the 'map' here is the result of the created 'var map = ...' above)
    google.maps.event.trigger(map, "resize");
  });
});
_x000D_
html,
body {
  height: 100%;
}
#map-canvas {
  min-width: 200px;
  width: 50%;
  min-height: 200px;
  height: 80%;
  border: 1px solid blue;
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&dummy=.js"></script>
Google Maps resize demo
<div id="map-canvas"></div>
_x000D_
_x000D_
_x000D_

UPDATE 2018-05-22

With a new renderer release in version 3.32 of Maps JavaScript API the resize event is no longer a part of Map class.

The documentation states

When the map is resized, the map center is fixed

  • The full-screen control now preserves center.

  • There is no longer any need to trigger the resize event manually.

source: https://developers.google.com/maps/documentation/javascript/new-renderer

google.maps.event.trigger(map, "resize"); doesn't have any effect starting from version 3.32

Bootstrap trying to load map file. How to disable it? Do I need to do it?

Delete the line "/*# sourceMappingURL=bootstrap.min.css.map */ " in following files.

  • css/bootstrap.min.css
  • css/bootstrap.css

To fetch the file path in Linux use the command find / -name "\*bootstrap\*"

pip broke. how to fix DistributionNotFound error?

I was facing the similar problem in OSx. My stacktrace was saying

raise DistributionNotFound(req)
pkg_resources.DistributionNotFound: setuptools>=11.3

Then I did the following

sudo pip install --upgrade setuptools

This solved the problem for me. Hope someone will find this useful.

How to set tint for an image view programmatically in android?

Not exact answer but a simpler alternative:

  • Place another view on top of the image
  • Change the alpha value of the view however you want (programmatically) to get the desired effect.

Here is a snippet for that:

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="@dimen/height120"
        android:contentDescription="@string/my_description"
        android:scaleType="fitXY"
        android:src="@drawable/my_awesome_image"/>

    <View
        android:layout_width="match_parent"
        android:layout_height="@dimen/height120"
        android:alpha="0.5"
        android:background="@color/my_blue_color"/>
</FrameLayout>

Remove innerHTML from div


var $div = $('#desiredDiv');
$div.contents().remove();
$div.html('<p>This is new HTML.</p>');

That should work just fine.

How do you post to an iframe?

If you want to change inputs in an iframe then submit the form from that iframe, do this

...
var el = document.getElementById('targetFrame');

var doc, frame_win = getIframeWindow(el); // getIframeWindow is defined below

if (frame_win) {
  doc = (window.contentDocument || window.document);
}

if (doc) {
  doc.forms[0].someInputName.value = someValue;
  ...
  doc.forms[0].submit();
}
...

Normally, you can only do this if the page in the iframe is from the same origin, but you can start Chrome in a debug mode to disregard the same origin policy and test this on any page.

function getIframeWindow(iframe_object) {
  var doc;

  if (iframe_object.contentWindow) {
    return iframe_object.contentWindow;
  }

  if (iframe_object.window) {
    return iframe_object.window;
  } 

  if (!doc && iframe_object.contentDocument) {
    doc = iframe_object.contentDocument;
  } 

  if (!doc && iframe_object.document) {
    doc = iframe_object.document;
  }

  if (doc && doc.defaultView) {
   return doc.defaultView;
  }

  if (doc && doc.parentWindow) {
    return doc.parentWindow;
  }

  return undefined;
}

How to create and show common dialog (Error, Warning, Confirmation) in JavaFX 2.0?

Recently released JDK 1.8.0_40 added support for JavaFX dialogs, alerts, etc. For example, to show a confirmation dialog, one would use the Alert class:

Alert alert = new Alert(AlertType.CONFIRMATION, "Delete " + selection + " ?", ButtonType.YES, ButtonType.NO, ButtonType.CANCEL);
alert.showAndWait();

if (alert.getResult() == ButtonType.YES) {
    //do stuff
}

Here's a list of added classes in this release:

Visual Studio "Could not copy" .... during build

I am working on a micro service projects solution where I need to run two projects at the same time, the conflict occurs when the lunchsettings.json applicationurl: {portNo} part for the two running projects are the same port

lunchsettings.json for first project

...
"Project#1": {
  ...
  "applicationUrl": "http://localhost:5001",
  ...
}

lunchsettings.json for second project

...
"Project#2": {
  ...
  "applicationUrl": "http://localhost:5001",
  ...
}

To fix it

lunchsettings.json for first project

...
"Project#1": {
  ...
  "applicationUrl": "http://localhost:5001",
  ...
}

lunchsettings.json for secondproject

...
"Project#2": {
  ...
  "applicationUrl": "http://localhost:5002",
  ...
}

How to calculate the number of occurrence of a given character in each row of a column of strings?

The stringi package provides the functions stri_count and stri_count_fixed which are very fast.

stringi::stri_count(q.data$string, fixed = "a")
# [1] 2 1 0

benchmark

Compared to the fastest approach from @42-'s answer and to the equivalent function from the stringr package for a vector with 30.000 elements.

library(microbenchmark)

benchmark <- microbenchmark(
  stringi = stringi::stri_count(test.data$string, fixed = "a"),
  baseR = nchar(test.data$string) - nchar(gsub("a", "", test.data$string, fixed = TRUE)),
  stringr = str_count(test.data$string, "a")
)

autoplot(benchmark)

data

q.data <- data.frame(number=1:3, string=c("greatgreat", "magic", "not"), stringsAsFactors = FALSE)
test.data <- q.data[rep(1:NROW(q.data), 10000),]

enter image description here

How to browse localhost on Android device?

Combining a few of the answers above plus one other additional item solved the problem for me.

  1. As mentioned above, turn your firewall off [add a specific rule allowing the incoming connections to the port once you've successfully connected]
  2. Find you IP address via ipconfig as mentioned above
  3. Verify that your webserver is binding to the ip address found above and not just 127.0.0.1. Test this locally by browsing to the ip address and port. E.g. 192.168.1.113:8888. If it's not, find a solution. E.g. https://groups.google.com/forum/?fromgroups=#!topic/google-appengine-java/z4rtqkKO2hg
  4. Now test it out on your Android device. Note that I also turned off my data connection and exclusively used a wifi connection on my Android.

Detect a finger swipe through JavaScript on the iPhone and Android

I had to write a simple script for a carousel to detect swipe left or right.

I utilised Pointer Events instead of Touch Events.

I hope this is useful to individuals and I welcome any insights to improve my code; I feel rather sheepish to join this thread with significantly superior JS developers.

function getSwipeX({elementId}) {

  this.e               = document.getElementsByClassName(elementId)[0];
  this.initialPosition = 0;
  this.lastPosition    = 0;
  this.threshold       = 200;
  this.diffInPosition  = null;
  this.diffVsThreshold = null;
  this.gestureState    = 0;

  this.getTouchStart = (event) => {
    event.preventDefault();
    if (window.PointerEvent) {
      this.e.setPointerCapture(event.pointerId);
    }
    return this.initalTouchPos = this.getGesturePoint(event);
  }

  this.getTouchMove  = (event) => {
    event.preventDefault();
    return this.lastPosition = this.getGesturePoint(event);
  }

  this.getTouchEnd   = (event) => {
    event.preventDefault();
    if (window.PointerEvent) {
      this.e.releasePointerCapture(event.pointerId);
    }
    this.doSomething();
    this.initialPosition = 0;
  }

  this.getGesturePoint = (event) => {
    this.point = event.pageX
    return this.point;
  }

  this.whatGestureDirection = (event) => {
    this.diffInPosition  = this.initalTouchPos - this.lastPosition;
    this.diffVsThreshold = Math.abs(this.diffInPosition) > this.threshold;
    (Math.sign(this.diffInPosition) > 0) ? this.gestureState = 'L' : (Math.sign(this.diffInPosition) < 0) ? this.gestureState = 'R' : this.gestureState = 'N';
    
    return [this.diffInPosition, this.diffVsThreshold, this.gestureState];
  }

  this.doSomething = (event) => {
    let [gestureDelta,gestureThreshold,gestureDirection] = this.whatGestureDirection();

    // USE THIS TO DEBUG
    console.log(gestureDelta,gestureThreshold,gestureDirection);

    if (gestureThreshold) {
      (gestureDirection == 'L') ? // LEFT ACTION : // RIGHT ACTION
    }
  }

  if (window.PointerEvent) {
    this.e.addEventListener('pointerdown', this.getTouchStart, true);
    this.e.addEventListener('pointermove', this.getTouchMove, true);
    this.e.addEventListener('pointerup', this.getTouchEnd, true);
    this.e.addEventListener('pointercancel', this.getTouchEnd, true);
  }
}

You can call the function using new.

window.addEventListener('load', () => {
  let test = new getSwipeX({
    elementId: 'your_div_here'
  });
})

How do I adb pull ALL files of a folder present in SD Card

On Android 6 with ADB version 1.0.32, you have to put / behind the folder you want to copy. E.g adb pull "/sdcard/".

Redirecting to authentication dialog - "An error occurred. Please try again later"

I know u may got the answer but this is for those who are still going down the thread for getting the solution.

U can try all the above solutions but just remember that delete the Previous app from the device or simulator before checking another solution.

I tried all solutions but getting no response as i was not deleting the previous app, only cleaning the build does not satisfy the condition.Hope it helps someone. :)

Compare two Timestamp in java

if(mytime.after(fromtime) && mytime.before(totime))
  //mytime is in between

SQL server stored procedure return a table

create procedure PSaleCForms
as
begin
declare 
@b varchar(9),
@c nvarchar(500),
@q nvarchar(max)
declare @T table(FY nvarchar(9),Qtr int,title nvarchar    (max),invoicenumber     nvarchar(max),invoicedate datetime,sp decimal    18,2),grandtotal decimal(18,2))
declare @data cursor
set @data= Cursor
forward_only static
for 
select x.DBTitle,y.CurrentFinancialYear from [Accounts     Manager].dbo.DBManager x inner join [Accounts Manager].dbo.Accounts y on        y.DBID=x.DBID where x.cfy=1
open @data
fetch next from @data
into @c,@b
while @@FETCH_STATUS=0
begin
set @q=N'Select '''+@b+''' [fy], case cast(month(i.invoicedate)/3.1 as int)     when 0 then 4 else cast(month(i.invoicedate)/3.1 as int) end [Qtr],     l.title,i.invoicenumber,i.invoicedate,i.sp,i.grandtotal from     ['+@c+'].dbo.invoicemain i inner join  ['+@c+'].dbo.ledgermain l on     l.ledgerid=i.ledgerid where (sp=0 or stocktype=''x'') and invoicetype=''DS'''

insert into @T exec [master].dbo.sp_executesql @q fetch next from @data into @c,@b end close @data deallocate @data select * from @T return end

Postgresql: password authentication failed for user "postgres"

Try to not use the -W parameter and leave the password in blank. Sometimes the user is created with no-password.

If that doesn't work reset the password. There are several ways to do it, but this works on many systems:

$ su root
$ su postgres
$ psql -h localhost
> ALTER USER postgres with password 'YourNewPassword';

Override body style for content in an iframe

Override another domain iframe CSS

By using part of SimpleSam5's answer, I achieved this with a few of Tawk's chat iframes (their customization interface is fine but I needed further customizations).

In this particular iframe that shows up on mobile devices, I needed to hide the default icon and place one of my background images. I did the following:

Tawk_API.onLoad = function() {
// without a specific API, you may try a similar load function
// perhaps with a setTimeout to ensure the iframe's content is fully loaded
  $('#mtawkchat-minified-iframe-element').
    contents().find("head").append(
     $("<style type='text/css'>"+
       "#tawkchat-status-text-container {"+
         "background: url(https://example.net/img/my_mobile_bg.png) no-repeat center center blue;"+
         "background-size: 100%;"+
       "} "+
       "#tawkchat-status-icon {display:none} </style>")
   );
};

I do not own any Tawk's domain and this worked for me, thus you may do this even if it's not from the same parent domain (despite Jeremy Becker's comment on Sam's answer).

Parse JSON String into a Particular Object Prototype in JavaScript

An alternate approach could be using Object.create. As first argument, you pass the prototype, and for the second one you pass a map of property names to descriptors:

_x000D_
_x000D_
function SomeConstructor() {_x000D_
  _x000D_
};_x000D_
_x000D_
SomeConstructor.prototype = {_x000D_
  doStuff: function() {_x000D_
      console.log("Some stuff"); _x000D_
  }_x000D_
};_x000D_
_x000D_
var jsonText = '{ "text": "hello wrold" }';_x000D_
var deserialized = JSON.parse(jsonText);_x000D_
_x000D_
// This will build a property to descriptor map_x000D_
// required for #2 argument of Object.create_x000D_
var descriptors = Object.keys(deserialized)_x000D_
  .reduce(function(result, property) {_x000D_
    result[property] = Object.getOwnPropertyDescriptor(deserialized, property);_x000D_
  }, {});_x000D_
_x000D_
var obj = Object.create(SomeConstructor.prototype, descriptors);
_x000D_
_x000D_
_x000D_

Centering image and text in R Markdown for a PDF report

If you are centering the output of an R code chunk, e.g., a plot, then you can use the fig.align option in knitr.

```{r fig.align="center"}
plot(mtcars)
```

Adding a custom header to HTTP request using angular.js

For me the following explanatory snippet worked. Perhaps you shouldn't use ' for header name?

{
   headers: { 
      Authorization: "Basic " + getAuthDigest(), 
      Accept: "text/plain" 
   }
}

I'm using $http.ajax(), though I wouldn't expect that to be a game changer.

How to return a file using Web API?

Better to return HttpResponseMessage with StreamContent inside of it.

Here is example:

public HttpResponseMessage GetFile(string id)
{
    if (String.IsNullOrEmpty(id))
        return Request.CreateResponse(HttpStatusCode.BadRequest);

    string fileName;
    string localFilePath;
    int fileSize;

    localFilePath = getFileFromID(id, out fileName, out fileSize);

    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
    response.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
    response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
    response.Content.Headers.ContentDisposition.FileName = fileName;
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");

    return response;
}

UPD from comment by patridge: Should anyone else get here looking to send out a response from a byte array instead of an actual file, you're going to want to use new ByteArrayContent(someData) instead of StreamContent (see here).

Why is it not advisable to have the database and web server on the same machine?

Database licences are not cheep and are often charged per CPU, therefore by separating out your web-servers you can reduce the cost of your database licences.

E.g if you have 1 server doing both web and database that contains 8 CPUs you will have to pay for an 8 cpu licence. However if you have two servers each with 4 CPUs and runs the database on one server you will only have to pay for a 4 cpu licences

How to create JSON Object using String?

In contrast to what the accepted answer proposes, the documentation says that for JSONArray() you must use put(value) no add(value).

https://developer.android.com/reference/org/json/JSONArray.html#put(java.lang.Object)

(Android API 19-27. Kotlin 1.2.50)

MySQL - SELECT * INTO OUTFILE LOCAL ?

Re: SELECT * INTO OUTFILE

Check if MySQL has permissions to write a file to the OUTFILE directory on the server.

Assembly code vs Machine code vs Object code?

Assembly is short descriptive terms humans can understand that can be directly translated into the machine code that a CPU actually uses.

While somewhat understandable by humans, Assembler is still low level. It takes a lot of code to do anything useful.

So instead we use higher level languages such as C, BASIC, FORTAN (OK I know I've dated myself). When compiled these produce object code. Early languages had machine language as their object code.

Many languages today such a JAVA and C# usually compile into a bytecode that is not machine code, but one that easily be interpreted at run time to produce machine code.

MySQL TEXT vs BLOB vs CLOB

TEXT is a data-type for text based input. On the other hand, you have BLOB and CLOB which are more suitable for data storage (images, etc) due to their larger capacity limits (4GB for example).

As for the difference between BLOB and CLOB, I believe CLOB has character encoding associated with it, which implies it can be suited well for very large amounts of text.

BLOB and CLOB data can take a long time to retrieve, relative to how quick data from a TEXT field can be retrieved. So, use only what you need.

There was no endpoint listening at (url) that could accept the message

An another possible case is make sure that you have installed WCF Activation feature. Go to Server Manager > Features > Add Features

enter image description here

Create a user with all privileges in Oracle

My issue was, i am unable to create a view with my "scott" user in oracle 11g edition. So here is my solution for this

Error in my case

SQL>create view v1 as select * from books where id=10;

insufficient privileges.

Solution

1)open your cmd and change your directory to where you install your oracle database. in my case i was downloaded in E drive so my location is E:\app\B_Amar\product\11.2.0\dbhome_1\BIN> after reaching in the position you have to type sqlplus sys as sysdba

E:\app\B_Amar\product\11.2.0\dbhome_1\BIN>sqlplus sys as sysdba

2) Enter password: here you have to type that password that you give at the time of installation of oracle software.

3) Here in this step if you want create a new user then you can create otherwise give all the privileges to existing user.

for creating new user

SQL> create user abc identified by xyz;

here abc is user and xyz is password.

giving all the privileges to abc user

SQL> grant all privileges to abc;

 grant succeeded. 

if you are seen this message then all the privileges are giving to the abc user.

4) Now exit from cmd, go to your SQL PLUS and connect to the user i.e enter your username & password.Now you can happily create view.

In My case

in cmd E:\app\B_Amar\product\11.2.0\dbhome_1\BIN>sqlplus sys as sysdba

SQL> grant all privileges to SCOTT;

grant succeeded.

Now I can create views.

What is the difference between Amazon SNS and Amazon SQS?

You can see SNS as a traditional topic which you can have multiple Subscribers. You can have heterogeneous subscribers for one given SNS topic, including Lambda and SQS, for example. You can also send SMS messages or even e-mails out of the box using SNS. One thing to consider in SNS is only one message (notification) is received at once, so you cannot take advantage from batching.

SQS, on the other hand, is nothing but a queue, where you store messages and subscribe one consumer (yes, you can have N consumers to one SQS queue, but it would get messy very quickly and way harder to manage considering all consumers would need to read the message at least once, so one is better off with SNS combined with SQS for this use case, where SNS would push notifications to N SQS queues and every queue would have one subscriber, only) to process these messages. As of Jun 28, 2018, AWS Supports Lambda Triggers for SQS, meaning you don't have to poll for messages any more.

Furthermore, you can configure a DLQ on your source SQS queue to send messages to in case of failure. In case of success, messages are automatically deleted (this is another great improvement), so you don't have to worry about the already processed messages being read again in case you forgot to delete them manually. I suggest taking a look at Lambda Retry Behaviour to better understand how it works.

One great benefit of using SQS is that it enables batch processing. Each batch can contain up to 10 messages, so if 100 messages arrive at once in your SQS queue, then 10 Lambda functions will spin up (considering the default auto-scaling behaviour for Lambda) and they'll process these 100 messages (keep in mind this is the happy path as in practice, a few more Lambda functions could spin up reading less than the 10 messages in the batch, but you get the idea). If you posted these same 100 messages to SNS, however, 100 Lambda functions would spin up, unnecessarily increasing costs and using up your Lambda concurrency.

However, if you are still running traditional servers (like EC2 instances), you will still need to poll for messages and manage them manually.

You also have FIFO SQS queues, which guarantee the delivery order of the messages. SQS FIFO is also supported as an event source for Lambda as of November 2019

Even though there's some overlap in their use cases, both SQS and SNS have their own spotlight.

Use SNS if:

  • multiple subscribers is a requirement
  • sending SMS/E-mail out of the box is handy

Use SQS if:

  • only one subscriber is needed
  • batching is important

How to test the type of a thrown exception in Jest

Further to Peter Danis' post, I just wanted to emphasize the part of his solution involving "[passing] a function into expect(function).toThrow(blank or type of error)".

In Jest, when you test for a case where an error should be thrown, within your expect() wrapping of the function under testing, you need to provide one additional arrow function wrapping layer in order for it to work. I.e.

Wrong (but most people's logical approach):

expect(functionUnderTesting();).toThrow(ErrorTypeOrErrorMessage);

Right:

expect(() => { functionUnderTesting(); }).toThrow(ErrorTypeOrErrorMessage);

It's very strange, but it should make the testing run successfully.

Why use prefixes on member variables in C++ classes

According to JOINT STRIKE FIGHTER AIR VEHICLE C++ CODING STANDARDS (december 2005):

AV Rule 67

Public and protected data should only be used in structs—not classes. Rationale: A class is able to maintain its invariant by controlling access to its data. However, a class cannot control access to its members if those members non-private. Hence all data in a class should be private.

Thus, the "m" prefix becomes unuseful as all data should be private.

But it is a good habit to use the p prefix before a pointer as it is a dangerous variable.

How to determine the content size of a UIWebView?

In Xcode 8 and iOS 10 to determine the height of a web view. you can get height using

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    CGFloat height = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight"] floatValue];
    NSLog(@"Webview height is:: %f", height);
}

OR for Swift

 func webViewDidFinishLoad(aWebView:UIWebView){
        let height: Float = (aWebView.stringByEvaluatingJavaScriptFromString("document.body.scrollHeight")?.toFloat())!
        print("Webview height is::\(height)")
    }

htaccess "order" Deny, Allow, Deny

Just use order allow,deny instead and remove the deny from all line.

Importing CommonCrypto in a Swift framework

In case you have the below issue :

ld: library not found for -lapple_crypto clang: error: linker command failed with exit code 1 (use -v to see invocation)

In Xcode 10, Swift 4.0. CommonCrypto is a part of the framework.

Add

 import CommonCrypto

Remove

  • CommonCrpto lib file from link binary with libraries from Build phases
  • import CommonCrypto from Bridging header

This worked for me!

R data formats: RData, Rda, Rds etc

Rda is just a short name for RData. You can just save(), load(), attach(), etc. just like you do with RData.

Rds stores a single R object. Yet, beyond that simple explanation, there are several differences from a "standard" storage. Probably this R-manual Link to readRDS() function clarifies such distinctions sufficiently.

So, answering your questions:

  • The difference is not about the compression, but serialization (See this page)
  • Like shown in the manual page, you may wanna use it to restore a certain object with a different name, for instance.
  • You may readRDS() and save(), or load() and saveRDS() selectively.

How to install JDK 11 under Ubuntu?

For anyone running a JDK on Ubuntu and want to upgrade to JDK11, I'd recommend installing via sdkman. SDKMAN is a tool for switching JVMs, removing and upgrading.

SDKMAN is a tool for managing parallel versions of multiple Software Development Kits on most Unix based systems. It provides a convenient Command Line Interface (CLI) and API for installing, switching, removing and listing Candidates.

Install SDKMAN

$ curl -s "https://get.sdkman.io" | bash
$ source "$HOME/.sdkman/bin/sdkman-init.sh"
$ sdk version

Install Java (11.0.3-zulu)

$ sdk install java

HTML5 live streaming

Firstly you need to setup a media streaming server. You can use Wowza, red5 or nginx-rtmp-module. Read their documentation and setup on OS you want. All the engine are support HLS (Http Live Stream protocol that was developed by Apple). You should read documentation for config. Example with nginx-rtmp-module:

rtmp {
    server {
        listen 1935; # Listen on standard RTMP port
        chunk_size 4000;

        application show {
            live on;
            # Turn on HLS
            hls on;
            hls_path /mnt/hls/;
            hls_fragment 3;
            hls_playlist_length 60;
            # disable consuming the stream from nginx as rtmp
            deny play all;
        }
    }
} 

server {
    listen 8080;

    location /hls {
        # Disable cache
        add_header Cache-Control no-cache;

        # CORS setup
        add_header 'Access-Control-Allow-Origin' '*' always;
        add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
        add_header 'Access-Control-Allow-Headers' 'Range';

        # allow CORS preflight requests
        if ($request_method = 'OPTIONS') {
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Headers' 'Range';
            add_header 'Access-Control-Max-Age' 1728000;
            add_header 'Content-Type' 'text/plain charset=UTF-8';
            add_header 'Content-Length' 0;
            return 204;
        }

        types {
            application/vnd.apple.mpegurl m3u8;
            video/mp2t ts;
        }

        root /mnt/;
    }
}

After server was setup and configuration successful. you must use some rtmp encoder software (OBS, wirecast ...) for start streaming like youtube or twitchtv.

In client side (browser in your case) you can use Videojs or JWplayer to play video for end user. You can do something like below for Videojs:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Live Streaming</title>
    <link href="//vjs.zencdn.net/5.8/video-js.min.css" rel="stylesheet">
    <script src="//vjs.zencdn.net/5.8/video.min.js"></script>
</head>
<body>
<video id="player" class="video-js vjs-default-skin" height="360" width="640" controls preload="none">
    <source src="http://localhost:8080/hls/stream.m3u8" type="application/x-mpegURL" />
</video>
<script>
    var player = videojs('#player');
</script>
</body>
</html>

You don't need to add others plugin like flash (because we use HLS not rtmp). This player can work well cross browser with out flash.

Sending command line arguments to npm script

For PowerShell users on Windows

The accepted answer did not work for me with npm 6.14. Neither adding no -- nor including it once does work. However, putting -- twice or putting "--" once before the arguments does the trick. Example:

npm run <my_script> -- -- <my arguments like --this>

Suspected reason

Like in bash, -- instructs PowerShell to treat all following arguments as literal strings, and not options (E.g see this answer). The issues seems to be that the command is interpreted one time more than expected, loosing the '--'. For instance, by doing

npm run <my_script> -- --option value

npm will run

<my_script> value

However, doing

npm run <my_script> "--" --option value

results in

<my_script> "--option" "value"

which works fine.

Where is the IIS Express configuration / metabase file found?

Since the introduction of Visual Studio 2015, this location has changed and is added into your solution root under the following location:

C:\<Path\To\Solution>\.vs\config\applicationhost.config

I hope this saves you some time!

Python's equivalent of && (logical-and) in an if-statement

Probably this is not best code for this task, but is working -

def front_back(a, b):

 if len(a) % 2 == 0 and len(b) % 2 == 0:
    print a[:(len(a)/2)] + b[:(len(b)/2)] + a[(len(a)/2):] + b[(len(b)/2):]

 elif len(a) % 2 == 1 and len(b) % 2 == 0:
    print a[:(len(a)/2)+1] + b[:(len(b)/2)] + a[(len(a)/2)+1:] + b[(len(b)/2):] 

 elif len(a) % 2 == 0 and len(b) % 2 == 1:
     print a[:(len(a)/2)] + b[:(len(b)/2)+1] + a[(len(a)/2):] + b[(len(b)/2)+1:] 

 else :
     print a[:(len(a)/2)+1] + b[:(len(b)/2)+1] + a[(len(a)/2)+1:] + b[(len(b)/2)+1:]

Array initialization in Perl

What do you mean by "initialize an array to zero"? Arrays don't contain "zero" -- they can contain "zero elements", which is the same as "an empty list". Or, you could have an array with one element, where that element is a zero: my @array = (0);

my @array = (); should work just fine -- it allocates a new array called @array, and then assigns it the empty list, (). Note that this is identical to simply saying my @array;, since the initial value of a new array is the empty list anyway.

Are you sure you are getting an error from this line, and not somewhere else in your code? Ensure you have use strict; use warnings; in your module or script, and check the line number of the error you get. (Posting some contextual code here might help, too.)

How to check SQL Server version

select charindex(  'Express',@@version)

if this value is 0 is not a express edition

Using jQuery's ajax method to retrieve images as a blob

You can't do this with jQuery ajax, but with native XMLHttpRequest.

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
    if (this.readyState == 4 && this.status == 200){
        //this.response is what you're looking for
        handler(this.response);
        console.log(this.response, typeof this.response);
        var img = document.getElementById('img');
        var url = window.URL || window.webkitURL;
        img.src = url.createObjectURL(this.response);
    }
}
xhr.open('GET', 'http://jsfiddle.net/img/logo.png');
xhr.responseType = 'blob';
xhr.send();      

EDIT

So revisiting this topic, it seems it is indeed possible to do this with jQuery 3

_x000D_
_x000D_
jQuery.ajax({_x000D_
        url:'https://images.unsplash.com/photo-1465101108990-e5eac17cf76d?ixlib=rb-0.3.5&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjE0NTg5fQ%3D%3D&s=471ae675a6140db97fea32b55781479e',_x000D_
        cache:false,_x000D_
        xhr:function(){// Seems like the only way to get access to the xhr object_x000D_
            var xhr = new XMLHttpRequest();_x000D_
            xhr.responseType= 'blob'_x000D_
            return xhr;_x000D_
        },_x000D_
        success: function(data){_x000D_
            var img = document.getElementById('img');_x000D_
            var url = window.URL || window.webkitURL;_x000D_
            img.src = url.createObjectURL(data);_x000D_
        },_x000D_
        error:function(){_x000D_
            _x000D_
        }_x000D_
    });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>_x000D_
<img id="img" width=100%>
_x000D_
_x000D_
_x000D_

or

use xhrFields to set the responseType

_x000D_
_x000D_
    jQuery.ajax({_x000D_
            url:'https://images.unsplash.com/photo-1465101108990-e5eac17cf76d?ixlib=rb-0.3.5&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjE0NTg5fQ%3D%3D&s=471ae675a6140db97fea32b55781479e',_x000D_
            cache:false,_x000D_
            xhrFields:{_x000D_
                responseType: 'blob'_x000D_
            },_x000D_
            success: function(data){_x000D_
                var img = document.getElementById('img');_x000D_
                var url = window.URL || window.webkitURL;_x000D_
                img.src = url.createObjectURL(data);_x000D_
            },_x000D_
            error:function(){_x000D_
                _x000D_
            }_x000D_
        });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>_x000D_
    <img id="img" width=100%>
_x000D_
_x000D_
_x000D_

google-services.json for different productFlavors

Inspired by @ahmed_khan_89 answer above. We can directly keep like this in gradle file.

android{

// set build flavor here to get the right Google-services configuration(Google Analytics).
    def currentFlavor = "free" //This should match with Build Variant selection. free/paidFull/paidBasic

    println "--> $currentFlavor copy!"
    copy {
        from "src/$currentFlavor/"
        include 'google-services.json'
        into '.'
    }
//other stuff
}

Is there a typical state machine implementation pattern?

For simple cases, you can you your switch style method. What I have found that works well in the past is to deal with transitions too:

static int current_state;    // should always hold current state -- and probably be an enum or something

void state_leave(int new_state) {
    // do processing on what it means to enter the new state
    // which might be dependent on the current state
}

void state_enter(int new_state) {
    // do processing on what is means to leave the current atate
    // might be dependent on the new state

    current_state = new_state;
}

void state_process() {
    // switch statement to handle current state
}

I don't know anything about the boost library, but this type of approach is dead simple, doesn't require any external dependencies, and is easy to implement.

How to scroll table's "tbody" independent of "thead"?

try this.

table 
{
    background-color: #aaa;
}

tbody 
{
    background-color: #ddd;
    height: 100px;
    overflow-y: scroll;
    position: absolute;
}

td 
{
    padding: 3px 10px;
    color: green;
    width: 100px;
}

How to use mod operator in bash?

You must put your mathematical expressions inside $(( )).

One-liner:

for i in {1..600}; do wget http://example.com/search/link$(($i % 5)); done;

Multiple lines:

for i in {1..600}; do
    wget http://example.com/search/link$(($i % 5))
done

Possible to extend types in Typescript?

May be below approach will be helpful for someone TS with reactjs

interface Event {
   name: string;
   dateCreated: string;
   type: string;
}

interface UserEvent<T> extends Event<T> {
    UserId: string;
}

How to keep form values after post

If you are looking to just repopulate the fields with the values that were posted in them, then just echo the post value back into the field, like so:

<input type="text" name="myField1" value="<?php echo isset($_POST['myField1']) ? $_POST['myField1'] : '' ?>" />

Why do you use typedef when declaring an enum in C++?

It's a C heritage, in C, if you do :

enum TokenType
{
    blah1   = 0x00000000,
    blah2   = 0X01000000,
    blah3   = 0X02000000
};

you'll have to use it doing something like :

enum TokenType foo;

But if you do this :

typedef enum e_TokenType
{
    blah1   = 0x00000000,
    blah2   = 0X01000000,
    blah3   = 0X02000000
} TokenType;

You'll be able to declare :

TokenType foo;

But in C++, you can use only the former definition and use it as if it were in a C typedef.

Java to Jackson JSON serialization: Money fields

You can use a custom serializer at your money field. Here's an example with a MoneyBean. The field amount gets annotated with @JsonSerialize(using=...).

public class MoneyBean {
    //...

    @JsonProperty("amountOfMoney")
    @JsonSerialize(using = MoneySerializer.class)
    private BigDecimal amount;

    //getters/setters...
}

public class MoneySerializer extends JsonSerializer<BigDecimal> {
    @Override
    public void serialize(BigDecimal value, JsonGenerator jgen, SerializerProvider provider) throws IOException,
            JsonProcessingException {
        // put your desired money style here
        jgen.writeString(value.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
    }
}

That's it. A BigDecimal is now printed in the right way. I used a simple testcase to show it:

@Test
public void jsonSerializationTest() throws Exception {
     MoneyBean m = new MoneyBean();
     m.setAmount(new BigDecimal("20.3"));

     ObjectMapper mapper = new ObjectMapper();
     assertEquals("{\"amountOfMoney\":\"20.30\"}", mapper.writeValueAsString(m));
}

How to change style of a default EditText

You have a few options.

  1. Use Android assets studios Android Holo colors generator to generate the resources, styles and themes you need to add to your app to get the holo look across all devices.

  2. Use holo everywhere library.

  3. Use the PNG for the holo text fields and set them as background images yourself. You can get the images from the Android assets studios holo color generator. You'll have to make a drawable and define the normal, selected and disabled states.

UPDATE 2016-01-07

This answer is now outdated. Android has tinting API and ability to theme on controls directly now. A good reference for how to style or theme any element is a site called materialdoc.

iPhone 6 and 6 Plus Media Queries

This is what is working for me right now:

iPhone 6

@media only screen and (max-device-width: 667px) 
    and (-webkit-device-pixel-ratio: 2) {

iPhone 6+

@media screen and (min-device-width : 414px) 
    and (-webkit-device-pixel-ratio: 3)

jQuery javascript regex Replace <br> with \n

True jQuery way if you want to change directly the DOM without messing with inner HTML:

$('#text').find('br').prepend(document.createTextNode('\n')).remove();

Prepend inserts inside the element, before() is the method we need here:

$('#text').find('br').before(document.createTextNode('\n')).remove();

Code will find any <br> elements, insert raw text with new line character and then remove the <br> elements.

This should be faster if you work with long texts since there are no string operations here.

To display the new lines:

$('#text').css('white-space', 'pre-line');

Passing a String by Reference in Java?

For passing an object (including String) by reference in java, you might pass it as member of a surrounding adapter. A solution with a generic is here:

import java.io.Serializable;

public class ByRef<T extends Object> implements Serializable
{
    private static final long serialVersionUID = 6310102145974374589L;

    T v;

    public ByRef(T v)
    {
        this.v = v;
    }

    public ByRef()
    {
        v = null;
    }

    public void set(T nv)
    {
        v = nv;
    }

    public T get()
    {
        return v;
    }

// ------------------------------------------------------------------

    static void fillString(ByRef<String> zText)
    {
        zText.set(zText.get() + "foo");
    }

    public static void main(String args[])
    {
        final ByRef<String> zText = new ByRef<String>(new String(""));
        fillString(zText);
        System.out.println(zText.get());
    }
}

Java HttpRequest JSON & Response Handling

The simplest way is using libraries like google-http-java-client but if you want parse the JSON response by yourself you can do that in a multiple ways, you can use org.json, json-simple, Gson, minimal-json, jackson-mapper-asl (from 1.x)... etc

A set of simple examples:

Using Gson:

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

public class Gson {

    public static void main(String[] args) {
    }

    public HttpResponse http(String url, String body) {

        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            HttpPost request = new HttpPost(url);
            StringEntity params = new StringEntity(body);
            request.addHeader("content-type", "application/json");
            request.setEntity(params);
            HttpResponse result = httpClient.execute(request);
            String json = EntityUtils.toString(result.getEntity(), "UTF-8");

            com.google.gson.Gson gson = new com.google.gson.Gson();
            Response respuesta = gson.fromJson(json, Response.class);

            System.out.println(respuesta.getExample());
            System.out.println(respuesta.getFr());

        } catch (IOException ex) {
        }
        return null;
    }

    public class Response{

        private String example;
        private String fr;

        public String getExample() {
            return example;
        }
        public void setExample(String example) {
            this.example = example;
        }
        public String getFr() {
            return fr;
        }
        public void setFr(String fr) {
            this.fr = fr;
        }
    }
}

Using json-simple:

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class JsonSimple {

    public static void main(String[] args) {

    }

    public HttpResponse http(String url, String body) {

        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            HttpPost request = new HttpPost(url);
            StringEntity params = new StringEntity(body);
            request.addHeader("content-type", "application/json");
            request.setEntity(params);
            HttpResponse result = httpClient.execute(request);

            String json = EntityUtils.toString(result.getEntity(), "UTF-8");
            try {
                JSONParser parser = new JSONParser();
                Object resultObject = parser.parse(json);

                if (resultObject instanceof JSONArray) {
                    JSONArray array=(JSONArray)resultObject;
                    for (Object object : array) {
                        JSONObject obj =(JSONObject)object;
                        System.out.println(obj.get("example"));
                        System.out.println(obj.get("fr"));
                    }

                }else if (resultObject instanceof JSONObject) {
                    JSONObject obj =(JSONObject)resultObject;
                    System.out.println(obj.get("example"));
                    System.out.println(obj.get("fr"));
                }

            } catch (Exception e) {
                // TODO: handle exception
            }

        } catch (IOException ex) {
        }
        return null;
    }
}

etc...

How to append a char to a std::string?

int main()
{
  char d = 'd';
  std::string y("Hello worl");

  y += d;
  y.push_back(d);
  y.append(1, d); //appending the character 1 time
  y.insert(y.end(), 1, d); //appending the character 1 time
  y.resize(y.size()+1, d); //appending the character 1 time
  y += std::string(1, d); //appending the character 1 time
}

Note that in all of these examples you could have used a character literal directly: y += 'd';.

Your second example almost would have worked, for unrelated reasons. char d[1] = { 'd'}; didn't work, but char d[2] = { 'd'}; (note the array is size two) would have been worked roughly the same as const char* d = "d";, and a string literal can be appended: y.append(d);.

Simple way to create matrix of random numbers

When you say "a matrix of random numbers", you can use numpy as Pavel https://stackoverflow.com/a/15451997/6169225 mentioned above, in this case I'm assuming to you it is irrelevant what distribution these (pseudo) random numbers adhere to.

However, if you require a particular distribution (I imagine you are interested in the uniform distribution), numpy.random has very useful methods for you. For example, let's say you want a 3x2 matrix with a pseudo random uniform distribution bounded by [low,high]. You can do this like so:

numpy.random.uniform(low,high,(3,2))

Note, you can replace uniform by any number of distributions supported by this library.

Further reading: https://docs.scipy.org/doc/numpy/reference/routines.random.html

How do I create a new line in Javascript?

In html page:

document.write("<br>"); 

but if you are in JavaScript file, then this will work as new line:

document.write("\n");

SQL query return data from multiple tables

Part 3 - Tricks and Efficient Code

MySQL in() efficiency

I thought I would add some extra bits, for tips and tricks that have come up.

One question I see come up a fair bit, is How do I get non-matching rows from two tables and I see the answer most commonly accepted as something like the following (based on our cars and brands table - which has Holden listed as a brand, but does not appear in the cars table):

select
    a.ID,
    a.brand
from
    brands a
where
    a.ID not in(select brand from cars)

And yes it will work.

+----+--------+
| ID | brand  |
+----+--------+
|  6 | Holden |
+----+--------+
1 row in set (0.00 sec)

However it is not efficient in some database. Here is a link to a Stack Overflow question asking about it, and here is an excellent in depth article if you want to get into the nitty gritty.

The short answer is, if the optimiser doesn't handle it efficiently, it may be much better to use a query like the following to get non matched rows:

select
    a.brand
from
    brands a
        left join cars b
            on a.id=b.brand
where
    b.brand is null

+--------+
| brand  |
+--------+
| Holden |
+--------+
1 row in set (0.00 sec)

Update Table with same table in subquery

Ahhh, another oldie but goodie - the old You can't specify target table 'brands' for update in FROM clause.

MySQL will not allow you to run an update... query with a subselect on the same table. Now, you might be thinking, why not just slap it into the where clause right? But what if you want to update only the row with the max() date amoung a bunch of other rows? You can't exactly do that in a where clause.

update 
    brands 
set 
    brand='Holden' 
where 
    id=
        (select 
            id 
        from 
            brands 
        where 
            id=6);
ERROR 1093 (HY000): You can't specify target table 'brands' 
for update in FROM clause

So, we can't do that eh? Well, not exactly. There is a sneaky workaround that a surprisingly large number of users don't know about - though it does include some hackery that you will need to pay attention to.

You can stick the subquery within another subquery, which puts enough of a gap between the two queries so that it will work. However, note that it might be safest to stick the query within a transaction - this will prevent any other changes being made to the tables while the query is running.

update 
    brands 
set 
    brand='Holden' 
where id=
    (select 
        id 
    from 
        (select 
            id 
        from 
            brands 
        where 
            id=6
        ) 
    as updateTable);

Query OK, 0 rows affected (0.02 sec)
Rows matched: 1  Changed: 0  Warnings: 0

How can I get the timezone name in JavaScript?

Retrieve timezone by name (i.e. "America/New York")

moment.tz.guess();

c - warning: implicit declaration of function ‘printf’

the warning or error of kind IMPLICIT DECLARATION is that the compiler is expecting a Function Declaration/Prototype..

It might either be a header file or your own function Declaration..

Django set field value after a form is initialized

To throw yet another way into the mix: this works too, with a bit more modern notation. It just works around the fact that a QueryDict is immutable.

>>> the_form.data = {**f.data.dict(), 'some_field': 47}
>>> the_form['some_field'].as_widget()
'<input type="hidden" name="some_field" value="47"
        class="field-some_field" id="id_some_field">'

Is `shouldOverrideUrlLoading` really deprecated? What can I use instead?

Documenting in detail for future readers:

The short answer is you need to override both the methods. The shouldOverrideUrlLoading(WebView view, String url) method is deprecated in API 24 and the shouldOverrideUrlLoading(WebView view, WebResourceRequest request) method is added in API 24. If you are targeting older versions of android, you need the former method, and if you are targeting 24 (or later, if someone is reading this in distant future) it's advisable to override the latter method as well.

The below is the skeleton on how you would accomplish this:

class CustomWebViewClient extends WebViewClient {

    @SuppressWarnings("deprecation")
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        final Uri uri = Uri.parse(url);
        return handleUri(uri);
    }

    @TargetApi(Build.VERSION_CODES.N)
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
        final Uri uri = request.getUrl();
        return handleUri(uri);
    }

    private boolean handleUri(final Uri uri) {
        Log.i(TAG, "Uri =" + uri);
        final String host = uri.getHost();
        final String scheme = uri.getScheme();
        // Based on some condition you need to determine if you are going to load the url 
        // in your web view itself or in a browser. 
        // You can use `host` or `scheme` or any part of the `uri` to decide.
        if (/* any condition */) {
            // Returning false means that you are going to load this url in the webView itself
            return false;
        } else {
            // Returning true means that you need to handle what to do with the url
            // e.g. open web page in a Browser
            final Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
            return true;
        }
    }
}

Just like shouldOverrideUrlLoading, you can come up with a similar approach for shouldInterceptRequest method.

git pull fails "unable to resolve reference" "unable to update local ref"

Explanation: It appears your remote repo (in Github / bitbucket) branches were removed ,though your local references were not updated and pointing to non existent references.

In order to solve this issue:

git fetch --prune
git fetch --all
git pull

For extra reading - Reference from Github documentation :

git-fetch - Download objects and refs from another repository

--all Fetch all remotes.

--prune After fetching, remove any remote tracking branches which no longer exist on the remote.

how to get docker-compose to use the latest image from repository

To get the latest images use docker-compose build --pull

I use below command which is really 3 in 1

docker-compose down && docker-compose build --pull && docker-compose up -d

This command will stop the services, pulls the latest image and then starts the services.

TypeError: Image data can not convert to float

Try to use this,

   plt.imshow(numpy.real(A))
   plt.show()

instead of plt.imshow(A)

Script Tag - async & defer

It seems the behavior of defer and async is browser dependent, at least on the execution phase. NOTE, defer only applies to external scripts. I'm assuming async follows same pattern.

In IE 11 and below, the order seems to be like this:

  • async (could partially execute while page loading)
  • none (could execute while page loading)
  • defer (executes after page loaded, all defer in order of placement in file)

In Edge, Webkit, etc, the async attribute seems to be either ignored or placed at the end:

  • data-pagespeed-no-defer (executes before any other scripts, while page is loading)
  • none (could execute while page is loading)
  • defer (waits until DOM loaded, all defer in order of placement in file)
  • async (seems to wait until DOM loaded)

In newer browsers, the data-pagespeed-no-defer attribute runs before any other external scripts. This is for scripts that don't depend on the DOM.

NOTE: Use defer when you need an explicit order of execution of your external scripts. This tells the browser to execute all deferred scripts in order of placement in the file.

ASIDE: The size of the external javascripts did matter when loading...but had no effect on the order of execution.

If you're worried about the performance of your scripts, you may want to consider minification or simply loading them dynamically with an XMLHttpRequest.

How do I get the web page contents from a WebView?

You also need to annotate the method with @JavascriptInterface if your targetSdkVersion is >= 17 - because there is new security requirements in SDK 17, i.e. all javascript methods must be annotated with @JavascriptInterface. Otherwise you will see error like: Uncaught TypeError: Object [object Object] has no method 'processHTML' at null:1

Insert an item into sorted list in Python

Hint 1: You might want to study the Python code in the bisect module.

Hint 2: Slicing can be used for list insertion:

>>> s = ['a', 'b', 'd', 'e']
>>> s[2:2] = ['c']
>>> s
['a', 'b', 'c', 'd', 'e']

Closing Application with Exit button

i try this

Button btnexit = (Button)findviewbyId(btn_exit);

btnexit.setOnClicklistenr(new onClicklister(){

     @override
     public void onClick(View v){
            finish();
});

How to make <input type="file"/> accept only these types?

IMPORTANT UPDATE:

Due to use of only application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint... allows only till 2003 MS products, and not newest. I've found this:

application/msword, application/vnd.openxmlformats-officedocument.wordprocessingml.document, application/vnd.ms-powerpoint, application/vnd.openxmlformats-officedocument.presentationml.slideshow, application/vnd.openxmlformats-officedocument.presentationml.presentation

And that includes the new ones. For other files, you can retrieve the MIME TYPE in your file by this way (pardon the lang)(in MIME list types, there aren't this ones):

enter image description here

You can select & copy the type of content

Can I change a column from NOT NULL to NULL without dropping it?

ALTER TABLE myTable ALTER COLUMN myColumn {DataType} NULL

where {DataType} is the current data type of that column (For example int or varchar(10))

How do I extract data from JSON with PHP?

// Using json as php array 

$json = '[{"user_id":"1","user_name":"Sayeed Amin","time":"2019-11-06 13:21:26"}]';

//or use from file
//$json = file_get_contents('results.json');

$someArray = json_decode($json, true);

foreach ($someArray as $key => $value) {
    echo $value["user_id"] . ", " . $value["user_name"] . ", " . $value["time"] . "<br>";
}

How do I convert a long to a string in C++?

One of the things not covered by anybody so far, to help you think about the problem further, is what format should a long take when it is cast to a string.

Just have a look at a spreedsheet program (like Calc/Excel). Do you want it rounded to the nearest million, with brackets if it's negative, always to show the sign.... Is the number realy a representation of something else, should you show it in Oractal or Hex instead?

The answers so far have given you some default output, but perhaps not the right ones.

How can I open an Excel file in Python?

Try the xlrd library.

[Edit] - from what I can see from your comment, something like the snippet below might do the trick. I'm assuming here that you're just searching one column for the word 'john', but you could add more or make this into a more generic function.

from xlrd import open_workbook

book = open_workbook('simple.xls',on_demand=True)
for name in book.sheet_names():
    if name.endswith('2'):
        sheet = book.sheet_by_name(name)

        # Attempt to find a matching row (search the first column for 'john')
        rowIndex = -1
        for cell in sheet.col(0): # 
            if 'john' in cell.value:
                break

        # If we found the row, print it
        if row != -1:
            cells = sheet.row(row)
            for cell in cells:
                print cell.value

        book.unload_sheet(name) 

Python JSON serialize a Decimal object

I would like to let everyone know that I tried Michal Marczyk's answer on my web server that was running Python 2.6.5 and it worked fine. However, I upgraded to Python 2.7 and it stopped working. I tried to think of some sort of way to encode Decimal objects and this is what I came up with:

import decimal

class DecimalEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, decimal.Decimal):
            return str(o)
        return super(DecimalEncoder, self).default(o)

Note that this will convert the decimal to its string representation (e.g.; "1.2300") to a. not lose significant digits and b. prevent rounding errors.

This should hopefully help anyone who is having problems with Python 2.7. I tested it and it seems to work fine. If anyone notices any bugs in my solution or comes up with a better way, please let me know.

Getting the actual usedrange

Here's another one. It looks for the first and last non empty cell and builds are range from those. This also handles cases where your data is not rectangular and does not start in A1. Furthermore it handles merged cells as well, which .Find skips when executed from a macro, used on .Cells on a worksheet.

Function getUsedRange(ByRef sheet As Worksheet) As Range
' finds used range by looking for non empty cells
' works around bug in .Find that skips merged cells
' by starting at with the UsedRange (that may be too big)

' credit to https://contexturesblog.com/archives/2012/03/01/select-actual-used-range-in-excel-sheet/
' for the .Find commands

Dim excelsUsedRange As Range
Dim lastRow As Long
Dim lastCol As Long
Dim lastCell As Range
Dim firstRow As Long
Dim firstCol As Long
Dim firstCell As Range

Set excelsUsedRange = ActiveSheet.UsedRange

lastRow = excelsUsedRange.Find(What:="*", _
                               LookIn:=xlValues, SearchOrder:=xlRows, _
                               SearchDirection:=xlPrevious).Row
lastCol = excelsUsedRange.Find(What:="*", _
                               LookIn:=xlValues, SearchOrder:=xlByColumns, _
                               SearchDirection:=xlPrevious).Column
Set lastCell = sheet.Cells(lastRow, lastCol)

firstRow = excelsUsedRange.Find(What:="*", After:=lastCell, _
                                LookIn:=xlValues, SearchOrder:=xlRows, _
                                SearchDirection:=xlNext).Row
firstCol = excelsUsedRange.Find(What:="*", After:=lastCell, _
                                LookIn:=xlValues, SearchOrder:=xlByColumns, _
                                SearchDirection:=xlNext).Row
Set firstCell = sheet.Cells(firstRow, firstCol)
Set getUsedRange = sheet.Range(firstCell, lastCell)
End Function

How do I execute a command and get the output of the command within C++ using POSIX?

Assuming POSIX, simple code to capture stdout:

#include <sys/wait.h>
#include <unistd.h>
#include <string>
#include <vector>

std::string qx(const std::vector<std::string>& args) {
  int stdout_fds[2];
  pipe(stdout_fds);

  int stderr_fds[2];
  pipe(stderr_fds);

  const pid_t pid = fork();
  if (!pid) {
    close(stdout_fds[0]);
    dup2(stdout_fds[1], 1);
    close(stdout_fds[1]);

    close(stderr_fds[0]);
    dup2(stderr_fds[1], 2);
    close(stderr_fds[1]);

    std::vector<char*> vc(args.size() + 1, 0);
    for (size_t i = 0; i < args.size(); ++i) {
      vc[i] = const_cast<char*>(args[i].c_str());
    }

    execvp(vc[0], &vc[0]);
    exit(0);
  }

  close(stdout_fds[1]);

  std::string out;
  const int buf_size = 4096;
  char buffer[buf_size];
  do {
    const ssize_t r = read(stdout_fds[0], buffer, buf_size);
    if (r > 0) {
      out.append(buffer, r);
    }
  } while (errno == EAGAIN || errno == EINTR);

  close(stdout_fds[0]);

  close(stderr_fds[1]);
  close(stderr_fds[0]);

  int r, status;
  do {
    r = waitpid(pid, &status, 0);
  } while (r == -1 && errno == EINTR);

  return out;
}

Code contributions are welcome for more functionality:

https://github.com/ericcurtin/execxx

How do I get column datatype in Oracle with PL-SQL with low privileges?

To see the internal representation size in bytes you can use:

REGEXP_SUBSTR(DUMP(your_column_name), 'Len=(\d+)\:', 1, 1, 'c', 1 ) 

How do you do a ‘Pause’ with PowerShell 2.0?

In addition to Michael Sorens' answer:

<6> ReadKey in a new process

Start-Process PowerShell {[void][System.Console]::ReadKey($true)} -Wait -NoNewWindow
  • Advantage: Accepts any key but properly excludes Shift, Alt, Ctrl modifier keys.
  • Advantage: Works in PS-ISE.

How do I fix the Visual Studio compile error, "mismatch between processor architecture"?

If your C# DLL has x86-based dependencies, then your DLL itself is going to have to be x86. I don't really see a way around that. VS complains about changing it to (for example) x64 because a 64-bit executable can't load 32-bit libraries.

I'm a little confused about the configuration of the C++ project. The warning message that was provided for the build suggests that it was targeted for AnyCPU, because it reported the platform that it targeted was [MSIL], but you indicated that the configuration for the project was actually Win32. A native Win32 app shouldn't involve the MSIL - although it would likely need to have CLR support enabled if it is interacting with a C# library. So I think there are a few gaps on the information side.

Could I respectfully ask you review and post a bit more detail of the exact configuration of the projects and how they are inter-related? Be glad to help further if possible.

How to print from Flask @app.route to python console

I tried running @Viraj Wadate's code, but couldn't get the output from app.logger.info on the console.

To get INFO, WARNING, and ERROR messages in the console, the dictConfig object can be used to create logging configuration for all logs (source):

from logging.config import dictConfig
from flask import Flask


dictConfig({
    'version': 1,
    'formatters': {'default': {
        'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s',
    }},
    'handlers': {'wsgi': {
        'class': 'logging.StreamHandler',
        'stream': 'ext://flask.logging.wsgi_errors_stream',
        'formatter': 'default'
    }},
    'root': {
        'level': 'INFO',
        'handlers': ['wsgi']
    }
})


app = Flask(__name__)

@app.route('/')
def index():
    return "Hello from Flask's test environment"

@app.route('/print')
def printMsg():
    app.logger.warning('testing warning log')
    app.logger.error('testing error log')
    app.logger.info('testing info log')
    return "Check your console"

if __name__ == '__main__':
    app.run(debug=True)

UnicodeEncodeError: 'ascii' codec can't encode character u'\xef' in position 0: ordinal not in range(128)

An easy solution to overcome this problem is to set your default encoding to utf8. Follow is an example

import sys

reload(sys)
sys.setdefaultencoding('utf8')

Convert string to buffer Node

Note: Just reposting John Zwinck's comment as answer.

One issue might be that you are using a older version of Node (for the moment, I cannot upgrade, codebase struck with v4.3.1). Simple solution here is, using the deprecated way:

new Buffer(bufferStr)

Note #2: This is for people struck in older version, for whom Buffer.from does not work

how to get date of yesterday using php?

Yesterday Date in PHP:

echo date("Y-m-d", strtotime("yesterday")); 

Can someone explain mappedBy in JPA and Hibernate?

MappedBy signals hibernate that the key for the relationship is on the other side.

This means that although you link 2 tables together, only 1 of those tables has a foreign key constraint to the other one. MappedBy allows you to still link from the table not containing the constraint to the other table.

SQL query for extracting year from a date

This worked for me:

SELECT EXTRACT(YEAR FROM ASOFDATE) FROM PSASOFDATE;

Remove all spaces from a string in SQL Server

A functional version (udf) that removes spaces, cr, lf, tabs or configurable.

select Common.ufn_RemoveWhitespace(' 234   asdf   wefwef 3  x   ', default) as S

Result: '234asdfwefwef3x'

alter function Common.RemoveWhitespace
(
    @pString nvarchar(max),
    @pWhitespaceCharsOpt nvarchar(max) = null -- default: tab, lf, cr, space 
)  
returns nvarchar(max) as
/*--------------------------------------------------------------------------------------------------
    Purpose:   Compress whitespace

    Example:  select Common.ufn_RemoveWhitespace(' 234   asdf   wefwef 3  x   ', default) as s 
              -- Result: 234asdfwefwef3x

    Modified    By          Description
    ----------  ----------- --------------------------------------------------------------------
    2018.07.24  crokusek    Initial Version 
  --------------------------------------------------------------------------------------------------*/ 
begin    
    declare 
        @maxLen bigint = 1073741823, -- (2^31 - 1) / 2 (https://stackoverflow.com/a/4270085/538763)
        @whitespaceChars nvarchar(30) = coalesce(
            @pWhitespaceCharsOpt, 
            char(9) + char(10) + char(13) + char(32));  -- tab, lf, cr, space

    declare
        @whitespacePattern nvarchar(30) = '%[' + @whitespaceChars + ']%',
        @nonWhitespacePattern nvarchar(30) = '%[^' + @whitespaceChars + ']%',
        @previousString nvarchar(max) = '';

    while (@pString != @previousString)
    begin
        set @previousString = @pString;

        declare
            @whiteIndex int = patindex(@whitespacePattern, @pString);

        if (@whiteIndex > 0)
        begin                   
            declare 
                @whitespaceLength int = nullif(patindex(@nonWhitespacePattern, substring(@pString, @whiteIndex, @maxLen)), 0) - 1;                

            set @pString = 
                substring(@pString, 1, @whiteIndex - 1) + 
                iif(@whiteSpaceLength > 0, substring(@pString, @whiteIndex + @whiteSpaceLength, @maxLen), '');
        end        
    end        
    return @pString;
end
go

How do I bind Twitter Bootstrap tooltips to dynamically created elements?

For me, only catching the mouseenter event was a bit buggy, and the tooltip was not showing/hiding properly. I had to write this, and it is now working perfectly:

$(document).on('mouseenter','[rel=tooltip]', function(){
    $(this).tooltip('show');
});

$(document).on('mouseleave','[rel=tooltip]', function(){
    $(this).tooltip('hide');
});

How to make a Bootstrap accordion collapse when clicking the header div?

Here's a solution for Bootstrap4. You just need to put the card-header class in the a tag. This is a modified from an example in W3Schools.

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
  <div id="accordion">_x000D_
    <div class="card">_x000D_
      <a class="card-link card-header" data-toggle="collapse" href="#collapseOne" >_x000D_
        Collapsible Group Item #1_x000D_
      </a>_x000D_
      <div id="collapseOne" class="collapse" data-parent="#accordion">_x000D_
        <div class="card-body">_x000D_
          Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat._x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
    <div class="card">_x000D_
      <a class="collapsed card-link card-header" data-toggle="collapse" href="#collapseTwo">_x000D_
        Collapsible Group Item #2_x000D_
      </a>_x000D_
      <div id="collapseTwo" class="collapse" data-parent="#accordion">_x000D_
        <div class="card-body">_x000D_
          Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat._x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
    <div class="card">_x000D_
      <a class="card-link card-header" data-toggle="collapse" href="#collapseThree">_x000D_
        Collapsible Group Item #3_x000D_
      </a>_x000D_
      <div id="collapseThree" class="collapse" data-parent="#accordion">_x000D_
        <div class="card-body">_x000D_
          Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat._x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Error LNK2019: Unresolved External Symbol in Visual Studio

I was getting this error after adding the include files and linking the library. It was because the lib was built with non-unicode and my application was unicode. Matching them fixed it.

How to view the committed files you have not pushed yet?

Assuming you're on local branch master, which is tracking origin/master:

git diff --stat origin/master..

What is the difference between concurrent programming and parallel programming?

Although there isn’t complete agreement on the distinction between the terms parallel and concurrent, many authors make the following distinctions:

  • In concurrent computing, a program is one in which multiple tasks can be in progress at any instant.
  • In parallel computing, a program is one in which multiple tasks cooperate closely to solve a problem.

So parallel programs are concurrent, but a program such as a multitasking operating system is also concurrent, even when it is run on a machine with only one core, since multiple tasks can be in progress at any instant.

Source: An introduction to parallel programming, Peter Pacheco

Java - What does "\n" mean?

In the specific case of the code example from the original question, the

System.out.print("\n");

is there to move to a new line between incrementing i.

So the first print statement prints all of the elements of Grid[0][j]. When the innermost for loop has completed, the "\n" gets printed and then all of the elements of Grid[1][j] are printed on the next line, and this is repeated until you have a 10x10 grid of the elements of the 2-dimensional array, Grid.

Facebook Android Generate Key Hash

use this in kotlin for print key hash in log

try {
        val info = context.getPackageManager().getPackageInfo(context.packageName,
                PackageManager.GET_SIGNATURES);
        for (signature in info.signatures) {
            val md = MessageDigest.getInstance("SHA")
            md.update(signature.toByteArray())
            Log.d("Key hash ", android.util.Base64.encodeToString(md.digest(), android.util.Base64.DEFAULT))
        }
    }catch (e:Exception){

    }

Finding longest string in array

var longest = (arr) => {
  let sum = 0
  arr.map((e) => {
    sum = e.length > sum ? e.length : sum
  })
  return sum
}

it can be work

npm not working - "read ECONNRESET"

Remove yarn.lock , package-lock.json, node_modules

and then

npm install -f 

Worked for me

Uncaught TypeError: Cannot read property 'length' of undefined

console.log(typeof json_data !== 'undefined'
    ? json_data.length : 'There is no spoon.');

...or more simply...

console.log(json_data ? json_data.length : 'json_data is null or undefined');

Copy / Put text on the clipboard with FireFox, Safari and Chrome

Firefox does allow you to store data in the clipboard, but due to security implications it is disabled by default. See how to enable it in "Granting JavaScript access to the clipboard" in the Mozilla Firefox knowledge base.

The solution offered by amdfan is the best if you are having a lot of users and configuring their browser isn't an option. Though you could test if the clipboard is available and provide a link for changing the settings, if the users are tech savvy. The JavaScript editor TinyMCE follows this approach.

Can an Android NFC phone act as an NFC tag?

Its possible to make Android device behave as an NFC Tag. Such a behaviour is called Card Emulation.

  • Card emulation can be host-based(HCE) or secure-element based(CE).
  • In HCE, an application running on the Android main processor responds to the reader. So, the phone needs to be ON.
  • In CE, an applet residing in the Secure element responds to the reader. Here, its sufficient to have the NFC controller powered, with rest of the device suspended.
  • One of these or both approaches can be active simultaneously.
    A routing table instructs the NFC controller where route the Reader's commands to.

jQuery deferreds and promises - .then() vs .done()

There is a very simple mental mapping in response that was a bit hard to find in the other answers:

when I try to open an HTML file through `http://localhost/xampp/htdocs/index.html` it says unable to connect to localhost

You should simply create your own folder in htdocs and save your .html and .php files in it. An example is create a folder called myNewFolder directly in htdocs. Don't put it in index.html. Then save all your.html and .php files in it like this-> "localhost/myNewFolder/myFilename.html" or "localhost/myNewFolder/myFilename.php" I hope this helps.

UINavigationBar Hide back Button Text

You can implement UINavigationControllerDelegate like this:

Older Swift

func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController, animated: Bool) {
    let item = UIBarButtonItem(title: " ", style: .Plain, target: nil, action: nil)
    viewController.navigationItem.backBarButtonItem = item
}

Swift 4.x

class MyNavigationController: UINavigationController, UINavigationControllerDelegate {
    override func viewDidLoad() {
        super.viewDidLoad()
        self.delegate = self
    }

    func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
        let item = UIBarButtonItem(title: " ", style: .plain, target: nil, action: nil)
        viewController.navigationItem.backBarButtonItem = item
    }
}

backBarButtonItem is nil by default and it affects next pushed controller, so you just set it for all controllers

numpy max vs amax vs maximum

You've already stated why np.maximum is different - it returns an array that is the element-wise maximum between two arrays.

As for np.amax and np.max: they both call the same function - np.max is just an alias for np.amax, and they compute the maximum of all elements in an array, or along an axis of an array.

In [1]: import numpy as np

In [2]: np.amax
Out[2]: <function numpy.core.fromnumeric.amax>

In [3]: np.max
Out[3]: <function numpy.core.fromnumeric.amax>

Invert colors of an image in CSS or JavaScript

You can apply the style via javascript. This is the Js code below that applies the filter to the image with the ID theImage.

function invert(){
document.getElementById("theImage").style.filter="invert(100%)";
}

And this is the

<img id="theImage" class="img-responsive" src="http://i.imgur.com/1H91A5Y.png"></img>

Now all you need to do is call invert() We do this when the image is clicked.

_x000D_
_x000D_
function invert(){_x000D_
document.getElementById("theImage").style.filter="invert(100%)";_x000D_
}
_x000D_
<h4> Click image to invert </h4>_x000D_
_x000D_
<img id="theImage" class="img-responsive" src="http://i.imgur.com/1H91A5Y.png" onClick="invert()" ></img>
_x000D_
_x000D_
_x000D_

We use this on our website

What is the difference between the HashMap and Map objects in Java?

Map is an interface that HashMap implements. The difference is that in the second implementation your reference to the HashMap will only allow the use of functions defined in the Map interface, while the first will allow the use of any public functions in HashMap (which includes the Map interface).

It will probably make more sense if you read Sun's interface tutorial

How to while loop until the end of a file in Python without checking for empty line?

for line in f

reads all file to a memory, and that can be a problem.

My offer is to change the original source by replacing stripping and checking for empty line. Because if it is not last line - You will receive at least newline character in it ('\n'). And '.strip()' removes it. But in last line of a file You will receive truely empty line, without any characters. So the following loop will not give You false EOF, and You do not waste a memory:

with open("blablabla.txt", "r") as fl_in:
   while True:
      line = fl_in.readline()

        if not line:
            break

      line = line.strip()
      # do what You want

How to find a value in an array of objects in JavaScript?

There's already a lot of good answers here so why not one more, use a library like lodash or underscore :)

obj = {
   1 : { name : 'bob' , dinner : 'pizza' },
   2 : { name : 'john' , dinner : 'sushi' },
   3 : { name : 'larry', dinner : 'hummus' }
}

_.where(obj, {dinner: 'pizza'})
>> [{"name":"bob","dinner":"pizza"}]

How to dynamically change header based on AngularJS partial view?

Simplistic solution for angular-ui-router :

HTML :

<html ng-app="myApp">
  <head>
     <title ng-bind="title"></title>
     .....
     .....  
  </head>
</html>

App.js > myApp.config block

$stateProvider
    .state("home", {
        title: "My app title this will be binded in html title",
        url: "/home",
        templateUrl: "/home.html",
        controller: "homeCtrl"
    })

App.js>myApp.run

myApp.run(['$rootScope','$state', function($rootScope,$state) {
   $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
    $rootScope.title = $state.current.title;
    console.log($state);
   });
}]);

How do I remove time part from JavaScript date?

Split it by space and take first part like below. Hope this will help you.

var d = '12/12/1955 12:00:00 AM';
d = d.split(' ')[0];
console.log(d);

What are the differences between json and simplejson Python modules?

Another reason projects use simplejson is that the builtin json did not originally include its C speedups, so the performance difference was noticeable.

Vue.js dynamic images not working

There is another way of doing it by adding your image files to public folder instead of assets and access those as static images.

<img :src="'/img/' + pic + '.png'" v-bind:alt="pic" >

This is where you need to put your static images:

enter image description here

How to call a parent method from child class in javascript?

Well in order to do this, you are not limited with the Class abstraction of ES6. Accessing the parent constructor's prototype methods is possible through the __proto__ property (I am pretty sure there will be fellow JS coders to complain that it's depreciated) which is depreciated but at the same time discovered that it is actually an essential tool for sub-classing needs (especially for the Array sub-classing needs though). So while the __proto__ property is still available in all major JS engines that i know, ES6 introduced the Object.getPrototypeOf() functionality on top of it. The super() tool in the Class abstraction is a syntactical sugar of this.

So in case you don't have access to the parent constructor's name and don't want to use the Class abstraction you may still do as follows;

function ChildObject(name) {
    // call the parent's constructor
    ParentObject.call(this, name);
    this.myMethod = function(arg) {
    //this.__proto__.__proto__.myMethod.call(this,arg);
    Object.getPrototypeOf(Object.getPrototypeOf(this)).myMethod.call(this,arg);
    }
}

Response Buffer Limit Exceeded

Here is what a Microsoft support page says about this: https://support.microsoft.com/en-us/help/944886/error-message-when-you-use-the-response-binarywrite-method-in-iis-6-an.

But it’s easier in the GUI:

  • In Internet Information Services (IIS) Manager, click on ASP.
  • Change Behavior > Limits Properties > Response Buffering Limit from 4 MB to 64 MB.
  • Apply and restart.

Deserialize from string instead TextReader

static T DeserializeXml<T>(string sourceXML) where T : class
{
    var serializer = new XmlSerializer(typeof(T));
    T result = null;

    using (TextReader reader = new StringReader(sourceXML))
    {
        result = (T) serializer.Deserialize(reader);
    }

    return result;
}

How to update Android Studio automatically?

The simplest way to update is as follows:

  1. Go to the start screen for Android Studio. If it automatically opens a project when you open it, close that project (not exit).

  2. At the bottom there will be a check for updates link which you can use to update to the latest version.

React.js: Identifying different inputs with one onChange handler

Hi have improved ssorallen answer. You don't need to bind function because you can access to the input without it.

var Hello = React.createClass({
    render: function() {
        var total = this.state.input1 + this.state.input2;
        return (
             <div>{total}<br/>
                  <input type="text" 
                    value={this.state.input1}
                    id="input1"  
                    onChange={this.handleChange} />
                 <input type="text" 
                    value={this.state.input2}
                    id="input2" 
                    onChange={this.handleChange} />
            </div>
       );
   },
   handleChange: function (name, value) {
       var change = {};
       change[name] = value;
       this.setState(change);
   }
});

React.renderComponent(<Hello />, document.getElementById('content'));

How to change css property using javascript

Consider the following example: If you want to change a single CSS property(say, color to 'blue'), then the below statement works fine.

document.getElementById("ele_id").style.color="blue";

But, for changing multiple properies the more robust way is using Object.assign() or, object spread operator {...};

See below:

const ele=document.getElementById("ele_id");
const custom_style={
    display: "block",
    color: "red"
}

//Object.assign():
Object.assign(ele.style,custum_style);

Spread operator works similarly, just the syntax is a little different.

How to split the screen with two equal LinearLayouts?

I am answering this question after 4-5 years but best practices to do this as below

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">

   <LinearLayout
      android:id="@+id/firstLayout"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:layout_toLeftOf="@+id/secondView"
      android:orientation="vertical"></LinearLayout>

   <View
      android:id="@+id/secondView"
      android:layout_width="0dp"
      android:layout_height="match_parent"
      android:layout_centerHorizontal="true" />

   <LinearLayout
      android:id="@+id/thirdLayout"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:layout_toRightOf="@+id/secondView"
      android:orientation="vertical"></LinearLayout>
</RelativeLayout>

This is right approach as use of layout_weight is always heavy for UI operations. Splitting Layout equally using LinearLayout is not good practice

Bootstrap 3 - jumbotron background image effect

I think what you are looking for is to keep the background image fixed and just move the content on scroll. For that you have to simply use the following css property :

background-attachment: fixed;

How to switch to another domain and get-aduser

Try specifying a DC in DomainB using the -Server property. Ex:

Get-ADUser -Server "dc01.DomainB.local" -Filter {EmailAddress -like "*Smith_Karla*"} -Properties EmailAddress

Using TortoiseSVN how do I merge changes from the trunk to a branch and vice versa?

Take a look at svnmerge.py. It's command-line, can't be invoked by TortoiseSVN, but it's more powerful. From the FAQ:

Traditional subversion will let you merge changes, but it doesn't "remember" what you've already merged. It also doesn't provide a convenient way to exclude a change set from being merged. svnmerge.py automates some of the work, and simplifies it. Svnmerge also creates a commit message with the log messages from all of the things it merged.

Better techniques for trimming leading zeros in SQL Server?

SUBSTRING(str_col, PATINDEX('%[^0]%', str_col+'.'), LEN(str_col))

C++ catching all exceptions

Well this really depends on the compiler environment. gcc does not catch these. Visual Studio and the last Borland that I used did.

So the conclusion about crashes is that it depends on the quality of your development environment.

The C++ specification says that catch(...) must catch any exceptions, but it doesn't in all cases.

At least from what I tried.

Simple way to calculate median with MySQL

Building off of velcro's answer, for those of you having to do a median off of something that is grouped by another parameter:

SELECT grp_field, t1.val FROM (
   SELECT grp_field, @rownum:=IF(@s = grp_field, @rownum + 1, 0) AS row_number,
   @s:=IF(@s = grp_field, @s, grp_field) AS sec, d.val
  FROM data d,  (SELECT @rownum:=0, @s:=0) r
  ORDER BY grp_field, d.val
) as t1 JOIN (
  SELECT grp_field, count(*) as total_rows
  FROM data d
  GROUP BY grp_field
) as t2
ON t1.grp_field = t2.grp_field
WHERE t1.row_number=floor(total_rows/2)+1;

How would you make two <div>s overlap?

Just use negative margins, in the second div say:

<div style="margin-top: -25px;">

And make sure to set the z-index property to get the layering you want.

Android Studio - Importing external Library/Jar

you export the project from Eclipse and then import the project from Android Studio, this should solve your problem, open a eclipse project without importing it from Android Studio you can cause problems, look at: (Excuse my language, I speak Spanish.) http://developer.android.com/intl/es/sdk/installing/migrate.html

Concept behind putting wait(),notify() methods in Object class

The other answers to this question all miss the key point that in Java, there is one mutex associated with every object. (I'm assuming you know what a mutex or "lock" is.) This is not the case in most programming languages which have the concept of "locks". For example, in Ruby, you have to explicitly create as many Mutex objects as you need.

I think I know why the creators of Java made this choice (although, in my opinion, it was a mistake). The reason has to do with the inclusion of the synchronized keyword. I believe that the creators of Java (naively) thought that by including synchronized methods in the language, it would become easy for people to write correct multithreaded code -- just encapsulate all your shared state in objects, declare the methods that access that state as synchronized, and you're done! But it didn't work out that way...

Anyways, since any class can have synchronized methods, there needs to be one mutex for each object, which the synchronized methods can lock and unlock.

wait and notify both rely on mutexes. Maybe you already understand why this is the case... if not I can add more explanation, but for now, let's just say that both methods need to work on a mutex. Each Java object has a mutex, so it makes sense that wait and notify can be called on any Java object. Which means that they need to be declared as methods of Object.

Another option would have been to put static methods on Thread or something, which would take any Object as an argument. That would have been much less confusing to new Java programmers. But they didn't do it that way. It's much too late to change any of these decisions; too bad!

Age from birthdate in python

Expanding on Danny's Solution, but with all sorts of ways to report ages for younger folk (note, today is datetime.date(2015,7,17)):

def calculate_age(born):
    '''
        Converts a date of birth (dob) datetime object to years, always rounding down.
        When the age is 80 years or more, just report that the age is 80 years or more.
        When the age is less than 12 years, rounds down to the nearest half year.
        When the age is less than 2 years, reports age in months, rounded down.
        When the age is less than 6 months, reports the age in weeks, rounded down.
        When the age is less than 2 weeks, reports the age in days.
    '''
    today = datetime.date.today()
    age_in_years = today.year - born.year - ((today.month, today.day) < (born.month, born.day))
    months = (today.month - born.month - (today.day < born.day)) %12
    age = today - born
    age_in_days = age.days
    if age_in_years >= 80:
        return 80, 'years or older'
    if age_in_years >= 12:
        return age_in_years, 'years'
    elif age_in_years >= 2:
        half = 'and a half ' if months > 6 else ''
        return age_in_years, '%syears'%half
    elif months >= 6:
        return months, 'months'
    elif age_in_days >= 14:
        return age_in_days/7, 'weeks'
    else:
        return age_in_days, 'days'

Sample code:

print '%d %s' %calculate_age(datetime.date(1933,6,12)) # >=80 years
print '%d %s' %calculate_age(datetime.date(1963,6,12)) # >=12 years
print '%d %s' %calculate_age(datetime.date(2010,6,19)) # >=2 years
print '%d %s' %calculate_age(datetime.date(2010,11,19)) # >=2 years with half
print '%d %s' %calculate_age(datetime.date(2014,11,19)) # >=6 months
print '%d %s' %calculate_age(datetime.date(2015,6,4)) # >=2 weeks
print '%d %s' %calculate_age(datetime.date(2015,7,11)) # days old

80 years or older
52 years
5 years
4 and a half years
7 months
6 weeks
7 days

How to apply shell command to each line of a command output?

You can use a for loop:

for file in * ; do
   echo "$file"
done

Note that if the command in question accepts multiple arguments, then using xargs is almost always more efficient as it only has to spawn the utility in question once instead of multiple times.

Pause Console in C++ program

I always used a couple lines of code which clear the input stream of any characters and then wait for input to ignore.

Something like:

void pause() {
    cin.clear();
    cout << endl << "Press any key to continue...";
    cin.ignore();
}

And then any time I need it in the program I have my own pause(); function, without the overhead of a system pause. This is only really an issue when writing console programs that you want to stay open or stay fixated on a certain point though.

How to parse month full form string using DateFormat in Java?

LocalDate from java.time

Use LocalDate from java.time, the modern Java date and time API, for a date

    DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MMMM d, u", Locale.ENGLISH);
    LocalDate date = LocalDate.parse("June 27, 2007", dateFormatter);
    System.out.println(date);

Output:

2007-06-27

As others have said already, remember to specify an English-speaking locale when your string is in English. A LocalDate is a date without time of day, so a lot better suitable for the date from your string than the old Date class. Despite its name a Date does not represent a date but a point in time that falls on at least two different dates in different time zones of the world.

Only if you need an old-fashioned Date for an API that you cannot afford to upgrade to java.time just now, convert like this:

    Instant startOfDay = date.atStartOfDay(ZoneId.systemDefault()).toInstant();
    Date oldfashionedDate = Date.from(startOfDay);
    System.out.println(oldfashionedDate);

Output in my time zone:

Wed Jun 27 00:00:00 CEST 2007

Link

Oracle tutorial: Date Time explaining how to use java.time.

ffmpeg - Converting MOV files to MP4

The command to just stream it to a new container (mp4) needed by some applications like Adobe Premiere Pro without encoding (fast) is:

ffmpeg -i input.mov -qscale 0 output.mp4

Alternative as mentioned in the comments, which re-encodes with best quaility (-qscale 0):

ffmpeg -i input.mov -q:v 0 output.mp4

How do I change the IntelliJ IDEA default JDK?

For latest version intellij, to set default jdk/sdk for new projects go to

Configure->Structure for New Projects -> Project Settings -> Project SDK

How can I get the last day of the month in C#?

Another way of doing it:

DateTime today = DateTime.Today;
DateTime endOfMonth = new DateTime(today.Year, 
                                   today.Month, 
                                   DateTime.DaysInMonth(today.Year, 
                                                        today.Month));

Create dynamic URLs in Flask with url_for()

Refer to the Flask API document for flask.url_for()

Other sample snippets of usage for linking js or css to your template are below.

<script src="{{ url_for('static', filename='jquery.min.js') }}"></script>

<link rel=stylesheet type=text/css href="{{ url_for('static', filename='style.css') }}">

Bash conditionals: how to "and" expressions? (if [ ! -z $VAR && -e $VAR ])

if [ ! -z "$var" ] && [ -e "$var" ]; then
      # something ...
fi

How to do a SUM() inside a case statement in SQL server

If you're using SQL Server 2005 or above, you can use the windowing function SUM() OVER ().

case 
when test1.TotalType = 'Average' then Test2.avgscore
when test1.TotalType = 'PercentOfTot' then (cnt/SUM(test1.qrank) over ())
else cnt
end as displayscore

But it'll be better if you show your full query to get context of what you actually need.

Open a facebook link by native Facebook app on iOS

I know the question is old, but in support of the above answers i wanted to share my working code. Just add these two methods to whatever class.The code checks if facebook app is installed, if not installed the url is opened in a browser.And if any errors occur when trying to find the profileId, the page will be opened in a browser. Just pass the url(example, http://www.facebook.com/AlibabaUS) to openUrl: and it will do all the magic. Hope it helps someone!.

NOTE: UrlUtils was the class that had the code for me, you might have to change it to something else to suite your needs.

+(void) openUrlInBrowser:(NSString *) url
{
    if (url.length > 0) {
        NSURL *linkUrl = [NSURL URLWithString:url];
        [[UIApplication sharedApplication] openURL:linkUrl];
    }
}
+(void) openUrl:(NSString *) urlString
{

    //check if facebook app exists
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"fb://"]]) {

        // Facebook app installed
        NSArray *tokens = [urlString componentsSeparatedByString:@"/"];
        NSString *profileName = [tokens lastObject];

        //call graph api
        NSURL *apiUrl = [NSURL URLWithString:[NSString stringWithFormat:@"https://graph.facebook.com/%@",profileName]];
        NSData *apiResponse = [NSData dataWithContentsOfURL:apiUrl];

        NSError *error = nil;
        NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:apiResponse options:NSJSONReadingMutableContainers error:&error];

        //check for parse error
        if (error == nil) {

            NSString *profileId = [jsonDict objectForKey:@"id"];

            if (profileId.length > 0) {//make sure id key is actually available
                NSURL *fbUrl = [NSURL URLWithString:[NSString stringWithFormat:@"fb://profile/%@",profileId]];
                [[UIApplication sharedApplication] openURL:fbUrl];
            }
            else{
                [UrlUtils openUrlInBrowser:urlString];
            }

        }
        else{//parse error occured
            [UrlUtils openUrlInBrowser:urlString];
        }

    }
    else{//facebook app not installed
        [UrlUtils openUrlInBrowser:urlString];
    }

}

How do I convert a string to a double in Python?

>>> x = "2342.34"
>>> float(x)
2342.3400000000001

There you go. Use float (which behaves like and has the same precision as a C,C++, or Java double).

Select and trigger click event of a radio button in jquery

In my case i had to load images on radio button click, I just uses the regular onclick event and it worked for me.

 <input type="radio" name="colors" value="{{color.id}}" id="{{color.id}}-option" class="color_radion"  onclick="return get_images(this, {{color.id}})">

<script>
  function get_images(obj, color){
    console.log($("input[type='radio'][name='colors']:checked").val());

  }
  </script>

Removing packages installed with go get

You can delete the archive files and executable binaries that go install (or go get) produces for a package with go clean -i importpath.... These normally reside under $GOPATH/pkg and $GOPATH/bin, respectively.

Be sure to include ... on the importpath, since it appears that, if a package includes an executable, go clean -i will only remove that and not archive files for subpackages, like gore/gocode in the example below.

Source code then needs to be removed manually from $GOPATH/src.

go clean has an -n flag for a dry run that prints what will be run without executing it, so you can be certain (see go help clean). It also has a tempting -r flag to recursively clean dependencies, which you probably don't want to actually use since you'll see from a dry run that it will delete lots of standard library archive files!

A complete example, which you could base a script on if you like:

$ go get -u github.com/motemen/gore

$ which gore
/Users/ches/src/go/bin/gore

$ go clean -i -n github.com/motemen/gore...
cd /Users/ches/src/go/src/github.com/motemen/gore
rm -f gore gore.exe gore.test gore.test.exe commands commands.exe commands_test commands_test.exe complete complete.exe complete_test complete_test.exe debug debug.exe helpers_test helpers_test.exe liner liner.exe log log.exe main main.exe node node.exe node_test node_test.exe quickfix quickfix.exe session_test session_test.exe terminal_unix terminal_unix.exe terminal_windows terminal_windows.exe utils utils.exe
rm -f /Users/ches/src/go/bin/gore
cd /Users/ches/src/go/src/github.com/motemen/gore/gocode
rm -f gocode.test gocode.test.exe
rm -f /Users/ches/src/go/pkg/darwin_amd64/github.com/motemen/gore/gocode.a

$ go clean -i github.com/motemen/gore...

$ which gore

$ tree $GOPATH/pkg/darwin_amd64/github.com/motemen/gore
/Users/ches/src/go/pkg/darwin_amd64/github.com/motemen/gore

0 directories, 0 files

# If that empty directory really bugs you...
$ rmdir $GOPATH/pkg/darwin_amd64/github.com/motemen/gore

$ rm -rf $GOPATH/src/github.com/motemen/gore

Note that this information is based on the go tool in Go version 1.5.1.

How to create a WPF Window without a border that can be resized via a grip only?

If you set the AllowsTransparency property on the Window (even without setting any transparency values) the border disappears and you can only resize via the grip.

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Width="640" Height="480" 
    WindowStyle="None"
    AllowsTransparency="True"
    ResizeMode="CanResizeWithGrip">

    <!-- Content -->

</Window>

Result looks like:

how to install gcc on windows 7 machine?

Download mingw-get and simply issue:

mingw-get install gcc.

See the Getting Started page.

LINQ Join with Multiple Conditions in On Clause

This works fine for 2 tables. I have 3 tables and on clause has to link 2 conditions from 3 tables. My code:

from p in _dbContext.Products join pv in _dbContext.ProductVariants on p.ProduktId equals pv.ProduktId join jpr in leftJoinQuery on new { VariantId = pv.Vid, ProductId = p.ProduktId } equals new { VariantId = jpr.Prices.VariantID, ProductId = jpr.Prices.ProduktID } into lj

But its showing error at this point: join pv in _dbContext.ProductVariants on p.ProduktId equals pv.ProduktId

Error: The type of one of the expressions in the join clause is incorrect. Type inference failed in the call to 'GroupJoin'.

Making a POST call instead of GET using urllib2

This may have been answered before: Python URLLib / URLLib2 POST.

Your server is likely performing a 302 redirect from http://myserver/post_service to http://myserver/post_service/. When the 302 redirect is performed, the request changes from POST to GET (see Issue 1401). Try changing url to http://myserver/post_service/.

Loop through columns and add string lengths as new columns

With dplyr and stringr you can use mutate_all:

> df %>% mutate_all(funs(length = str_length(.)))

     col1     col2 col1_length col2_length
1     abc adf qqwe           3           8
2    abcd        d           4           1
3       a        e           1           1
4 abcdefg        f           7           1

How to define a List bean in Spring?

Stacker posed a great answer, I would go one step farther to make it more dynamic and use Spring 3 EL Expression.

<bean id="listBean" class="java.util.ArrayList">
        <constructor-arg>
            <value>#{springDAOBean.getGenericListFoo()}</value>
        </constructor-arg>
</bean>

I was trying to figure out how I could do this with the util:list but couldn't get it work due to conversion errors.

How to implement a SQL like 'LIKE' operator in java?

public static boolean like(String source, String exp) {
        if (source == null || exp == null) {
            return false;
        }

        int sourceLength = source.length();
        int expLength = exp.length();

        if (sourceLength == 0 || expLength == 0) {
            return false;
        }

        boolean fuzzy = false;
        char lastCharOfExp = 0;
        int positionOfSource = 0;

        for (int i = 0; i < expLength; i++) {
            char ch = exp.charAt(i);

            // ????
            boolean escape = false;
            if (lastCharOfExp == '\\') {
                if (ch == '%' || ch == '_') {
                    escape = true;
                    // System.out.println("escape " + ch);
                }
            }

            if (!escape && ch == '%') {
                fuzzy = true;
            } else if (!escape && ch == '_') {
                if (positionOfSource >= sourceLength) {
                    return false;
                }

                positionOfSource++;// <<<----- ???1
            } else if (ch != '\\') {// ????,?????????
                if (positionOfSource >= sourceLength) {// ?????source????
                    return false;
                }

                if (lastCharOfExp == '%') { // ??????%,?????
                    int tp = source.indexOf(ch);
                    // System.out.println("?????=%,?????=" + ch + ",position=" + position + ",tp=" + tp);

                    if (tp == -1) { // ????????,????
                        return false;
                    }

                    if (tp >= positionOfSource) {
                        positionOfSource = tp + 1;// <<<----- ????

                        if (i == expLength - 1 && positionOfSource < sourceLength) { // exp??????????,????source?????????
                            return false;
                        }
                    } else {
                        return false;
                    }
                } else if (source.charAt(positionOfSource) == ch) {// ????????ch??
                    positionOfSource++;
                } else {
                    return false;
                }
            }

            lastCharOfExp = ch;// <<<----- ??
            // System.out.println("?????=" + ch + ",position=" + position);
        }

        // expr???????,???????,??source???????????source???
        if (!fuzzy && positionOfSource < sourceLength) {
            // System.out.println("?????=" + lastChar + ",position=" + position );

            return false;
        }

        return true;// ????true
    }
Assert.assertEquals(true, like("abc_d", "abc\\_d"));
        Assert.assertEquals(true, like("abc%d", "abc\\%%d"));
        Assert.assertEquals(false, like("abcd", "abc\\_d"));

        String source = "1abcd";
        Assert.assertEquals(true, like(source, "_%d"));
        Assert.assertEquals(false, like(source, "%%a"));
        Assert.assertEquals(false, like(source, "1"));
        Assert.assertEquals(true, like(source, "%d"));
        Assert.assertEquals(true, like(source, "%%%%"));
        Assert.assertEquals(true, like(source, "1%_"));
        Assert.assertEquals(false, like(source, "1%_2"));
        Assert.assertEquals(false, like(source, "1abcdef"));
        Assert.assertEquals(true, like(source, "1abcd"));
        Assert.assertEquals(false, like(source, "1abcde"));

        // ????case?????
        Assert.assertEquals(true, like(source, "_%_"));
        Assert.assertEquals(true, like(source, "_%____"));
        Assert.assertEquals(true, like(source, "_____"));// 5?
        Assert.assertEquals(false, like(source, "___"));// 3?
        Assert.assertEquals(false, like(source, "__%____"));// 6?
        Assert.assertEquals(false, like(source, "1"));

        Assert.assertEquals(false, like(source, "a_%b"));
        Assert.assertEquals(true, like(source, "1%"));
        Assert.assertEquals(false, like(source, "d%"));
        Assert.assertEquals(true, like(source, "_%"));
        Assert.assertEquals(true, like(source, "_abc%"));
        Assert.assertEquals(true, like(source, "%d"));
        Assert.assertEquals(true, like(source, "%abc%"));
        Assert.assertEquals(false, like(source, "ab_%"));

        Assert.assertEquals(true, like(source, "1ab__"));
        Assert.assertEquals(true, like(source, "1ab__%"));
        Assert.assertEquals(false, like(source, "1ab___"));
        Assert.assertEquals(true, like(source, "%"));

        Assert.assertEquals(false, like(null, "1ab___"));
        Assert.assertEquals(false, like(source, null));
        Assert.assertEquals(false, like(source, ""));

Get Max value from List<myType>

Simplest is actually just Age.Max(), you don't need any more code.

How to launch html using Chrome at "--allow-file-access-from-files" mode?

You may want to try Web Server for Chrome, which serves web pages from a local folder using HTTP. It's simple to use and would avoid the flag, which, as someone mentioned above, might make your file system vulnerable.

Screenshot of Web Server for Chrome

How do you get the cursor position in a textarea?

Here is code to get line number and column position

function getLineNumber(tArea) {

    return tArea.value.substr(0, tArea.selectionStart).split("\n").length;
}

function getCursorPos() {
    var me = $("textarea[name='documenttext']")[0];
    var el = $(me).get(0);
    var pos = 0;
    if ('selectionStart' in el) {
        pos = el.selectionStart;
    } else if ('selection' in document) {
        el.focus();
        var Sel = document.selection.createRange();
        var SelLength = document.selection.createRange().text.length;
        Sel.moveStart('character', -el.value.length);
        pos = Sel.text.length - SelLength;
    }
    var ret = pos - prevLine(me);
    alert(ret);

    return ret; 
}

function prevLine(me) {
    var lineArr = me.value.substr(0, me.selectionStart).split("\n");

    var numChars = 0;

    for (var i = 0; i < lineArr.length-1; i++) {
        numChars += lineArr[i].length+1;
    }

    return numChars;
}

tArea is the text area DOM element

How do I remove a specific element from a JSONArray?

public static JSONArray RemoveJSONArray( JSONArray jarray,int pos) {

JSONArray Njarray=new JSONArray();
try{
for(int i=0;i<jarray.length();i++){     
    if(i!=pos)
        Njarray.put(jarray.get(i));     
}
}catch (Exception e){e.printStackTrace();}
return Njarray;

}

python list by value not by reference

I would recommend the following solution:

b = []
b[:] = a

This will copy all the elements from a to b. The copy will be value copy, not reference copy.

Understanding the difference between Object.create() and new SomeFunction()

Object creation variants.


Variant 1 : 'new Object()' -> Object constructor without arguments.

var p1 = new Object(); // 'new Object()' create and return empty object -> {}

var p2 = new Object(); // 'new Object()' create and return empty object -> {}

console.log(p1); // empty object -> {}

console.log(p2); // empty object -> {}

// p1 and p2 are pointers to different objects
console.log(p1 === p2); // false

console.log(p1.prototype); // undefined

// empty object which is in fact Object.prototype
console.log(p1.__proto__); // {}

// empty object to which p1.__proto__ points
console.log(Object.prototype); // {}

console.log(p1.__proto__ === Object.prototype); // true

// null, which is in fact Object.prototype.__proto__
console.log(p1.__proto__.__proto__); // null

console.log(Object.prototype.__proto__); // null

enter image description here


Variant 2 : 'new Object(person)' -> Object constructor with argument.

const person = {
    name: 'no name',
    lastName: 'no lastName',
    age: -1
}

// 'new Object(person)' return 'person', which is pointer to the object ->
//  -> { name: 'no name', lastName: 'no lastName', age: -1 }
var p1 = new Object(person);

// 'new Object(person)' return 'person', which is pointer to the object ->
//  -> { name: 'no name', lastName: 'no lastName', age: -1 }
var p2 = new Object(person);

// person, p1 and p2 are pointers to the same object
console.log(p1 === p2); // true
console.log(p1 === person); // true
console.log(p2 === person); // true

p1.name = 'John'; // change 'name' by 'p1'
p2.lastName = 'Doe'; // change 'lastName' by 'p2'
person.age = 25; // change 'age' by 'person'

// when print 'p1', 'p2' and 'person', it's the same result,
// because the object they points is the same
console.log(p1); // { name: 'John', lastName: 'Doe', age: 25 }
console.log(p2); // { name: 'John', lastName: 'Doe', age: 25 }
console.log(person); // { name: 'John', lastName: 'Doe', age: 25 }

enter image description here


Variant 3.1 : 'Object.create(person)'. Use Object.create with simple object 'person'. 'Object.create(person)' will create(and return) new empty object and add property '__proto__' to the same new empty object. This property '__proto__' will point to the object 'person'.

const person = {
        name: 'no name',
        lastName: 'no lastName',
        age: -1,
        getInfo: function getName() {
           return `${this.name} ${this.lastName}, ${this.age}!`;
    }
}

var p1 = Object.create(person);

var p2 = Object.create(person);

// 'p1.__proto__' and 'p2.__proto__' points to
// the same object -> 'person'
// { name: 'no name', lastName: 'no lastName', age: -1, getInfo: [Function: getName] }
console.log(p1.__proto__);
console.log(p2.__proto__);
console.log(p1.__proto__ === p2.__proto__); // true

console.log(person.__proto__); // {}(which is the Object.prototype)

// 'person', 'p1' and 'p2' are different
console.log(p1 === person); // false
console.log(p1 === p2); // false
console.log(p2 === person); // false

// { name: 'no name', lastName: 'no lastName', age: -1, getInfo: [Function: getName] }
console.log(person);

console.log(p1); // empty object - {}

console.log(p2); // empty object - {}

// add properties to object 'p1'
// (properties with the same names like in object 'person')
p1.name = 'John';
p1.lastName = 'Doe';
p1.age = 25;

// add properties to object 'p2'
// (properties with the same names like in object 'person')
p2.name = 'Tom';
p2.lastName = 'Harrison';
p2.age = 38;

// { name: 'no name', lastName: 'no lastName', age: -1, getInfo: [Function: getName] }
console.log(person);

// { name: 'John', lastName: 'Doe', age: 25 }
console.log(p1);

// { name: 'Tom', lastName: 'Harrison', age: 38 }
console.log(p2);

// use by '__proto__'(link from 'p1' to 'person'),
// person's function 'getInfo'
console.log(p1.getInfo()); // John Doe, 25!

// use by '__proto__'(link from 'p2' to 'person'),
// person's function 'getInfo'
console.log(p2.getInfo()); // Tom Harrison, 38!

enter image description here


Variant 3.2 : 'Object.create(Object.prototype)'. Use Object.create with built-in object -> 'Object.prototype'. 'Object.create(Object.prototype)' will create(and return) new empty object and add property '__proto__' to the same new empty object. This property '__proto__' will point to the object 'Object.prototype'.

// 'Object.create(Object.prototype)' :
// 1. create and return empty object -> {}.
// 2. add to 'p1' property '__proto__', which is link to 'Object.prototype'
var p1 = Object.create(Object.prototype);

// 'Object.create(Object.prototype)' :
// 1. create and return empty object -> {}.
// 2. add to 'p2' property '__proto__', which is link to 'Object.prototype'
var p2 = Object.create(Object.prototype);

console.log(p1); // {}

console.log(p2); // {}

console.log(p1 === p2); // false

console.log(p1.prototype); // undefined

console.log(p2.prototype); // undefined

console.log(p1.__proto__ === Object.prototype); // true

console.log(p2.__proto__ === Object.prototype); // true

enter image description here


Variant 4 : 'new SomeFunction()'

// 'this' in constructor-function 'Person'
// represents a new instace,
// that will be created by 'new Person(...)'
// and returned implicitly
function Person(name, lastName, age) {

    this.name = name;
    this.lastName = lastName;
    this.age = age;

    //-----------------------------------------------------------------
    // !--- only for demonstration ---
    // if add function 'getInfo' into
    // constructor-function 'Person',
    // then all instances will have a copy of the function 'getInfo'!
    //
    // this.getInfo: function getInfo() {
    //  return this.name + " " + this.lastName + ", " + this.age + "!";
    // }
    //-----------------------------------------------------------------
}

// 'Person.prototype' is an empty object
// (before add function 'getInfo')
console.log(Person.prototype); // Person {}

// With 'getInfo' added to 'Person.prototype',
// instances by their properties '__proto__',
// will have access to the function 'getInfo'.
// With this approach, instances not need
// a copy of the function 'getInfo' for every instance.
Person.prototype.getInfo = function getInfo() {
    return this.name + " " + this.lastName + ", " + this.age + "!";
}

// after function 'getInfo' is added to 'Person.prototype'
console.log(Person.prototype); // Person { getInfo: [Function: getInfo] }

// create instance 'p1'
var p1 = new Person('John', 'Doe', 25);

// create instance 'p2'
var p2 = new Person('Tom', 'Harrison', 38);

// Person { name: 'John', lastName: 'Doe', age: 25 }
console.log(p1);

// Person { name: 'Tom', lastName: 'Harrison', age: 38 }
console.log(p2);

// 'p1.__proto__' points to 'Person.prototype'
console.log(p1.__proto__); // Person { getInfo: [Function: getInfo] }

// 'p2.__proto__' points to 'Person.prototype'
console.log(p2.__proto__); // Person { getInfo: [Function: getInfo] }

console.log(p1.__proto__ === p2.__proto__); // true

// 'p1' and 'p2' points to different objects(instaces of 'Person')
console.log(p1 === p2); // false

// 'p1' by its property '__proto__' reaches 'Person.prototype.getInfo' 
// and use 'getInfo' with 'p1'-instance's data
console.log(p1.getInfo()); // John Doe, 25!

// 'p2' by its property '__proto__' reaches 'Person.prototype.getInfo' 
// and use 'getInfo' with 'p2'-instance's data
console.log(p2.getInfo()); // Tom Harrison, 38!

enter image description here

Writing unit tests in Python: How do I start?

unittest comes with the standard library, but I would recomend you nosetests.

"nose extends unittest to make testing easier."

I would also recomend you pylint

"analyzes Python source code looking for bugs and signs of poor quality."

<code> vs <pre> vs <samp> for inline and block code snippets

Consider Prism.js: https://prismjs.com/#examples

It makes <pre><code> work and is attractive.

Multiple inputs on one line

Yes, you can.

From cplusplus.com:

Because these functions are operator overloading functions, the usual way in which they are called is:

   strm >> variable;

Where strm is the identifier of a istream object and variable is an object of any type supported as right parameter. It is also possible to call a succession of extraction operations as:

   strm >> variable1 >> variable2 >> variable3; //...

which is the same as performing successive extractions from the same object strm.

Just replace strm with cin.

Convert MFC CString to integer

CString s;
int i;
i = _wtoi(s); // if you use wide charater formats
i = _atoi(s); // otherwise

How to increment a variable on a for loop in jinja template?

Here's my solution:

Put all the counters in a dictionary:

{% set counter = {
    'counter1': 0,
    'counter2': 0,
    'etc': 0,
    } %}

Define a macro to increment them easily:

{% macro increment(dct, key, inc=1)%}
    {% if dct.update({key: dct[key] + inc}) %} {% endif %}
{% endmacro %}

Now, whenever you want to increment the 'counter1' counter, just do:

{{ increment(counter, 'counter1') }}

DataTables: Cannot read property 'length' of undefined

It's even simpler: just use dataSrc:'' option in the ajax defintion so dataTable knows to expect an array instead of an object:

    $('#pos-table2').DataTable({
                  processing: true,
                  serverSide: true,
                  ajax:{url:"pos.json",dataSrc:""}
            }
    );

See ajax options

How to avoid Python/Pandas creating an index in a saved csv?

There are two ways to handle the situation where we do not want the index to be stored in csv file.

  1. As others have stated you can use index=False while saving your
    dataframe to csv file.

    df.to_csv('file_name.csv',index=False)

  2. Or you can save your dataframe as it is with an index, and while reading you just drop the column unnamed 0 containing your previous index.Simple!

    df.to_csv(' file_name.csv ')
    df_new = pd.read_csv('file_name.csv').drop(['unnamed 0'],axis=1)

Logical XOR operator in C++?

The XOR operator cannot be short circuited; i.e. you cannot predict the result of an XOR expression just by evaluating its left hand operand. Thus, there's no reason to provide a ^^ version.

How do I check if a Key is pressed on C++

check if a key is pressed, if yes, then do stuff

Consider 'select()', if this (reportedly Posix) function is available on your os.

'select()' uses 3 sets of bits, which you create using functions provided (see man select, FD_SET, etc). You probably only need create the input bits (for now)


from man page:

'select()' "allow a program to monitor multiple file descriptors, waiting until one or more of the file descriptors become "ready" for some class of I/O operation (e.g., input possible). A file descriptor is considered ready if it is possible to perform a corresponding I/O operation (e.g., read(2) without blocking...)"

When select is invoked:

a) the function looks at each fd identified in the sets, and if that fd state indicates you can do something (perhaps read, perhaps write), select will return and let you go do that ... 'all you got to do' is scan the bits, find the set bit, and take action on the fd associated with that bit.

The 1st set (passed into select) contains active input fd's (typically devices). Probably 1 bit in this set is all you will need. And with only 1 fd (i.e. an input from keyboard), 1 bit, this is all quite simple. With this return from select, you can 'do-stuff' (perhaps, after you have fetched the char).

b) the function also has a timeout, with which you identify how much time to await a change of the fd state. If the fd state does not change, the timeout will cause 'select()' to return with a 0. (i.e. no keyboard input) Your code can do something at this time, too, perhaps an output.

fyi - fd's are typically 0,1,2... Remembe that C uses 0 as STDIN, 1 and STDOUT.


Simple test set up: I open a terminal (separate from my console), and type the tty command in that terminal to find its id. The response is typically something like "/dev/pts/0", or 3, or 17...

Then I get an fd to use in 'select()' by using open:

// flag options are: O_RDONLY, O_WRONLY, or O_RDWR
int inFD = open( "/dev/pts/5", O_RDONLY ); 

It is useful to cout this value.

Here is a snippet to consider (from man select):

  fd_set rfds;
  struct timeval tv;
  int retval;

  /* Watch stdin (fd 0) to see when it has input. */
  FD_ZERO(&rfds);
  FD_SET(0, &rfds);

  /* Wait up to five seconds. */
  tv.tv_sec = 5;
  tv.tv_usec = 0;

  retval = select(1, &rfds, NULL, NULL, &tv);
  /* Don't rely on the value of tv now! */

  if (retval == -1)
      perror("select()");
  else if (retval)
      printf("Data is available now.\n");  // i.e. doStuff()
      /* FD_ISSET(0, &rfds) will be true. */
  else
      printf("No data within five seconds.\n"); // i.e. key not pressed

Browser/HTML Force download of image from src="data:image/jpeg;base64..."

Simply replace image/jpeg with application/octet-stream. The client would not recognise the URL as an inline-able resource, and prompt a download dialog.

A simple JavaScript solution would be:

//var img = reference to image
var url = img.src.replace(/^data:image\/[^;]+/, 'data:application/octet-stream');
window.open(url);
// Or perhaps: location.href = url;
// Or even setting the location of an <iframe> element, 

Another method is to use a blob: URI:

var img = document.images[0];
img.onclick = function() {
    // atob to base64_decode the data-URI
    var image_data = atob(img.src.split(',')[1]);
    // Use typed arrays to convert the binary data to a Blob
    var arraybuffer = new ArrayBuffer(image_data.length);
    var view = new Uint8Array(arraybuffer);
    for (var i=0; i<image_data.length; i++) {
        view[i] = image_data.charCodeAt(i) & 0xff;
    }
    try {
        // This is the recommended method:
        var blob = new Blob([arraybuffer], {type: 'application/octet-stream'});
    } catch (e) {
        // The BlobBuilder API has been deprecated in favour of Blob, but older
        // browsers don't know about the Blob constructor
        // IE10 also supports BlobBuilder, but since the `Blob` constructor
        //  also works, there's no need to add `MSBlobBuilder`.
        var bb = new (window.WebKitBlobBuilder || window.MozBlobBuilder);
        bb.append(arraybuffer);
        var blob = bb.getBlob('application/octet-stream'); // <-- Here's the Blob
    }

    // Use the URL object to create a temporary URL
    var url = (window.webkitURL || window.URL).createObjectURL(blob);
    location.href = url; // <-- Download!
};

Relevant documentation

How to use HTML to print header and footer on every printed page of a document?

I found one solution. The basic idea is to make a table and in thead section place the data of header in tr and by css force to show that tr only in print not in screen then your normal header should be force to show only in screen not in print. 100% working on many pages print. sample code is here

<style> 
    @media screen {
        .only_print{
            display:none;
        }
    }
    @media print {
        .no-print {
            display: none !important;
        }
    }
    TABLE{border-collapse: collapse;}
    TH, TD {border:1px solid grey;}
</style>
<div class="no-print">  <!-- This is header for screen and will not be printed -->
    <div>COMPANY NAME FOR SCREEN</div>
    <div>DESCRIPTION FOR SCREEN</div>
</div>

<table>
    <thead>
        <tr class="only_print"> <!-- This is header for print and will not be shown on screen -->
            <td colspan="100" style="border: 0px;">
                <div>COMPANY NAME FOR PRINT</div>
                <div>DESCRIPTION FOR PRINT</div>
            </td>
        </tr>
        <!-- From here Actual Data of table start -->
        <tr>
            <th>Column 1</th>
            <th>Column 2</th>
            <th>Column 3</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>1-1</td>
            <td>1-2</td>
            <td>1-3</td>
        </tr>
        <tr>
            <td>2-1</td>
            <td>2-2</td>
            <td>2-3</td>
        </tr>
    </tbody>
</table>

Str_replace for multiple items

Like this:

str_replace(array(':', '\\', '/', '*'), ' ', $string);

Or, in modern PHP (anything from 5.4 onwards), the slighty less wordy:

str_replace([':', '\\', '/', '*'], ' ', $string);

How can I add 1 day to current date?

currentDay = '2019-12-06';
currentDay = new Date(currentDay).add(Date.DAY, +1).format('Y-m-d');

Found 'OR 1=1/* sql injection in my newsletter database

'OR 1=1 is an attempt to make a query succeed no matter what
The /* is an attempt to start a multiline comment so the rest of the query is ignored.

An example would be

SELECT userid 
FROM users 
WHERE username = ''OR 1=1/*' 
    AND password = ''
    AND domain = ''

As you can see if you were to populate the username field without escaping the ' no matter what credentials the user passes in the query would return all userids in the system likely granting access to the attacker (possibly admin access if admin is your first user). You will also notice the remainder of the query would be commented out because of the /* including the real '.

The fact that you can see the value in your database means that it was escaped and that particular attack did not succeed. However, you should investigate if any other attempts were made.

ssh : Permission denied (publickey,gssapi-with-mic)

fixed by setting GSSAPIAuthentication to no in /etc/ssh/sshd_config

Plot multiple lines (data series) each with unique color in R

In case the x-axis is a factor / discrete variable, and one would like to keep the order of the variable (different values corresponding to different groups) to visualise the group effect. The following code wold do:

library(ggplot2)
set.seed(45)

# dummy data
df <- data.frame(x=rep(letters[1:5], 9), val=sample(1:100, 45), 
                   variable=rep(paste0("category", 1:9), each=5))

# This ensures that x-axis (which is a factor variable)  will be ordered appropriately
df$x <- ordered(df$x, levels=letters[1:5])

ggplot(data = df, aes(x=x, y=val, group=variable, color=variable)) + geom_line() + geom_point() + ggtitle("Multiple lines with unique color")

enter image description here Also note that: adding group=variable remove the warning information: "geom_path: Each group consists of only one observation. Do you need to adjust the group aesthetic?"

SSL error SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

Add

$mail->SMTPOptions = array(
'ssl' => array(
    'verify_peer' => false,
    'verify_peer_name' => false,
    'allow_self_signed' => true
));

before

mail->send()

and replace

require "mailer/class.phpmailer.php";

with

require "mailer/PHPMailerAutoload.php";

How to ignore a particular directory or file for tslint?

linterOptions is currently only handled by the CLI. If you're not using CLI then depending on the code base you're using you'll need to set the ignore somewhere else. webpack, tsconfig, etc

Log4j: How to configure simplest possible file logging?

Here is a log4j.properties file that I've used with great success.

logDir=/var/log/myapp

log4j.rootLogger=INFO, stdout
#log4j.rootLogger=DEBUG, stdout

log4j.appender.stdout=org.apache.log4j.DailyRollingFileAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{MM/dd/yyyy hh:mm:ss a}|%-5p|%-30c{1}| %m%n
log4j.appender.stdout.DatePattern='.'yyyy-MM-dd
log4j.appender.stdout.File=${logDir}/myapp.log
log4j.appender.stdout.append=true

The DailyRollingFileAppender will create new files each day with file names that look like this:

myapp.log.2017-01-27
myapp.log.2017-01-28
myapp.log.2017-01-29
myapp.log  <-- today's log

Each entry in the log file will will have this format:

01/30/2017 12:59:47 AM|INFO |Component1   | calling foobar(): userId=123, returning totalSent=1
01/30/2017 12:59:47 AM|INFO |Component2   | count=1 > 0, calling fooBar()

Set the location of the above file by using -Dlog4j.configuration, as mentioned in this posting:

java -Dlog4j.configuration=file:/home/myapp/config/log4j.properties com.foobar.myapp

In your Java code, be sure to set the name of each software component when you instantiate your logger object. I also like to log to both the log file and standard output, so I wrote this small function.

private static final Logger LOGGER = Logger.getLogger("Component1");

public static void log(org.apache.log4j.Logger logger, String message) {

    logger.info(message);
    System.out.printf("%s\n", message);
}

public static String stackTraceToString(Exception ex) {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    ex.printStackTrace(pw);
    return sw.toString();
}

And then call it like so:

LOGGER.info(String.format("Exception occurred: %s", stackTraceToString(ex)));

How can I get javascript to read from a .json file?

Actually, you are looking for the AJAX CALL, in which you will replace the URL parameter value with the link of the JSON file to get the JSON values.

$.ajax({
    url: "File.json", //the path of the file is replaced by File.json
    dataType: "json",
    success: function (response) {
        console.log(response); //it will return the json array
    }
});