Programs & Examples On #Pyc

Python source code is automatically compiled into Python byte code by the CPython interpreter. Compiled code is usually stored in .pyc or .pyo files, and is regenerated when the source is updated, or when otherwise necessary.

What do the python file extensions, .pyc .pyd .pyo stand for?

  1. .py: This is normally the input source code that you've written.
  2. .pyc: This is the compiled bytecode. If you import a module, python will build a *.pyc file that contains the bytecode to make importing it again later easier (and faster).
  3. .pyo: This was a file format used before Python 3.5 for *.pyc files that were created with optimizations (-O) flag. (see the note below)
  4. .pyd: This is basically a windows dll file. http://docs.python.org/faq/windows.html#is-a-pyd-file-the-same-as-a-dll

Also for some further discussion on .pyc vs .pyo, take a look at: http://www.network-theory.co.uk/docs/pytut/CompiledPythonfiles.html (I've copied the important part below)

  • When the Python interpreter is invoked with the -O flag, optimized code is generated and stored in ‘.pyo’ files. The optimizer currently doesn't help much; it only removes assert statements. When -O is used, all bytecode is optimized; .pyc files are ignored and .py files are compiled to optimized bytecode.
  • Passing two -O flags to the Python interpreter (-OO) will cause the bytecode compiler to perform optimizations that could in some rare cases result in malfunctioning programs. Currently only __doc__ strings are removed from the bytecode, resulting in more compact ‘.pyo’ files. Since some programs may rely on having these available, you should only use this option if you know what you're doing.
  • A program doesn't run any faster when it is read from a ‘.pyc’ or ‘.pyo’ file than when it is read from a ‘.py’ file; the only thing that's faster about ‘.pyc’ or ‘.pyo’ files is the speed with which they are loaded.
  • When a script is run by giving its name on the command line, the bytecode for the script is never written to a ‘.pyc’ or ‘.pyo’ file. Thus, the startup time of a script may be reduced by moving most of its code to a module and having a small bootstrap script that imports that module. It is also possible to name a ‘.pyc’ or ‘.pyo’ file directly on the command line.

Note:

On 2015-09-15 the Python 3.5 release implemented PEP-488 and eliminated .pyo files. This means that .pyc files represent both unoptimized and optimized bytecode.

Is it possible to decompile a compiled .pyc file into a .py file?

Install using pip install pycompyle6

pycompyle6 filename.pyc

If Python is interpreted, what are .pyc files?

Machines don't understand English or any other languages, they understand only byte code, which they have to be compiled (e.g., C/C++, Java) or interpreted (e.g., Ruby, Python), the .pyc is a cached version of the byte code. https://www.geeksforgeeks.org/difference-between-compiled-and-interpreted-language/ Here is a quick read on what is the difference between compiled language vs interpreted language, TLDR is interpreted language does not require you to compile all the code before run time and thus most of the time they are not strict on typing etc.

JavaScript open in a new window, not tab

I had this same question but found a relatively simple solution to it.

In JavaScript I was checking for window.opener !=null; to determine if the window was a pop up. If you're using some similar detection code to determine if the window you're site is being rendered in is a pop up you can easily "turn it off" when you want to open a "new" window using the new windows JavaScript.

Just put this at the top of your page you want to always be a "new" window.

<script type="text/javascript">
    window.opener=null;
</script>

I use this on the log in page of my site so users don't get pop up behavior if they use a pop up window to navigate to my site.

You could even create a simple redirect page that does this and then moves to the URL you gave it. Something like,

JavaScript on parent page:

window.open("MyRedirect.html?URL="+URL, "_blank");

And then by using a little javascript from here you can get the URL and redirect to it.

JavaScript on Redirect Page:

 <script type="text/javascript">
        window.opener=null;

    function getSearchParameters() {
          var prmstr = window.location.search.substr(1);
          return prmstr != null && prmstr != "" ? transformToAssocArray(prmstr) : {};
    }

    function transformToAssocArray( prmstr ) {
        var params = {};
        var prmarr = prmstr.split("&");
        for ( var i = 0; i < prmarr.length; i++) {
            var tmparr = prmarr[i].split("=");
            params[tmparr[0]] = tmparr[1];
        }
        return params;
    }

    var params = getSearchParameters();
    window.location = params.URL;
    </script>

How to Insert Double or Single Quotes

Assuming your data is in column A, add a formula to column B

="'" & A1 & "'" 

and copy the formula down. If you now save to CSV, you should get the quoted values. If you need to keep it in Excel format, copy column B then paste value to get rid of the formula.

$.focus() not working

Found a solution elsewhere on the net...

$('#id').focus();

did not work.

$('#id').get(0).focus();

did work.

What's faster, SELECT DISTINCT or GROUP BY in MySQL?

They are essentially equivalent to each other (in fact this is how some databases implement DISTINCT under the hood).

If one of them is faster, it's going to be DISTINCT. This is because, although the two are the same, a query optimizer would have to catch the fact that your GROUP BY is not taking advantage of any group members, just their keys. DISTINCT makes this explicit, so you can get away with a slightly dumber optimizer.

When in doubt, test!

get Context in non-Activity class

If your class is non-activity class, and creating an instance of it from the activiy, you can pass an instance of context via constructor of the later as follows:

class YourNonActivityClass{

// variable to hold context
private Context context;

//save the context recievied via constructor in a local variable

public YourNonActivityClass(Context context){
    this.context=context;
}

}

You can create instance of this class from the activity as follows:

new YourNonActivityClass(this);

Android: how to convert whole ImageView to Bitmap?

Just thinking out loud here (with admittedly little expertise working with graphics in Java) maybe something like this would work?:

ImageView iv = (ImageView)findViewById(R.id.imageview);
Bitmap bitmap = Bitmap.createBitmap(iv.getWidth(), iv.getHeight(), Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
iv.draw(canvas);

Out of curiosity, what are you trying to accomplish? There may be a better way to achieve your goal than what you have in mind.

ASP.Net MVC: How to display a byte array image from model

This worked for me

<img src="data:image;base64,@System.Convert.ToBase64String(Model.CategoryPicture.Content)" width="80" height="80"/>     

Fastest JavaScript summation

What about summing both extremities? It would cut time in half. Like so:

1, 2, 3, 4, 5, 6, 7, 8; sum = 0

2, 3, 4, 5, 6, 7; sum = 10

3, 4, 5, 6; sum = 19

4, 5; sum = 28

sum = 37

One algorithm could be:

function sum_array(arr){
    let sum = 0,
        length = arr.length,
        half = Math.floor(length/2)

    for (i = 0; i < half; i++) {
        sum += arr[i] + arr[length - 1 - i]
    }
    if (length%2){
        sum += arr[half]
    }
    return sum
}

It performs faster when I test it on the browser with performance.now(). I think this is a better way. What do you guys think?

Best approach to real time http streaming to HTML5 video client

One way to live-stream a RTSP-based webcam to a HTML5 client (involves re-encoding, so expect quality loss and needs some CPU-power):

  • Set up an icecast server (could be on the same machine you web server is on or on the machine that receives the RTSP-stream from the cam)
  • On the machine receiving the stream from the camera, don't use FFMPEG but gstreamer. It is able to receive and decode the RTSP-stream, re-encode it and stream it to the icecast server. Example pipeline (only video, no audio):

    gst-launch-1.0 rtspsrc location=rtsp://192.168.1.234:554 user-id=admin user-pw=123456 ! rtph264depay ! avdec_h264 ! vp8enc threads=2 deadline=10000 ! webmmux streamable=true ! shout2send password=pass ip=<IP_OF_ICECAST_SERVER> port=12000 mount=cam.webm
    

=> You can then use the <video> tag with the URL of the icecast-stream (http://127.0.0.1:12000/cam.webm) and it will work in every browser and device that supports webm

Transfer data from one HTML file to another

Assuming you are talking about this js in browser environment (unlike others like nodejs), Unfortunately I think what you are trying to do isn't possible simply because this is not the way it is supposed to work.

Html pages are delivered to the browser via HTTP Protocol, which is a 'stateless' protocol. If you still needed to pass values in between pages, there could be 3 approaches:

  1. Session Cookies
  2. HTML5 LocalStorage
  3. POST the variable in the url and retrieve them in next.html via window object

Datagrid binding in WPF

PLEASE do not use object as a class name:

public class MyObject //better to choose an appropriate name
{
    string id;
    DateTime date;
    public string ID
    {
       get { return id; }
       set { id = value; }
    }
    public DateTime Date
    {
       get { return date; }
       set { date = value; }
    }
}

You should implement INotifyPropertyChanged for this class and of course call it on the Property setter. Otherwise changes are not reflected in your ui.

Your Viewmodel class/ dialogbox class should have a Property of your MyObject list. ObservableCollection<MyObject> is the way to go:

public ObservableCollection<MyObject> MyList
{
     get...
     set...
}

In your xaml you should set the Itemssource to your collection of MyObject. (the Datacontext have to be your dialogbox class!)

<DataGrid ItemsSource="{Binding Source=MyList}"  AutoGenerateColumns="False">
   <DataGrid.Columns>                
     <DataGridTextColumn Header="ID" Binding="{Binding ID}"/>
     <DataGridTextColumn Header="Date" Binding="{Binding Date}"/>
   </DataGrid.Columns>
</DataGrid>

How do I collapse a table row in Bootstrap?

You are using collapse on the div inside of your table row (tr). So when you collapse the div, the row is still there. You need to change it to where your id and class are on the tr instead of the div.

Change this:

<tr><td><div class="collapse out" id="collapseme">Should be collapsed</div></td></tr>

to this:

<tr class="collapse out" id="collapseme"><td><div>Should be collapsed</div></td></tr>

JSFiddle: http://jsfiddle.net/KnuU6/21/

EDIT: If you are unable to upgrade to 3.0.0, I found a JQuery workaround in 2.3.2:

Remove your data-toggle and data-target and add this JQuery to your button.

$(".btn").click(function() {
    if($("#collapseme").hasClass("out")) {
        $("#collapseme").addClass("in");
        $("#collapseme").removeClass("out");
    } else {
        $("#collapseme").addClass("out");
        $("#collapseme").removeClass("in");
    }
});

JSFiddle: http://jsfiddle.net/KnuU6/25/

HTML text-overflow ellipsis detection

This sample show tooltip on cell table with text truncated. Is dynamic based on table width:

$.expr[':'].truncated = function (obj) {
    var element = $(obj);

    return (element[0].scrollHeight > (element.innerHeight() + 1)) || (element[0].scrollWidth > (element.innerWidth() + 1));
};

$(document).ready(function () {
    $("td").mouseenter(function () {
        var cella = $(this);
        var isTruncated = cella.filter(":truncated").length > 0;
        if (isTruncated) 
            cella.attr("title", cella.text());
        else 
            cella.attr("title", null);
    });
});

Demo: https://jsfiddle.net/t4qs3tqs/

It works on all version of jQuery

How to use opencv in using Gradle?

The following permissions and features are necessary in the AndroidManifest.xml file without which you will get the following dialog box

"It seems that your device does not support camera (or it is locked). Application will be closed"

  <uses-permission android:name="android.permission.CAMERA"/>

    <uses-feature android:name="android.hardware.camera" android:required="false"/>
    <uses-feature android:name="android.hardware.camera.autofocus" android:required="false"/>
    <uses-feature android:name="android.hardware.camera.front" android:required="false"/>
    <uses-feature android:name="android.hardware.camera.front.autofocus" android:required="false"/>

Select dropdown with fixed width cutting off content in IE

A workaround if you don't care about the strange view after an option is selected (i.e. Select to jump to a new page):

<!-- Limit width of the wrapping div instead of the select and use 'overflow: hidden' to hide the right part of it. -->
<div style='width: 145px; overflow: hidden; border-right: 1px solid #aaa;'>
  <select onchange='jump();'>
    <!-- '&#9660;(?)' produces a fake dropdown indicator -->
    <option value=''>Jump to ... &#9660;</option>
    <option value='1'>http://stackoverflow.com/questions/682764/select-dropdown-with-fixed-width-cutting-off-content-in-ie</option>
    ...
  </select>
</div>

This page didn't load Google Maps correctly. See the JavaScript console for technical details

There are 2 possibilities for this problem :

  1. you didn't enter the API KEY for map browser
  2. you didn't enabling the API Library especially for this Google Maps JavaScript API

just check on your Google developer console for that 2 items

How do I enable logging for Spring Security?

Spring security logging for webflux reactive apps is now available starting with version 5.4.0-M2 (as mentionned by @bzhu in comment How do I enable logging for Spring Security?)

Until this gets into a GA release, here is how to get this milestone release in gradle

repositories {
    mavenCentral()
    if (!version.endsWith('RELEASE')) {
        maven { url "https://repo.spring.io/milestone" }
    }
}

// Force earlier milestone release to get securing logging preview
// https://docs.spring.io/spring-security/site/docs/current/reference/html5/#getting-gradle-boot
// https://github.com/spring-projects/spring-security/pull/8504
// https://github.com/spring-projects/spring-security/releases/tag/5.4.0-M2
ext['spring-security.version']='5.4.0-M2'
dependencyManagement {
    imports {
        mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
    }

}

Typescript Type 'string' is not assignable to type

All the above answers are valid, however, there are some cases that the String Literal Type is part of another complex type. Consider the following example:

  // in foo.ts
  export type ToolbarTheme = {
    size: 'large' | 'small',
  };

  // in bar.ts
  import { ToolbarTheme } from './foo.ts';
  function useToolbarTheme(theme: ToolbarTheme) {/* ... */}

  // Here you will get the following error: 
  // Type 'string' is not assignable to type '"small" | "large"'.ts(2322)
  ['large', 'small'].forEach(size => (
    useToolbarTheme({ size })
  ));

You have multiple solutions to fix this. Each solution is valid and has its own use cases.

1) The first solution is to define a type for the size and export it from the foo.ts. This is good if when you need to work with the size parameter by its own. For example, you have a function that accepts or returns a parameter of type size and you want to type it.

  // in foo.ts
  export type ToolbarThemeSize = 'large' | 'small';
  export type ToolbarTheme = {
    size: ToolbarThemeSize
  };

  // in bar.ts
  import { ToolbarTheme, ToolbarThemeSize } from './foo.ts';
  function useToolbarTheme(theme: ToolbarTheme) {/* ... */}
  function getToolbarSize(): ToolbarThemeSize  {/* ... */}

  ['large', 'small'].forEach(size => (
    useToolbarTheme({ size: size as ToolbarThemeSize })
  ));

2) The second option is to just cast it to the type ToolbarTheme. In this case, you don't need to expose the internal of ToolbarTheme if you don't need.

  // in foo.ts
  export type ToolbarTheme = {
    size: 'large' | 'small'
  };

  // in bar.ts
  import { ToolbarTheme } from './foo.ts';
  function useToolbarTheme(theme: ToolbarTheme) {/* ... */}

  ['large', 'small'].forEach(size => (
    useToolbarTheme({ size } as ToolbarTheme)
  ));

Cannot start MongoDB as a service

Well, in my case, I was running low disk space on my drive where I have my MongoDB data files. I checked MongoDB logs file which stated the following

2015-11-11T21:53:54.717+0500 E JOURNAL [initandlisten] Insufficient free space for journal files 2015-11-11T21:53:54.717+0500 I JOURNAL [initandlisten] Please make at least 3379MB available in C:\wamp\bin\mongodb\data\db\journal or use --smallfiles

All I had to do is clean up some space and fire up the service again.. Worked for me. So All you have to is check your logs file and deal with the problem accordingly.

How to get the screen width and height in iOS?

CGFloat width = [[UIScreen mainScreen] bounds].size.width; CGFloat height = [[UIScreen mainScreen]bounds ].size.height;

Printing the value of a variable in SQL Developer

DECLARE

  CTABLE USER_OBJECTS.OBJECT_NAME%TYPE;
  CCOLUMN ALL_TAB_COLS.COLUMN_NAME%TYPE;
  V_ALL_COLS VARCHAR2(5000);

  CURSOR CURSOR_TABLE
    IS
    SELECT OBJECT_NAME 
    FROM USER_OBJECTS 
    WHERE OBJECT_TYPE='TABLE'
    AND OBJECT_NAME LIKE 'STG%';

  CURSOR CURSOR_COLUMNS (V_TABLE_NAME IN VARCHAR2)
    IS
    SELECT COLUMN_NAME
    FROM ALL_TAB_COLS
    WHERE TABLE_NAME = V_TABLE_NAME;

BEGIN

  OPEN CURSOR_TABLE;
  LOOP
    FETCH CURSOR_TABLE INTO CTABLE;

    OPEN CURSOR_COLUMNS (CTABLE);
    V_ALL_COLS := NULL;
    LOOP

      FETCH CURSOR_COLUMNS INTO CCOLUMN;
      V_ALL_COLS := V_ALL_COLS || CCOLUMN;
      IF CURSOR_COLUMNS%FOUND THEN
        V_ALL_COLS := V_ALL_COLS || ', ';
      ELSE
        EXIT;
      END IF;
    END LOOP;
   close CURSOR_COLUMNS ;
    DBMS_OUTPUT.PUT_LINE(V_ALL_COLS);
    EXIT WHEN CURSOR_TABLE%NOTFOUND;
  END LOOP;`enter code here`
  CLOSE CURSOR_TABLE;

END;

I have added Close of second cursor. It working and getting output as well...

Local Storage vs Cookies

It is also worth mentioning that localStorage cannot be used when users browse in "private" mode in some versions of mobile Safari.

Quoted from MDN (https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage):

Note: Starting with iOS 5.1, Safari Mobile stores localStorage data in the cache folder, which is subject to occasional clean up, at the behest of the OS, typically if space is short. Safari Mobile's Private Browsing mode also prevents writing to localStorage entirely.

What's the difference between .so, .la and .a library files?

.so files are dynamic libraries. The suffix stands for "shared object", because all the applications that are linked with the library use the same file, rather than making a copy in the resulting executable.

.a files are static libraries. The suffix stands for "archive", because they're actually just an archive (made with the ar command -- a predecessor of tar that's now just used for making libraries) of the original .o object files.

.la files are text files used by the GNU "libtools" package to describe the files that make up the corresponding library. You can find more information about them in this question: What are libtool's .la file for?

Static and dynamic libraries each have pros and cons.

Static pro: The user always uses the version of the library that you've tested with your application, so there shouldn't be any surprising compatibility problems.

Static con: If a problem is fixed in a library, you need to redistribute your application to take advantage of it. However, unless it's a library that users are likely to update on their own, you'd might need to do this anyway.

Dynamic pro: Your process's memory footprint is smaller, because the memory used for the library is amortized among all the processes using the library.

Dynamic pro: Libraries can be loaded on demand at run time; this is good for plugins, so you don't have to choose the plugins to be used when compiling and installing the software. New plugins can be added on the fly.

Dynamic con: The library might not exist on the system where someone is trying to install the application, or they might have a version that's not compatible with the application. To mitigate this, the application package might need to include a copy of the library, so it can install it if necessary. This is also often mitigated by package managers, which can download and install any necessary dependencies.

Dynamic con: Link-Time Optimization is generally not possible, so there could possibly be efficiency implications in high-performance applications. See the Wikipedia discussion of WPO and LTO.

Dynamic libraries are especially useful for system libraries, like libc. These libraries often need to include code that's dependent on the specific OS and version, because kernel interfaces have changed. If you link a program with a static system library, it will only run on the version of the OS that this library version was written for. But if you use a dynamic library, it will automatically pick up the library that's installed on the system you run on.

How to delete multiple pandas (python) dataframes from memory to save RAM?

In python automatic garbage collection deallocates the variable (pandas DataFrame are also just another object in terms of python). There are different garbage collection strategies that can be tweaked (requires significant learning).

You can manually trigger the garbage collection using

import gc
gc.collect()

But frequent calls to garbage collection is discouraged as it is a costly operation and may affect performance.

Reference

Remove spaces from a string in VB.NET

To trim a string down so it does not contain two or more spaces in a row. Every instance of 2 or more space will be trimmed down to 1 space. A simple solution:

While ImageText1.Contains("  ")                     '2 spaces.
    ImageText1 = ImageText1.Replace("  ", " ")      'Replace with 1 space.
End While

How do I detect a click outside an element?

this works fine for me. i am not an expert.

$(document).click(function(event) {
  var $target = $(event.target);
  if(!$target.closest('#hamburger, a').length &&
  $('#hamburger, a').is(":visible")) {
    $('nav').slideToggle();
  }
});

How to reverse an std::string?

I'm not sure what you mean by a string that contains binary numbers. But for reversing a string (or any STL-compatible container), you can use std::reverse(). std::reverse() operates in place, so you may want to make a copy of the string first:

#include <algorithm>
#include <iostream>
#include <string>

int main()
{
    std::string foo("foo");
    std::string copy(foo);
    std::cout << foo << '\n' << copy << '\n';

    std::reverse(copy.begin(), copy.end());
    std::cout << foo << '\n' << copy << '\n';
}

Extract the first (or last) n characters of a string

Make it simple and use R basic functions:

# To get the LEFT part:
> substr(a, 1, 4)
[1] "left"
> 
# To get the MIDDLE part:
> substr(a, 3, 7)
[1] "ftrig"
> 
# To get the RIGHT part:
> substr(a, 5, 10)
[1] "right"

The substr() function tells you where start and stop substr(x, start, stop)

How to Validate a DateTime in C#?

private void btnEnter_Click(object sender, EventArgs e)
{
    maskedTextBox1.Mask = "00/00/0000";
    maskedTextBox1.ValidatingType = typeof(System.DateTime);
    //if (!IsValidDOB(maskedTextBox1.Text)) 
    if (!ValidateBirthday(maskedTextBox1.Text))
        MessageBox.Show(" Not Valid");
    else
        MessageBox.Show("Valid");
}
// check date format dd/mm/yyyy. but not if year < 1 or > 2013.
public static bool IsValidDOB(string dob)
{ 
    DateTime temp;
    if (DateTime.TryParse(dob, out temp))
        return (true);
    else 
        return (false);
}
// checks date format dd/mm/yyyy and year > 1900!.
protected bool ValidateBirthday(String date)
{
    DateTime Temp;
    if (DateTime.TryParse(date, out Temp) == true &&
        Temp.Year > 1900 &&
       // Temp.Hour == 0 && Temp.Minute == 0 &&
        //Temp.Second == 0 && Temp.Millisecond == 0 &&
        Temp > DateTime.MinValue)
        return (true);
    else
        return (false);
}

How to create a signed APK file using Cordova command line interface?

For Windows, I've created a build.cmd file:

(replace the keystore path and alias)

For Cordova:

@echo off 
set /P spassw="Store Password: " && set /P kpassw="Key Password: " && cordova build android --release -- --keystore=../../local/my.keystore --storePassword=%spassw% --alias=tmpalias --password=%kpassw%

And for Ionic:

@echo off 
set /P spassw="Store Password: " && set /P kpassw="Key Password: " && ionic build --prod && cordova build android --release -- --keystore=../../local/my.keystore --storePassword=%spassw% --alias=tmpalias --password=%kpassw%

Save it in the ptoject's directory, you can double click or open it with cmd.

Why can't Python import Image from PIL?

If you use Anaconda, you may try:

conda install Pillow

Example

Set a variable if undefined in JavaScript

If you're a FP (functional programming) fan, Ramda has a neat helper function for this called defaultTo :

usage:

const result = defaultTo(30)(value)

It's more useful when dealing with undefined boolean values:

const result2 = defaultTo(false)(dashboard.someValue)

CSS container div not getting height

Try inserting this clearing div before the last </div>

<div style="clear: both; line-height: 0;">&nbsp;</div>

Text Editor For Linux (Besides Vi)?

When I searched for TextMate alternative for Linux, I ended up using Geany. It's not as powerfull, but still nice to work with. Great replacement for Kate.

Pass request headers in a jQuery AJAX GET call

Use beforeSend:

$.ajax({
         url: "http://localhost/PlatformPortal/Buyers/Account/SignIn",
         data: { signature: authHeader },
         type: "GET",
         beforeSend: function(xhr){xhr.setRequestHeader('X-Test-Header', 'test-value');},
         success: function() { alert('Success!' + authHeader); }
      });

http://api.jquery.com/jQuery.ajax/

http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader-method

ExpressJS - throw er Unhandled error event

Actually Ctrl+C keys not releasing port used by node process. So there is this error. The resolution to the issue was using following code snippet in server.js:

process.on('SIGINT', function() {
  console.log( "\nGracefully shutting down from SIGINT (Ctrl-C)" );
  // some other closing procedures go here
  process.exit(1);
});

This worked for me.

You can also check for other solutions mentioned at Graceful shutdown in NodeJS

SSIS expression: convert date to string

Something simpler than what @Milen proposed but it gives YYYY-MM-DD instead of the DD-MM-YYYY you wanted :

SUBSTRING((DT_STR,30, 1252) GETDATE(), 1, 10)

Expression builder screen:

enter image description here

JavaScript: Object Rename Key

This is a small modification that I made to the function of pomber; To be able to take an Array of Objects instead of an object alone and also you can activate index. also the "Keys" can be assigned by an array

function renameKeys(arrayObject, newKeys, index = false) {
    let newArray = [];
    arrayObject.forEach((obj,item)=>{
        const keyValues = Object.keys(obj).map((key,i) => {
            return {[newKeys[i] || key]:obj[key]}
        });
        let id = (index) ? {'ID':item} : {}; 
        newArray.push(Object.assign(id, ...keyValues));
    });
    return newArray;
}

test

const obj = [{ a: "1", b: "2" }, { a: "5", b: "4" } ,{ a: "3", b: "0" }];
const newKeys = ["A","C"];
const renamedObj = renameKeys(obj, newKeys);
console.log(renamedObj);

password for postgres

What's the default superuser username/password for postgres after a new install?:

CAUTION The answer about changing the UNIX password for "postgres" through "$ sudo passwd postgres" is not preferred, and can even be DANGEROUS!

This is why: By default, the UNIX account "postgres" is locked, which means it cannot be logged in using a password. If you use "sudo passwd postgres", the account is immediately unlocked. Worse, if you set the password to something weak, like "postgres", then you are exposed to a great security danger. For example, there are a number of bots out there trying the username/password combo "postgres/postgres" to log into your UNIX system.

What you should do is follow Chris James's answer:

sudo -u postgres psql postgres

# \password postgres

Enter new password: 

To explain it a little bit...

Create a Date with a set timezone without using a string representation

This code will return your Date object formatted with the browser timezone.

Date.prototype.timezone = function () {
    this.setHours(this.getHours() + (new Date().getTimezoneOffset() / 60));
    return this;
}

Edit:

To avoid to pollute the Date API, the above function can be transformed into a utility function. The function takes a Date object, and returns a mutated Date object.

function setTimeZone(date) {
    date.setHours(date.getHours() + (new Date().getTimezoneOffset() / 60));
    return date;
}

How do I release memory used by a pandas dataframe?

del df will not be deleted if there are any reference to the df at the time of deletion. So you need to to delete all the references to it with del df to release the memory.

So all the instances bound to df should be deleted to trigger garbage collection.

Use objgragh to check which is holding onto the objects.

How do I move an existing Git submodule within a Git repository?

In my case, I wanted to move a submodule from one directory into a subdirectory, e.g. "AFNetworking" -> "ext/AFNetworking". These are the steps I followed:

  1. Edit .gitmodules changing submodule name and path to be "ext/AFNetworking"
  2. Move submodule's git directory from ".git/modules/AFNetworking" to ".git/modules/ext/AFNetworking"
  3. Move library from "AFNetworking" to "ext/AFNetworking"
  4. Edit ".git/modules/ext/AFNetworking/config" and fix the [core] worktree line. Mine changed from ../../../AFNetworking to ../../../../ext/AFNetworking
  5. Edit "ext/AFNetworking/.git" and fix gitdir. Mine changed from ../.git/modules/AFNetworking to ../../git/modules/ext/AFNetworking
  6. git add .gitmodules
  7. git rm --cached AFNetworking
  8. git submodule add -f <url> ext/AFNetworking

Finally, I saw in the git status:

matt$ git status
# On branch ios-master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#   modified:   .gitmodules
#   renamed:    AFNetworking -> ext/AFNetworking

Et voila. The above example doesn't change the directory depth, which makes a big difference to the complexity of the task, and doesn't change the name of the submodule (which may not really be necessary, but I did it to be consistent with what would happen if I added a new module at that path.)

Where is SQLite database stored on disk?

A SQLite database is a regular file. It is created in your script current directory.

Set textbox to readonly and background color to grey in jquery

there are 2 solutions:

visit this jsfiddle

in your css you can add this:
     .input-disabled{background-color:#EBEBE4;border:1px solid #ABADB3;padding:2px 1px;}

in your js do something like this:
     $('#test').attr('readonly', true);
     $('#test').addClass('input-disabled');

Hope this help.

Another way is using hidden input field as mentioned by some of the comments. However bear in mind that, in the backend code, you need to make sure you validate this newly hidden input at correct scenario. Hence I'm not recommend this way as it will create more bugs if its not handle properly.

How do I auto size columns through the Excel interop objects?

Have a look at this article, it's not an exact match to your problem, but suits it:

SSL Proxy/Charles and Android trouble

The top rated answers are working perfect (a bit old but still working), but I just want to mention that since Android N we all can configure your apps in order to have diff trust SSL certificates (for release , debug only and so on), including Charles SSL Proxy certificate (if you download the Charles certificate and put .pem file in your raw folder). More info can be found here: https://developer.android.com/training/articles/security-config.html

Also the official Charles documentation can be useful to setup this : https://www.charlesproxy.com/documentation/using-charles/ssl-certificates/

Hope this will help to setup Charles inside your app project not on every single Android device.

How can I autoformat/indent C code in vim?

Maybe you can try the followings $indent -kr -i8 *.c

Hope it's useful for you!

Get free disk space

using System;
using System.IO;

class Test
{
    public static void Main()
    {
        DriveInfo[] allDrives = DriveInfo.GetDrives();

        foreach (DriveInfo d in allDrives)
        {
            Console.WriteLine("Drive {0}", d.Name);
            Console.WriteLine("  Drive type: {0}", d.DriveType);
            if (d.IsReady == true)
            {
                Console.WriteLine("  Volume label: {0}", d.VolumeLabel);
                Console.WriteLine("  File system: {0}", d.DriveFormat);
                Console.WriteLine(
                    "  Available space to current user:{0, 15} bytes", 
                    d.AvailableFreeSpace);

                Console.WriteLine(
                    "  Total available space:          {0, 15} bytes",
                    d.TotalFreeSpace);

                Console.WriteLine(
                    "  Total size of drive:            {0, 15} bytes ",
                    d.TotalSize);
            }
        }
    }
}
/* 
This code produces output similar to the following:

Drive A:\
  Drive type: Removable
Drive C:\
  Drive type: Fixed
  Volume label: 
  File system: FAT32
  Available space to current user:     4770430976 bytes
  Total available space:               4770430976 bytes
  Total size of drive:                10731683840 bytes 
Drive D:\
  Drive type: Fixed
  Volume label: 
  File system: NTFS
  Available space to current user:    15114977280 bytes
  Total available space:              15114977280 bytes
  Total size of drive:                25958948864 bytes 
Drive E:\
  Drive type: CDRom

The actual output of this code will vary based on machine and the permissions
granted to the user executing it.
*/

ElasticSearch: Unassigned Shards, how to fix?

I had two indices with unassigned shards that didn't seem to be self-healing. I eventually resolved this by temporarily adding an extra data-node[1]. After the indices became healthy and everything stabilized to green, I removed the extra node and the system was able to rebalance (again) and settle on a healthy state.

It's a good idea to avoid killing multiple data nodes at once (which is how I got into this state). Likely, I had failed to preserve any copies/replicas for at least one of the shards. Luckily, Kubernetes kept the disk storage around, and reused it when I relaunched the data-node.


...Some time has passed...

Well, this time just adding a node didn't seem to be working (after waiting several minutes for something to happen), so I started poking around in the REST API.

GET /_cluster/allocation/explain

This showed my new node with "decision": "YES".

By the way, all of the pre-existing nodes had "decision": "NO" due to "the node is above the low watermark cluster setting". So this was probably a different case than the one I had addressed previously.

Then I made the following simple POST[2] with no body, which kicked things into gear...

POST /_cluster/reroute

Other notes:


[1] Pretty easy to do in Kubernetes if you have enough headroom: just scale out the stateful set via the dashboard.

[2] Using the Kibana "Dev Tools" interface, I didn't have to bother with SSH/exec shells.

How to unpublish an app in Google Play Developer Console

As per new Interface follow these steps

  1. Go to Google Play Developer Console
  2. Select your app you want to un-publish
  3. From the left Navigation Release >> Setup >> Advance Settings
  4. In the App Availability Check on Unpublished Radio button enter image description here

Correct way to detach from a container without stopping it

I consider Ashwin's answer to be the most correct, my old answer is below.


I'd like to add another option here which is to run the container as follows

docker run -dti foo bash

You can then enter the container and run bash with

docker exec -ti ID_of_foo bash

No need to install sshd :)

Build not visible in itunes connect

Check all the key and values in info.plist file. if any key is missing then it will cause this issue. AppIcon and other thing written in info.plist file must be prefect then u will not able to get this issue.

Cloning an Object in Node.js

Y'all suffering yet the solution is simple.

var obj1 = {x: 5, y:5};

var obj2 = {...obj1}; // Boom

Display Parameter(Multi-value) in Report

Hopefully someone else finds this useful:

Using the Join is the best way to use a multi-value parameter. But what if you want to have an efficient 'Select All'? If there are 100s+ then the query will be very inefficient.

To solve this instead of using a SQL Query as is, change it to using an expression (click the Fx button top right) then build your query something like this (speech marks are necessary):

= "Select * from tProducts Where 1 = 1 " 
IIF(Parameters!ProductID.Value(0)=-1,Nothing," And ProductID In (" & Join(Parameters!ProductID.Value,"','") & ")")

In your Parameter do the following:

    SELECT -1 As ProductID, 'All' as ProductName Union All
    Select  
    tProducts.ProductID,tProducts.ProductName
    FROM
    tProducts

By building the query as an expression means you can make the SQL Statement more efficient but also handle the difficulty SQL Server has with handling values in an 'In' statement.

make a header full screen (width) css

Set the max-width:1250px; that is currently on your body on your #container. This way your header will be 100% of his parent (body) :)

how much memory can be accessed by a 32 bit machine?

basically 32bit architecture can address 4GB as you expected. There are some techniques which allows processor to address more data like AWE or PAE.

How to copy a dictionary and only edit the copy

i ran into a peculiar behavior when trying to deep copy dictionary property of class w/o assigning it to variable

new = copy.deepcopy(my_class.a) doesn't work i.e. modifying new modifies my_class.a

but if you do old = my_class.a and then new = copy.deepcopy(old) it works perfectly i.e. modifying new does not affect my_class.a

I am not sure why this happens, but hope it helps save some hours! :)

How to plot ROC curve in Python

AUC curve For Binary Classification using matplotlib

from sklearn import svm, datasets
from sklearn import metrics
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_breast_cancer
import matplotlib.pyplot as plt

Load Breast Cancer Dataset

breast_cancer = load_breast_cancer()

X = breast_cancer.data
y = breast_cancer.target

Split the Dataset

X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.33, random_state=44)

Model

clf = LogisticRegression(penalty='l2', C=0.1)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)

Accuracy

print("Accuracy", metrics.accuracy_score(y_test, y_pred))

AUC Curve

y_pred_proba = clf.predict_proba(X_test)[::,1]
fpr, tpr, _ = metrics.roc_curve(y_test,  y_pred_proba)
auc = metrics.roc_auc_score(y_test, y_pred_proba)
plt.plot(fpr,tpr,label="data 1, auc="+str(auc))
plt.legend(loc=4)
plt.show()

AUC Curve

Maven build failed: "Unable to locate the Javac Compiler in: jre or jdk issue"

I have just installed Maven 3.0.4, set M2_HOME, M2 and JAVA_HOME accordingly. I then ran the following commands:

mvn archetype:generate....

mvn compile

I got failed message such as: maven unable to locate javac compiler.

On my computer, I have by default JRE installed at C:\program files\java\jre.1.6. And I have the other C:\java\jdk1.6 and JAVA_HOME set to this C:\java\jdk1.6.

I didn't see anything wrong with my setting. After searching, I decided to look into mvn.bat, I echoed %JAVA_HOME% every step and it displayed correctly as C:\java\jdk1.6, but when I run the command mvn --version, it displayed Java home: C:\program files\java\jre1.1.6.

Finally, I found out that I just need to set -Djava.home=c:\java\jdk1.6 as in the command below, and working fine now:

%MAVEN_JAVA_EXE% %MAVEN_OPTS% -classpath %CLASSWORLDS_JAR% "-Dclassworlds.conf=%M2_HOME%\bin\m2.conf" "-Djava.home=%JAVA_HOME%" "-Dmaven.home=%M2_HOME%" %CLASSWORLDS_LAUNCHER% %MAVEN_CMD_LINE_ARGS%

Note: This is for mvn on the command line and not with Eclipse.

How to search for a file in the CentOS command line

CentOS is Linux, so as in just about all other Unix/Linux systems, you have the find command. To search for files within the current directory:

find -name "filename"

You can also have wildcards inside the quotes, and not just a strict filename. You can also explicitly specify a directory to start searching from as the first argument to find:

find / -name "filename"

will look for "filename" or all the files that match the regex expression in between the quotes, starting from the root directory. You can also use single quotes instead of double quotes, but in most cases you don't need either one, so the above commands will work without any quotes as well. Also, for example, if you're searching for java files and you know they are somewhere in your /home/username, do:

find /home/username -name *.java

There are many more options to the find command and you should do a:

man find

to learn more about it.

One more thing: if you start searching from / and are not root or are not sudo running the command, you might get warnings that you don't have permission to read certain directories. To ignore/remove those, do:

find / -name 'filename' 2>/dev/null

That just redirects the stderr to /dev/null.

When should I create a destructor?

Destructors provide an implicit way of freeing unmanaged resources encapsulated in your class, they get called when the GC gets around to it and they implicitly call the Finalize method of the base class. If you're using a lot of unmanaged resources it is better to provide an explicit way of freeing those resources via the IDisposable interface. See the C# programming guide: http://msdn.microsoft.com/en-us/library/66x5fx1b.aspx

numpy: most efficient frequency counts for unique values in an array

I was also interested in this, so I did a little performance comparison (using perfplot, a pet project of mine). Result:

y = np.bincount(a)
ii = np.nonzero(y)[0]
out = np.vstack((ii, y[ii])).T

is by far the fastest. (Note the log-scaling.)

enter image description here


Code to generate the plot:

import numpy as np
import pandas as pd
import perfplot
from scipy.stats import itemfreq


def bincount(a):
    y = np.bincount(a)
    ii = np.nonzero(y)[0]
    return np.vstack((ii, y[ii])).T


def unique(a):
    unique, counts = np.unique(a, return_counts=True)
    return np.asarray((unique, counts)).T


def unique_count(a):
    unique, inverse = np.unique(a, return_inverse=True)
    count = np.zeros(len(unique), np.int)
    np.add.at(count, inverse, 1)
    return np.vstack((unique, count)).T


def pandas_value_counts(a):
    out = pd.value_counts(pd.Series(a))
    out.sort_index(inplace=True)
    out = np.stack([out.keys().values, out.values]).T
    return out


perfplot.show(
    setup=lambda n: np.random.randint(0, 1000, n),
    kernels=[bincount, unique, itemfreq, unique_count, pandas_value_counts],
    n_range=[2 ** k for k in range(26)],
    logx=True,
    logy=True,
    xlabel="len(a)",
)

PLS-00103: Encountered the symbol when expecting one of the following:

begin
    var_number := 10;

    if var_number > 100 then
        dbms_output.put_line(var_number||' is greater than 100');
    else if var_number < 100 then
        dbms_output.put_line(var_number||' is less than 100');
    else
        dbms_output.put_line(var_number||' is equal to 100');
    end if;
end if;

Launching an application (.EXE) from C#?

Use System.Diagnostics.Process.Start() method.

Check out this article on how to use it.

Process.Start("notepad", "readme.txt");

string winpath = Environment.GetEnvironmentVariable("windir");
string path = System.IO.Path.GetDirectoryName(
              System.Windows.Forms.Application.ExecutablePath);

Process.Start(winpath + @"\Microsoft.NET\Framework\v1.0.3705\Installutil.exe",
path + "\\MyService.exe");

What is the difference between explicit and implicit cursors in Oracle?

An explicit cursor is one you declare, like:

CURSOR my_cursor IS
  SELECT table_name FROM USER_TABLES

An implicit cursor is one created to support any in-line SQL you write (either static or dynamic).

MySQL: #126 - Incorrect key file for table

I know that this is an old topic but none of the solution mentioned worked for me. I have done something else that worked:

You need to:

  1. stop the MySQL service:
  2. Open mysql\data
  3. Remove both ib_logfile0 and ib_logfile1.
  4. Restart the service

Winforms TableLayoutPanel adding rows programmatically

Create a table layout panel with two columns in your form and name it tlpFields.

Then, simply add new control to table layout panel (in this case I added 5 labels in column-1 and 5 textboxes in column-2).

tlpFields.RowStyles.Clear();  //first you must clear rowStyles

for (int ii = 0; ii < 5; ii++)
{
    Label l1= new Label();
    TextBox t1 = new TextBox();

    l1.Text = "field : ";

    tlpFields.Controls.Add(l1, 0, ii);  // add label in column0
    tlpFields.Controls.Add(t1, 1, ii);  // add textbox in column1

    tlpFields.RowStyles.Add(new RowStyle(SizeType.Absolute,30)); // 30 is the rows space
}

Finally, run the code.

Gradle, Android and the ANDROID_HOME SDK location

I have the same problem, seems the sample code can not find the android environment, instead to try to fix that I just remove the sample code from settings.gradle and then the installation goes fine.

after that just import the project in eclipse and that's all :)

How to convert color code into media.brush?

You could use the same mechanism the XAML reading system uses: Type converters

var converter = new System.Windows.Media.BrushConverter();
var brush = (Brush)converter.ConvertFromString("#FFFFFF90");
Fill = brush;

How to tell if a connection is dead in python

Short answer:

use a non-blocking recv(), or a blocking recv() / select() with a very short timeout.

Long answer:

The way to handle socket connections is to read or write as you need to, and be prepared to handle connection errors.

TCP distinguishes between 3 forms of "dropping" a connection: timeout, reset, close.

Of these, the timeout can not really be detected, TCP might only tell you the time has not expired yet. But even if it told you that, the time might still expire right after.

Also remember that using shutdown() either you or your peer (the other end of the connection) may close only the incoming byte stream, and keep the outgoing byte stream running, or close the outgoing stream and keep the incoming one running.

So strictly speaking, you want to check if the read stream is closed, or if the write stream is closed, or if both are closed.

Even if the connection was "dropped", you should still be able to read any data that is still in the network buffer. Only after the buffer is empty will you receive a disconnect from recv().

Checking if the connection was dropped is like asking "what will I receive after reading all data that is currently buffered ?" To find that out, you just have to read all data that is currently bufferred.

I can see how "reading all buffered data", to get to the end of it, might be a problem for some people, that still think of recv() as a blocking function. With a blocking recv(), "checking" for a read when the buffer is already empty will block, which defeats the purpose of "checking".

In my opinion any function that is documented to potentially block the entire process indefinitely is a design flaw, but I guess it is still there for historical reasons, from when using a socket just like a regular file descriptor was a cool idea.

What you can do is:

  • set the socket to non-blocking mode, but than you get a system-depended error to indicate the receive buffer is empty, or the send buffer is full
  • stick to blocking mode but set a very short socket timeout. This will allow you to "ping" or "check" the socket with recv(), pretty much what you want to do
  • use select() call or asyncore module with a very short timeout. Error reporting is still system-specific.

For the write part of the problem, keeping the read buffers empty pretty much covers it. You will discover a connection "dropped" after a non-blocking read attempt, and you may choose to stop sending anything after a read returns a closed channel.

I guess the only way to be sure your sent data has reached the other end (and is not still in the send buffer) is either:

  • receive a proper response on the same socket for the exact message that you sent. Basically you are using the higher level protocol to provide confirmation.
  • perform a successful shutdow() and close() on the socket

The python socket howto says send() will return 0 bytes written if channel is closed. You may use a non-blocking or a timeout socket.send() and if it returns 0 you can no longer send data on that socket. But if it returns non-zero, you have already sent something, good luck with that :)

Also here I have not considered OOB (out-of-band) socket data here as a means to approach your problem, but I think OOB was not what you meant.

for-in statement

TypeScript isn't giving you a gun to shoot yourself in the foot with.

The iterator variable is a string because it is a string, full stop. Observe:

var obj = {};
obj['0'] = 'quote zero quote';
obj[0.0] = 'zero point zero';
obj['[object Object]'] = 'literal string "[object Object]"';
obj[<any>obj] = 'this obj'
obj[<any>undefined] = 'undefined';
obj[<any>"undefined"] = 'the literal string "undefined"';

for(var key in obj) {
    console.log('Type: ' + typeof key);
    console.log(key + ' => ' + obj[key]);
}

How many key/value pairs are in obj now? 6, more or less? No, 3, and all of the keys are strings:

Type: string
0 => zero point zero
Type: string
[object Object] => this obj; 
Type: string
undefined => the literal string "undefined" 

How can I force division to be floating point? Division keeps rounding down to 0?

You can cast to float by doing c = a / float(b). If the numerator or denominator is a float, then the result will be also.


A caveat: as commenters have pointed out, this won't work if b might be something other than an integer or floating-point number (or a string representing one). If you might be dealing with other types (such as complex numbers) you'll need to either check for those or use a different method.

IsNothing versus Is Nothing

I find that Patrick Steele answered this question best on his blog: Avoiding IsNothing()

I did not copy any of his answer here, to ensure Patrick Steele get's credit for his post. But I do think if you're trying to decide whether to use Is Nothing or IsNothing you should read his post. I think you'll agree that Is Nothing is the best choice.

Edit - VoteCoffe's comment here

Partial article contents: After reviewing more code I found out another reason you should avoid this: It accepts value types! Obviously, since IsNothing() is a function that accepts an 'object', you can pass anything you want to it. If it's a value type, .NET will box it up into an object and pass it to IsNothing -- which will always return false on a boxed value! The VB.NET compiler will check the "Is Nothing" style syntax and won't compile if you attempt to do an "Is Nothing" on a value type. But the IsNothing() function compiles without complaints. -PSteele – VoteCoffee

How to format number of decimal places in wpf using style/template?

    void NumericTextBoxInput(object sender, TextCompositionEventArgs e)
    {
        TextBox txt = (TextBox)sender;
        var regex = new Regex(@"^[0-9]*(?:\.[0-9]{0,1})?$");
        string str = txt.Text + e.Text.ToString();
        int cntPrc = 0;
        if (str.Contains('.'))
        {
            string[] tokens = str.Split('.');
            if (tokens.Count() > 0)
            {
                string result = tokens[1];
                char[] prc = result.ToCharArray();
                cntPrc = prc.Count();
            }
        }
        if (regex.IsMatch(e.Text) && !(e.Text == "." && ((TextBox)sender).Text.Contains(e.Text)) && (cntPrc < 3))
        {
            e.Handled = false;
        }
        else
        {
            e.Handled = true;
        }
    }

Nginx location "not equal to" regex

According to nginx documentation

there is no syntax for NOT matching a regular expression. Instead, match the target regular expression and assign an empty block, then use location / to match anything else

So you could define something like

location ~ (dir1|file2\.php) { 
    # empty
}

location / {
    rewrite ^/(.*) http://example.com/$1 permanent; 
}

How to write inline if statement for print?

This can be done with string formatting. It works with the % notation as well as .format() and f-strings (new to 3.6)

print '%s' % (a if b else "")

or

print '{}'.format(a if b else "")

or

print(f'{a if b else ""}')

Java JDBC - How to connect to Oracle using Service Name instead of SID

This should be working: jdbc:oracle:thin//hostname:Port/ServiceName=SERVICE_NAME

Pygame mouse clicking detection

The pygame documentation for mouse events is here. You can either use the pygame.mouse.get_pressed method in collaboration with the pygame.mouse.get_pos (if needed). But please use the mouse click event via a main event loop. The reason why the event loop is better is due to "short clicks". You may not notice these on normal machines, but computers that use tap-clicks on trackpads have excessively small click periods. Using the mouse events will prevent this.

EDIT: To perform pixel perfect collisions use pygame.sprite.collide_rect() found on their docs for sprites.

First char to upper case

Comilation error is due arguments are not properly provided, replaceFirst accepts regx as initial arg. [a-z]{1} will match string of simple alpha characters of length 1.

Try this.

betterIdea = userIdea.replaceFirst("[a-z]{1}", userIdea.substring(0,1).toUpperCase())

The difference in months between dates in MySQL

PERIOD_DIFF calculates months between two dates.

For example, to calculate the difference between now() and a time column in your_table:

select period_diff(date_format(now(), '%Y%m'), date_format(time, '%Y%m')) as months from your_table;

How to set the height of table header in UITableView?

In Xcode 10 you can set header and footer of section hight from "Size Inspector" tab

Size Inspector header

How to Ignore "Duplicate Key" error in T-SQL (SQL Server)

If by "Ignore Duplicate Error statments", to abort the current statement and continue to the next statement without aborting the trnsaction then just put BEGIN TRY.. END TRY around each statement:

BEGIN TRY
    INSERT ...
END TRY
BEGIN CATCH /*required, but you dont have to do anything */ END CATCH
...

$_POST vs. $_SERVER['REQUEST_METHOD'] == 'POST'

As long as I may need to access my PHP scripts with more than one method, what I do actually is:

if (in_array($_SERVER['REQUEST_METHOD'],array("GET","POST","DELETE"))) {
// do wathever I do 
}

Disable all table constraints in Oracle

It's not a single command, but here's how I do it. The following script has been designed to run in SQL*Plus. Note, I've purposely written this to only work within the current schema.

set heading off

spool drop_constraints.out

select
    'alter table ' || 
    owner || '.' || 
    table_name || 
    ' disable constraint ' || -- or 'drop' if you want to permanently remove
    constraint_name || ';'
from
    user_constraints;

spool off

set heading on

@drop_constraints.out

To restrict what you drop, filter add a where clause to the select statement:-

  • filter on constraint_type to drop only particular types of constraints
  • filter on table_name to do it only for one or a few tables.

To run on more than the current schema, modify the select statement to select from all_constraints rather than user_constraints.

Note - for some reason I can't get the underscore to NOT act like an italicization in the previous paragraph. If someone knows how to fix it, please feel free to edit this answer.

Built in Python hash() function

It probably just asks the operating system provided function, rather than its own algorithm.

As other comments says, use hashlib or write your own hash function.

Javascript: Extend a Function

Another option could be:

var initial = function() {
    console.log( 'initial function!' );
}

var iWantToExecuteThisOneToo = function () {
    console.log( 'the other function that i wanted to execute!' );
}

function extendFunction( oldOne, newOne ) {
    return (function() {
        oldOne();
        newOne();
    })();
}

var extendedFunction = extendFunction( initial, iWantToExecuteThisOneToo );

Ansible: Set variable to file content

You can use the slurp module to fetch a file from the remote host: (Thanks to @mlissner for suggesting it)

vars:
  amazon_linux_ami: "ami-fb8e9292"
  user_data_file: "base-ami-userdata.sh"
tasks:
- name: Load data
  slurp:
    src: "{{ user_data_file }}"
  register: slurped_user_data
- name: Decode data and store as fact # You can skip this if you want to use the right hand side directly...
  set_fact:
    user_data: "{{ slurped_user_data.content | b64decode }}"

Call a "local" function within module.exports from another function in module.exports?

Starting with Node.js version 13 you can take advantage of ES6 Modules.

export function foo() {
    return 'foo';
}

export function bar() {
    return foo();
}

Following the Class approach:

class MyClass {

    foo() {
        return 'foo';
    }

    bar() {
        return this.foo();
    }
}

module.exports = new MyClass();

This will instantiate the class only once, due to Node's module caching:
https://nodejs.org/api/modules.html#modules_caching

What is Android keystore file, and what is it used for?

The answer I would provide is that a keystore file is to authenticate yourself to anyone who is asking. It isn't restricted to just signing .apk files, you can use it to store personal certificates, sign data to be transmitted and a whole variety of authentication.

In terms of what you do with it for Android and probably what you're looking for since you mention signing apk's, it is your certificate. You are branding your application with your credentials. You can brand multiple applications with the same key, in fact, it is recommended that you use one certificate to brand multiple applications that you write. It easier to keep track of what applications belong to you.

I'm not sure what you mean by implications. I suppose it means that no one but the holder of your certificate can update your application. That means that if you release it into the wild, lose the cert you used to sign the application, then you cannot release updates so keep that cert safe and backed up if need be.

But apart from signing apks to release into the wild, you can use it to authenticate your device to a server over SSL if you so desire, (also Android related) among other functions.

MySQL: is a SELECT statement case sensitive?

Note also that table names are case sensitive on Linux unless you set the lower_case_table_name config directive to 1. This is because tables are represented by files which are case sensitive in Linux.

Especially beware of development on Windows which is not case sensitive and deploying to production where it is. For example:

"SELECT * from mytable" 

against table myTable will succeed in Windows but fail in Linux, again, unless the abovementioned directive is set.

Reference here: http://dev.mysql.com/doc/refman/5.0/en/identifier-case-sensitivity.html

'cl' is not recognized as an internal or external command,

I had the same issue for a long time and I spent God knows how much on it until I accidentally figured what to do. This solution worked on windows 10. All you need to do is to add C:\WINDOWS\System32 to Path variable under User Variables in Environmental Variables... Note that if you add this to the system variables, it may also work. But, that didn't work for me.

Recommended way to get hostname in Java

InetAddress.getLocalHost().getHostName() is the more portable way.

exec("hostname") actually calls out to the operating system to execute the hostname command.

Here are a couple other related answers on SO:

EDIT: You should take a look at A.H.'s answer or Arnout Engelen's answer for details on why this might not work as expected, depending on your situation. As an answer for this person who specifically requested portable, I still think getHostName() is fine, but they bring up some good points that should be considered.

Vim delete blank lines

Found it, it's:

g/^\s*$/d

Source: Power of g at vim wikia

Brief explanation of :g

:[range]g/pattern/cmd

This acts on the specified [range] (default whole file), by executing the Ex command cmd for each line matching pattern (an Ex command is one starting with a colon such as :d for delete). Before executing cmd, "." is set to the current line.

What is "with (nolock)" in SQL Server?

Not sure why you are not wrapping financial transactions in database transactions (as when you transfer funds from one account to another - you don't commit one side of the transaction at-a-time - this is why explicit transactions exist). Even if your code is braindead to business transactions as it sounds like it is, all transactional databases have the potential to do implicit rollbacks in the event of errors or failure. I think this discussion is way over your head.

If you are having locking problems, implement versioning and clean up your code.

No lock not only returns wrong values it returns phantom records and duplicates.

It is a common misconception that it always makes queries run faster. If there are no write locks on a table, it does not make any difference. If there are locks on the table, it may make the query faster, but there is a reason locks were invented in the first place.

In fairness, here are two special scenarios where a nolock hint may provide utility

1) Pre-2005 sql server database that needs to run long query against live OLTP database this may be the only way

2) Poorly written application that locks records and returns control to the UI and readers are indefinitely blocked. Nolock can be helpful here if application cannot be fixed (third party etc) and database is either pre-2005 or versioning cannot be turned on.

Can we use JSch for SSH key-based communication?

It is possible. Have a look at JSch.addIdentity(...)

This allows you to use key either as byte array or to read it from file.

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class UserAuthPubKey {
    public static void main(String[] arg) {
        try {
            JSch jsch = new JSch();

            String user = "tjill";
            String host = "192.18.0.246";
            int port = 10022;
            String privateKey = ".ssh/id_rsa";

            jsch.addIdentity(privateKey);
            System.out.println("identity added ");

            Session session = jsch.getSession(user, host, port);
            System.out.println("session created.");

            // disabling StrictHostKeyChecking may help to make connection but makes it insecure
            // see http://stackoverflow.com/questions/30178936/jsch-sftp-security-with-session-setconfigstricthostkeychecking-no
            // 
            // java.util.Properties config = new java.util.Properties();
            // config.put("StrictHostKeyChecking", "no");
            // session.setConfig(config);

            session.connect();
            System.out.println("session connected.....");

            Channel channel = session.openChannel("sftp");
            channel.setInputStream(System.in);
            channel.setOutputStream(System.out);
            channel.connect();
            System.out.println("shell channel connected....");

            ChannelSftp c = (ChannelSftp) channel;

            String fileName = "test.txt";
            c.put(fileName, "./in/");
            c.exit();
            System.out.println("done");

        } catch (Exception e) {
            System.err.println(e);
        }
    }
}

How to do what head, tail, more, less, sed do in Powershell?

$Push_Pop = $ErrorActionPreference #Suppresses errors
$ErrorActionPreference = “SilentlyContinue” #Suppresses errors
#Script
    #gc .\output\*.csv -ReadCount 5 | %{$_;throw "pipeline end!"} # head
    #gc .\output\*.csv | %{$num=0;}{$num++;"$num $_"}             # cat -n
    gc .\output\*.csv | %{$num=0;}{$num++; if($num -gt 2 -and $num -lt 7){"$num $_"}} # sed
#End Script 
$ErrorActionPreference = $Push_Pop #Suppresses errors

You don't get all the errors with the pushpop code BTW, your code only works with the "sed" option. All the rest ignores anything but gc and path.

Invalid column name sql error

Your issue seems to be the Name keyword. Rather use FullName or firstName and lastName, always try and remember to use CamelCase too.

Context.startForegroundService() did not then call Service.startForeground()

Problem With Android O API 26

If you stop the service right away (so your service does not actually really runs (wording / comprehension) and you are way under the ANR interval, you still need to call startForeground before stopSelf

https://plus.google.com/116630648530850689477/posts/L2rn4T6SAJ5

Tried this Approach But it Still creates an error:-

if (Util.SDK_INT > 26) {
    mContext.startForegroundService(playIntent);
} else {
    mContext.startService(playIntent);
}

I Am Using this until the Error is Resolved

mContext.startService(playIntent);

Converting Symbols, Accent Letters to English Alphabet

There is no easy or general way to do what you want because it is just your subjective opinion that these letters look loke the latin letters you want to convert to. They are actually separate letters with their own distinct names and sounds which just happen to superficially look like a latin letter.

If you want that conversion, you have to create your own translation table based on what latin letters you think the non-latin letters should be converted to.

(If you only want to remove diacritial marks, there are some answers in this thread: How do I remove diacritics (accents) from a string in .NET? However you describe a more general problem)

How can I compare a date and a datetime in Python?

Create and similar object for comparison works too ex:

from datetime import datetime, date

now = datetime.now()
today = date.today()

# compare now with today
two_month_earlier = date(now.year, now.month - 2, now.day)
if two_month_earlier > today:
    print(True)

two_month_earlier = datetime(now.year, now.month - 2, now.day)
if two_month_earlier > now:
   print("this will work with datetime too")

Python match a string with regex

As everyone else has mentioned it is better to use the "in" operator, it can also act on lists:

line = "This,is,a,sample,string"
lst = ['This', 'sample']
for i in lst:
     i in line

>> True
>> True

How do I run a file on localhost?

Looking at your other question I assume you are trying to run a php or asp file or something on your webserver and this is your first attempt in webdesign.

Once you have installed php correctly (which you probably did when you got XAMPP) just place whatever file you want under your localhost (/www/var/html perhaps?) and it should run. You can check this of course at localhost/file.php in your browser.

Form Validation With Bootstrap (jQuery)

I had your code setup on jsFiddle to try diagnose the problem.

http://jsfiddle.net/5WMff/

However, I don't seem to encounter your issue. Could you take a look and let us know?

HTML

<div class="hero-unit">
 <h1>Contact Form</h1> 
</br>
<form method="POST" action="contact-form-submission.php" class="form-horizontal" id="contact-form">
    <div class="control-group">
        <label class="control-label" for="name">Name</label>
        <div class="controls">
            <input type="text" name="name" id="name" placeholder="Your name">
        </div>
    </div>
    <div class="control-group">
        <label class="control-label" for="email">Email Address</label>
        <div class="controls">
            <input type="text" name="email" id="email" placeholder="Your email address">
        </div>
    </div>
    <div class="control-group">
        <label class="control-label" for="subject">Subject</label>
        <div class="controls">
            <select id="subject" name="subject">
                <option value="na" selected="">Choose One:</option>
                <option value="service">Feedback</option>
                <option value="suggestions">Suggestion</option>
                <option value="support">Question</option>
                <option value="other">Other</option>
            </select>
        </div>
    </div>
    <div class="control-group">
        <label class="control-label" for="message">Message</label>
        <div class="controls">
            <textarea name="message" id="message" rows="8" class="span5" placeholder="The message you want to send to us."></textarea>
        </div>
    </div>
    <div class="form-actions">
        <input type="hidden" name="save" value="contact">
        <button type="submit" class="btn btn-success">Submit Message</button>
        <button type="reset" class="btn">Cancel</button>
    </div>
</form>

Javascript

$(document).ready(function () {

$('#contact-form').validate({
    rules: {
        name: {
            minlength: 2,
            required: true
        },
        email: {
            required: true,
            email: true
        },
        message: {
            minlength: 2,
            required: true
        }
    },
    highlight: function (element) {
        $(element).closest('.control-group').removeClass('success').addClass('error');
    },
    success: function (element) {
        element.text('OK!').addClass('valid')
            .closest('.control-group').removeClass('error').addClass('success');
    }
});
});

See last changes in svn

svn log - I'm sure WebSVN has some feature for that too.

The "View Log" link near the center-top of the WebSVN overview shows the svn-log. However, the user-interface isn't exactly brilliant; I much prefer TortoiseSVN's log viewer.

Angular-cli from css to scss

For Angular 6,

ng config schematics.@schematics/angular:component.styleext scss

note: @schematics/angular is the default schematic for the Angular CLI

Passing arrays as parameters in bash

Note: This is the somewhat crude solution I posted myself, after not finding an answer here on Stack Overflow. It allows for only one array being passed, and it being the last element of the parameter list. Actually, it is not passing the array at all, but a list of its elements, which are re-assembled into an array by called_function(), but it worked for me. Somewhat later Ken posted his solution, but I kept mine here for "historic" reference.

calling_function()
{
    variable="a"
    array=( "x", "y", "z" )
    called_function "${variable}" "${array[@]}"
}

called_function()
{
    local_variable="${1}"
    shift
    local_array=("${@}")
}

Using Ansible set_fact to create a dictionary from register results

I think I got there in the end.

The task is like this:

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

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

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

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


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

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

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

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

Connecting to MySQL from Android with JDBC

You can't access a MySQL DB from Android natively. EDIT: Actually you may be able to use JDBC, but it is not recommended (or may not work?) ... see Android JDBC not working: ClassNotFoundException on driver

See

http://www.helloandroid.com/tutorials/connecting-mysql-database

http://www.basic4ppc.com/forum/basic4android-getting-started-tutorials/8339-connect-android-mysql-database-tutorial.html

Android cannot connect directly to the database server. Therefore we need to create a simple web service that will pass the requests to the database and will return the response.

http://codeoncloud.blogspot.com/2012/03/android-mysql-client.html

For most [good] users this might be fine. But imagine you get a hacker that gets a hold of your program. I've decompiled my own applications and its scary what I've seen. What if they get your username / password to your database and wreak havoc? Bad.

How to get root view controller?

Swift way to do it, you can call this from anywhere, it returns optional so watch out about that:

/// EZSwiftExtensions - Gives you the VC on top so you can easily push your popups
var topMostVC: UIViewController? {
    var presentedVC = UIApplication.sharedApplication().keyWindow?.rootViewController
    while let pVC = presentedVC?.presentedViewController {
        presentedVC = pVC
    }

    if presentedVC == nil {
        print("EZSwiftExtensions Error: You don't have any views set. You may be calling them in viewDidLoad. Try viewDidAppear instead.")
    }
    return presentedVC
}

Its included as a standard function in:

https://github.com/goktugyil/EZSwiftExtensions

Programmatically check Play Store for app updates

Firebase Remote Config could be a possible and reliable solution for now, since google didn't expose any api to it.

Check Firebase Remote Config Docs

Steps 1.Create a firebase project and add google_play_service.json to your project

2.Create keys like "android_latest_version_code" and "android_latest_version_name" in firebase console->Remote Config

3.Android Code

    public void initializeFirebase() {
        if (FirebaseApp.getApps(mContext).isEmpty()) {
            FirebaseApp.initializeApp(mContext, FirebaseOptions.fromResource(mContext));
        }
        final FirebaseRemoteConfig config = FirebaseRemoteConfig.getInstance();
        FirebaseRemoteConfigSettings configSettings = new FirebaseRemoteConfigSettings.Builder()
                                                              .setDeveloperModeEnabled(BuildConfig.DEBUG)
                                                              .build();
        config.setConfigSettings(configSettings);
}

Get current version name and code

int playStoreVersionCode = FirebaseRemoteConfig.getInstance().getString(
                "android_latest_version_code");
PackageInfo pInfo = this.getPackageManager().getPackageInfo(getPackageName(), 0);
int currentAppVersionCode = pInfo.versionCode; 
if(playStoreVersionCode>currentAppVersionCode){
//Show update popup or whatever best for you
}

4. And keep firebase "android_latest_version_code" and "android_latest_version_name" upto date with your current production version name and code.

Firebase remote config works on both Android and IPhone.

How to add an image to an svg container using D3.js

In SVG (contrasted with HTML), you will want to use <image> instead of <img> for elements.

Try changing your last block with:

var imgs = svg.selectAll("image").data([0]);
            imgs.enter()
            .append("svg:image")
            ...

How to close current tab in a browser window?

As far as I can tell, it no longer is possible in Chrome or FireFox. It may still be possible in IE (at least pre-Edge).

I am getting an "Invalid Host header" message when connecting to webpack-dev-server remotely

Hello React Developers,

Instead of doing this disableHostCheck: true, in webpackDevServer.config.js. You can easily solve 'invalid host headers' error by adding a .env file to you project, add the variables HOST=0.0.0.0 and DANGEROUSLY_DISABLE_HOST_CHECK=true in .env file. If you want to make changes in webpackDevServer.config.js, you need to extract the react-scripts by using 'npm run eject' which is not recommended to do it. So the better solution is adding above mentioned variables in .env file of your project.

Happy Coding :)

Scanner is never closed

I am assuming you are using java 7, thus you get a compiler warning, when you don't close the resource you should close your scanner usually in a finally block.

Scanner scanner = null;
try {
    scanner = new Scanner(System.in);
    //rest of the code
}
finally {
    if(scanner!=null)
        scanner.close();
}

Or even better: use the new Try with resource statement:

try(Scanner scanner = new Scanner(System.in)){
    //rest of your code
}

How to Deserialize XML document

See if this helps:

[Serializable()]
[System.Xml.Serialization.XmlRootAttribute("Cars", Namespace = "", IsNullable = false)]
public class Cars
{
    [XmlArrayItem(typeof(Car))]
    public Car[] Car { get; set; }
}

.

[Serializable()]
public class Car
{
    [System.Xml.Serialization.XmlElement()]
    public string StockNumber{ get; set; }

    [System.Xml.Serialization.XmlElement()]
    public string Make{ get; set; }

    [System.Xml.Serialization.XmlElement()]
    public string Model{ get; set; }
}

And failing that use the xsd.exe program that comes with visual studio to create a schema document based on that xml file, and then use it again to create a class based on the schema document.

Django Reverse with arguments '()' and keyword arguments '{}' not found

This problems gave me great headache when i tried to use reverse for generating activation link and send it via email of course. So i think from tests.py it will be same. The correct way to do this is following:

from django.test import Client
from django.core.urlresolvers import reverse

#app name - name of the app where the url is defined
client= Client()
response = client.get(reverse('app_name:edit_project', project_id=4)) 

Best Way to do Columns in HTML/CSS

Bootstrap. Check out their awesome grid system here.

Using Bootstrap, you could make three columns like this:

<div class="container">
  <div class="row">
    <div class="col-md-4">.col-md-4</div>
    <div class="col-md-4">.col-md-4</div>
    <div class="col-md-4">.col-md-4</div>
  </div>
</div>

Handler "ExtensionlessUrlHandler-Integrated-4.0" has a bad module "ManagedPipelineHandler" in its module list

I solved this problem, adding in "Turn Windows features on or off" The option ASP.NET 4.7

enter image description here

vector vs. list in STL

Well the students of my class seems quite unable to explain to me when it is more effective to use vectors, but they look quite happy when advising me to use lists.

This is how I understand it

Lists: Each item contains an address to the next or previous element, so with this feature, you can randomize the items, even if they aren't sorted, the order won't change: it's efficient if you memory is fragmented. But it also has an other very big advantage: you can easily insert/remove items, because the only thing you need to do is change some pointers. Drawback: To read a random single item, you have to jump from one item to another until you find the correct address.

Vectors: When using vectors, the memory is much more organized like regular arrays: each n-th items is stored just after (n-1)th item and before (n+1)th item. Why is it better than list ? Because it allow fast random access. Here is how: if you know the size of an item in a vector, and if they are contiguous in memory, you can easily predict where the n-th item is; you don't have to browse all the item of a list to read the one you want, with vector, you directly read it, with a list you can't. On the other hand, modify the vector array or change a value is much more slow.

Lists are more appropriate to keep track of objects which can be added/removed in memory. Vectors are more appropriate when you want to access an element from a big quantity of single items.

I don't know how lists are optimized, but you have to know that if you want fast read access, you should use vectors, because how good the STL fasten lists, it won't be as fast in read-access than vector.

Yum fails with - There are no enabled repos.

ok, so my problem was that I tried to install the package with yum which is the primary tool for getting, installing, deleting, querying, and managing Red Hat Enterprise Linux RPM software packages from official Red Hat software repositories, as well as other third-party repositories.

But I'm using ubuntu and The usual way to install packages on the command line in Ubuntu is with apt-get. so the right command was:

sudo apt-get install libstdc++.i686

UTF-8: General? Bin? Unicode?

Accepted answer is outdated.

If you use MySQL 5.5.3+, use utf8mb4_unicode_ci instead of utf8_unicode_ci to ensure the characters typed by your users won't give you errors.

utf8mb4 supports emojis for example, whereas utf8 might give you hundreds of encoding-related bugs like:

Incorrect string value: ‘\xF0\x9F\x98\x81…’ for column ‘data’ at row 1

C# how to use enum with switch

You don't need to convert it

switch(op)
{
     case Operator.PLUS:
     {
        // your code 
        // for plus operator
        break;
     }
     case Operator.MULTIPLY:
     {
        // your code 
        // for MULTIPLY operator
        break;
     }
     default: break;
}

By the way, use brackets

JFrame Exit on close Java

this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

this worked for me in case of Class Extends Frame

How to enable PHP's openssl extension to install Composer?

If you are using xampp .Go back to where you choose which command-line php you want to use at the beginning of your installation and select the path where your xampp folder is included.After that if your installer says youve got duplicate 'extension=php_openssl.dll' comment one ssl file in your php ini with a ';'and your installation should run smoothly.

Password Protect a SQLite DB. Is it possible?

Use SQLCipher, it's an opensource extension for SQLite that provides transparent 256-bit AES encryption of database files. http://sqlcipher.net

Calling the base constructor in C#

You can also do a conditional check with parameters in the constructor, which allows some flexibility.

public MyClass(object myObject=null): base(myObject ?? new myOtherObject())
{
}

or

public MyClass(object myObject=null): base(myObject==null ? new myOtherObject(): myObject)
{
}

Cannot obtain value of local or argument as it is not available at this instruction pointer, possibly because it has been optimized away

Regarding the problem with "Optimize code" property being UNCHECKED yet the code still compiling as optimized: What finally helped me after trying everything was checking the "Enable unmanaged code debugging" checkbox on the same settings page (Project properties - Debug). It doesn't directly relate to the code optimization, but with this enabled, VS no longer optimizes my library and I can debug.

My C# application is returning 0xE0434352 to Windows Task Scheduler but it is not crashing

When setup a job in new windows you have two fields "program/script" and "Start in(Optional)". Put program name in first and program location in second. If you will not do that and your program start not in directory with exe, it will not find files that are located in it.

Jquery - How to make $.post() use contentType=application/json?

I know this is a late answer, I actually have a shortcut method that I use for posting/reading to/from MS based services.. it works with MVC as well as ASMX etc...

Use:

$.msajax(
  '/services/someservice.asmx/SomeMethod'
  ,{}  /*empty object for nothing, or object to send as Application/JSON */
  ,function(data,jqXHR) {
    //use the data from the response.
  }
  ,function(err,jqXHR) {
    //additional error handling.
  }
);
//sends a json request to an ASMX or WCF service configured to reply to JSON requests.
(function ($) {
  var tries = 0; //IE9 seems to error out the first ajax call sometimes... will retry up to 5 times

  $.msajax = function (url, data, onSuccess, onError) {
    return $.ajax({
      'type': "POST"
      , 'url': url
      , 'contentType': "application/json"
      , 'dataType': "json"
      , 'data': typeof data == "string" ? data : JSON.stringify(data || {})
      ,beforeSend: function(jqXHR) {
        jqXHR.setRequestHeader("X-MicrosoftAjax","Delta=true");
      }
      , 'complete': function(jqXHR, textStatus) {
        handleResponse(jqXHR, textStatus, onSuccess, onError, function(){
          setTimeout(function(){
            $.msajax(url, data, onSuccess, onError);
          }, 100 * tries); //try again
        });
      }
    });
  }

  $.msajax.defaultErrorMessage = "Error retreiving data.";


  function logError(err, errorHandler, jqXHR) {
    tries = 0; //reset counter - handling error response

    //normalize error message
    if (typeof err == "string") err = { 'Message': err };

    if (console && console.debug && console.dir) {
      console.debug("ERROR processing jQuery.msajax request.");
      console.dir({ 'details': { 'error': err, 'jqXHR':jqXHR } });
    }

    try {
      errorHandler(err, jqXHR);
    } catch (e) {}
    return;
  }


  function handleResponse(jqXHR, textStatus, onSuccess, onError, onRetry) {
    var ret = null;
    var reterr = null;
    try {
      //error from jqXHR
      if (textStatus == "error") {
        var errmsg = $.msajax.defaultErrorMessage || "Error retreiving data.";

        //check for error response from the server
        if (jqXHR.status >= 300 && jqXHR.status < 600) {
          return logError( jqXHR.statusText || msg, onError, jqXHR);
        }

        if (tries++ < 5) return onRetry();

        return logError( msg, onError, jqXHR);
      }

      //not an error response, reset try counter
      tries = 0;

      //check for a redirect from server (usually authentication token expiration).
      if (jqXHR.responseText.indexOf("|pageRedirect||") > 0) {
        location.href = decodeURIComponent(jqXHR.responseText.split("|pageRedirect||")[1].split("|")[0]).split('?')[0];
        return;
      }

      //parse response using ajax enabled parser (if available)
      ret = ((JSON && JSON.parseAjax) || $.parseJSON)(jqXHR.responseText);

      //invalid response
      if (!ret) throw jqXHR.responseText;  

      // d property wrap as of .Net 3.5
      if (ret.d) ret = ret.d;

      //has an error
      reterr = (ret && (ret.error || ret.Error)) || null; //specifically returned an "error"

      if (ret && ret.ExceptionType) { //Microsoft Webservice Exception Response
        reterr = ret
      }

    } catch (err) {
      reterr = {
        'Message': $.msajax.defaultErrorMessage || "Error retreiving data."
        ,'debug': err
      }
    }

    //perform final logic outside try/catch, was catching error in onSuccess/onError callbacks
    if (reterr) {
      logError(reterr, onError, jqXHR);
      return;
    }

    onSuccess(ret, jqXHR);
  }

} (jQuery));

NOTE: I also have a JSON.parseAjax method that is modified from json.org's JS file, that adds handling for the MS "/Date(...)/" dates...

The modified json2.js file isn't included, it uses the script based parser in the case of IE8, as there are instances where the native parser breaks when you extend the prototype of array and/or object, etc.

I've been considering revamping this code to implement the promises interfaces, but it's worked really well for me.

Modifying a subset of rows in a pandas dataframe

To replace multiples columns convert to numpy array using .values:

df.loc[df.A==0, ['B', 'C']] = df.loc[df.A==0, ['B', 'C']].values / 2

Remove menubar from Electron app

Most of the answers here are not valid for newer versions. With the version of 9.0 or upper, Menu.setApplicationMenu(null); should work. By the way, Menu exported from electron package: const {Menu} = require('electron');

How can I detect if this dictionary key exists in C#?

Here is a little something I cooked up today. Seems to work for me. Basically you override the Add method in your base namespace to do a check and then call the base's Add method in order to actually add it. Hope this works for you

using System;
using System.Collections.Generic;
using System.Collections;

namespace Main
{
    internal partial class Dictionary<TKey, TValue> : System.Collections.Generic.Dictionary<TKey, TValue>
    {
        internal new virtual void Add(TKey key, TValue value)
        {   
            if (!base.ContainsKey(key))
            {
                base.Add(key, value);
            }
        }
    }

    internal partial class List<T> : System.Collections.Generic.List<T>
    {
        internal new virtual void Add(T item)
        {
            if (!base.Contains(item))
            {
                base.Add(item);
            }
        }
    }

    public class Program
    {
        public static void Main()
        {
            Dictionary<int, string> dic = new Dictionary<int, string>();
            dic.Add(1,"b");
            dic.Add(1,"a");
            dic.Add(2,"c");
            dic.Add(1, "b");
            dic.Add(1, "a");
            dic.Add(2, "c");

            string val = "";
            dic.TryGetValue(1, out val);

            Console.WriteLine(val);
            Console.WriteLine(dic.Count.ToString());


            List<string> lst = new List<string>();
            lst.Add("b");
            lst.Add("a");
            lst.Add("c");
            lst.Add("b");
            lst.Add("a");
            lst.Add("c");

            Console.WriteLine(lst[2]);
            Console.WriteLine(lst.Count.ToString());
        }
    }
}

Filling a List with all enum values in Java

There is a constructor for ArrayList which is

ArrayList(Collection<? extends E> c) 

Now, EnumSet extends AbstractCollection so you can just do

ArrayList<Something> all = new ArrayList<Something>(enumSet)

Is there an XSLT name-of element?

Nobody did point the subtle difference in the semantics of the functions name() and local-name().

  • name(someNode) returns the full name of the node, and that includes the prefix and colon in case the node is an element or an attribute.
  • local-name(someNode) returns only the local name of the node, and that doesn't include the prefix and colon in case the node is an element or an attribute.

Therefore, in situations where a name may belong to two different namespaces, one must use the name() function in order for these names to be still distinguished.

And, BTW, it is possible to specify both functions without any argument:

name() is an abbreviation for name(.)

local-name() is an abbreviation for local-name(.)

Finally, do remember that not only elements and attributes have names, these two functions can also be used on PIs and on these they are identical).

JAVA How to remove trailing zeros from a double

Use a DecimalFormat object with a format string of "0.#".

Cannot enqueue Handshake after invoking quit

I think this issue is similar to mine:

  1. Connect to MySQL
  2. End MySQL service (should not quit node script)
  3. Start MySQL service, Node reconnects to MySQL
  4. Query the DB -> FAIL (Cannot enqueue Query after fatal error.)

I solved this issue by recreating a new connection with the use of promises (q).

mysql-con.js

'use strict';
var config          = require('./../config.js');
var colors          = require('colors');
var mysql           = require('mysql');
var q               = require('q');
var MySQLConnection = {};

MySQLConnection.connect = function(){
    var d = q.defer();
    MySQLConnection.connection = mysql.createConnection({
        host                : 'localhost',
        user                : 'root',
        password            : 'password',
        database            : 'database'
    });

    MySQLConnection.connection.connect(function (err) {
        if(err) {
            console.log('Not connected '.red, err.toString().red, ' RETRYING...'.blue);
            d.reject();
        } else {
            console.log('Connected to Mysql. Exporting..'.blue);
            d.resolve(MySQLConnection.connection);
        }
    });
    return d.promise;
};

module.exports = MySQLConnection;

mysqlAPI.js

var colors          = require('colors');
var mysqlCon        = require('./mysql-con.js');
mysqlCon.connect().then(function(con){
   console.log('connected!');
    mysql = con;
    mysql.on('error', function (err, result) {
        console.log('error occurred. Reconneting...'.purple);
        mysqlAPI.reconnect();
    });
    mysql.query('SELECT 1 + 1 AS solution', function (err, results) {
            if(err) console.log('err',err);
            console.log('Works bro ',results);
    });
});

mysqlAPI.reconnect = function(){
    mysqlCon.connect().then(function(con){
      console.log("connected. getting new reference");
        mysql = con;
        mysql.on('error', function (err, result) {
            mysqlAPI.reconnect();
        });
    }, function (error) {
      console.log("try again");
        setTimeout(mysqlAPI.reconnect, 2000);
    });
};

I hope this helps.

ASP.NET: HTTP Error 500.19 – Internal Server Error 0x8007000d

I had this problem with a brand new web service. Solved it by adding read-only access for Everyone on Properties->Security for the folder that the service was in.

Chart creating dynamically. in .net, c#

Try to include these lines on your code, after mych.Visible = true;:

ChartArea chA = new ChartArea();
mych.ChartAreas.Add(chA);

What does the 'L' in front a string mean in C++?

It means that it is a wide character, wchar_t.

Similar to 1L being a long value.

CSS: stretching background image to 100% width and height of screen?

You need to set the height of html to 100%

body {
    background-image:url("../images/myImage.jpg");
    background-repeat: no-repeat;
    background-size: 100% 100%;
}
html {
    height: 100%
}

http://jsfiddle.net/8XUjP/

Use async await with Array.map

You can use:

for await (let resolvedPromise of arrayOfPromises) {
  console.log(resolvedPromise)
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of

If you wish to use Promise.all() instead you can go for Promise.allSettled() So you can have better control over rejected promises.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled

Handling errors in Promise.all

To continue the Promise.all loop (even when a Promise rejects) I wrote a utility function which is called executeAllPromises. This utility function returns an object with results and errors.

The idea is that all Promises you pass to executeAllPromises will be wrapped into a new Promise which will always resolve. The new Promise resolves with an array which has 2 spots. The first spot holds the resolving value (if any) and the second spot keeps the error (if the wrapped Promise rejects).

As a final step the executeAllPromises accumulates all values of the wrapped promises and returns the final object with an array for results and an array for errors.

Here is the code:

_x000D_
_x000D_
function executeAllPromises(promises) {_x000D_
  // Wrap all Promises in a Promise that will always "resolve"_x000D_
  var resolvingPromises = promises.map(function(promise) {_x000D_
    return new Promise(function(resolve) {_x000D_
      var payload = new Array(2);_x000D_
      promise.then(function(result) {_x000D_
          payload[0] = result;_x000D_
        })_x000D_
        .catch(function(error) {_x000D_
          payload[1] = error;_x000D_
        })_x000D_
        .then(function() {_x000D_
          /* _x000D_
           * The wrapped Promise returns an array:_x000D_
           * The first position in the array holds the result (if any)_x000D_
           * The second position in the array holds the error (if any)_x000D_
           */_x000D_
          resolve(payload);_x000D_
        });_x000D_
    });_x000D_
  });_x000D_
_x000D_
  var errors = [];_x000D_
  var results = [];_x000D_
_x000D_
  // Execute all wrapped Promises_x000D_
  return Promise.all(resolvingPromises)_x000D_
    .then(function(items) {_x000D_
      items.forEach(function(payload) {_x000D_
        if (payload[1]) {_x000D_
          errors.push(payload[1]);_x000D_
        } else {_x000D_
          results.push(payload[0]);_x000D_
        }_x000D_
      });_x000D_
_x000D_
      return {_x000D_
        errors: errors,_x000D_
        results: results_x000D_
      };_x000D_
    });_x000D_
}_x000D_
_x000D_
var myPromises = [_x000D_
  Promise.resolve(1),_x000D_
  Promise.resolve(2),_x000D_
  Promise.reject(new Error('3')),_x000D_
  Promise.resolve(4),_x000D_
  Promise.reject(new Error('5'))_x000D_
];_x000D_
_x000D_
executeAllPromises(myPromises).then(function(items) {_x000D_
  // Result_x000D_
  var errors = items.errors.map(function(error) {_x000D_
    return error.message_x000D_
  }).join(',');_x000D_
  var results = items.results.join(',');_x000D_
  _x000D_
  console.log(`Executed all ${myPromises.length} Promises:`);_x000D_
  console.log(`— ${items.results.length} Promises were successful: ${results}`);_x000D_
  console.log(`— ${items.errors.length} Promises failed: ${errors}`);_x000D_
});
_x000D_
_x000D_
_x000D_

find first sequence item that matches a criterion

a=[100,200,300,400,500]
def search(b):
 try:
  k=a.index(b)
  return a[k] 
 except ValueError:
    return 'not found'
print(search(500))

it'll return the object if found else it'll return "not found"

Spring Test & Security: How to mock authentication?

Options to avoid using SecurityContextHolder in tests:

  • Option 1: use mocks - I mean mock SecurityContextHolder using some mock library - EasyMock for example
  • Option 2: wrap call SecurityContextHolder.get... in your code in some service - for example in SecurityServiceImpl with method getCurrentPrincipal that implements SecurityService interface and then in your tests you can simply create mock implementation of this interface that returns the desired principal without access to SecurityContextHolder.

Running javascript in Selenium using Python

If you move from iframes, you may get lost in your page, best way to execute some jquery without issue (with selenimum/python/gecko):

# 1) Get back to the main body page
driver.switch_to.default_content()

# 2) Download jquery lib file to your current folder manually & set path here
with open('./_lib/jquery-3.3.1.min.js', 'r') as jquery_js: 
    # 3) Read the jquery from a file
    jquery = jquery_js.read() 
    # 4) Load jquery lib
    driver.execute_script(jquery)
    # 5) Execute your command 
    driver.execute_script('$("#myId").click()')

Bash script prints "Command Not Found" on empty lines

On Bash for Windows I've tried incorrectly to run

run_me.sh 

without ./ at the beginning and got the same error.

For people with Windows background the correct form looks redundant:

./run_me.sh

Force git stash to overwrite added files

git stash show -p | git apply

and then git stash drop if you want to drop the stashed items.

How to use '-prune' option of 'find' in sh?

Beware that -prune does not prevent descending into any directory as some have said. It prevents descending into directories that match the test it's applied to. Perhaps some examples will help (see the bottom for a regex example). Sorry for this being so lengthy.

$ find . -printf "%y %p\n"    # print the file type the first time FYI
d .
f ./test
d ./dir1
d ./dir1/test
f ./dir1/test/file
f ./dir1/test/test
d ./dir1/scripts
f ./dir1/scripts/myscript.pl
f ./dir1/scripts/myscript.sh
f ./dir1/scripts/myscript.py
d ./dir2
d ./dir2/test
f ./dir2/test/file
f ./dir2/test/myscript.pl
f ./dir2/test/myscript.sh

$ find . -name test
./test
./dir1/test
./dir1/test/test
./dir2/test

$ find . -prune
.

$ find . -name test -prune
./test
./dir1/test
./dir2/test

$ find . -name test -prune -o -print
.
./dir1
./dir1/scripts
./dir1/scripts/myscript.pl
./dir1/scripts/myscript.sh
./dir1/scripts/myscript.py
./dir2

$ find . -regex ".*/my.*p.$"
./dir1/scripts/myscript.pl
./dir1/scripts/myscript.py
./dir2/test/myscript.pl

$ find . -name test -prune -regex ".*/my.*p.$"
(no results)

$ find . -name test -prune -o -regex ".*/my.*p.$"
./test
./dir1/test
./dir1/scripts/myscript.pl
./dir1/scripts/myscript.py
./dir2/test

$ find . -regex ".*/my.*p.$" -a -not -regex ".*test.*"
./dir1/scripts/myscript.pl
./dir1/scripts/myscript.py

$ find . -not -regex ".*test.*"                   .
./dir1
./dir1/scripts
./dir1/scripts/myscript.pl
./dir1/scripts/myscript.sh
./dir1/scripts/myscript.py
./dir2

Get index of clicked element in collection with jQuery

$('selector').click(function (event) {
    alert($(this).index());
});

jsfiddle

How to study design patterns?

Ask yourself these questions:

What do they do?

What do they decouple/couple?

When should you use them?

When should you not use them?

What missing language feature would make them go away?

What technical debt do you incur by using it?

Is there a simpler way to get the job done?

Changing text color onclick

   <p id="text" onclick="func()">
    Click on text to change
</p>
<script>
function func()
{
    document.getElementById("text").style.color="red";
    document.getElementById("text").style.font="calibri";
}
</script>

Big O, how do you calculate/approximate it?

If your cost is a polynomial, just keep the highest-order term, without its multiplier. E.g.:

O((n/2 + 1)*(n/2)) = O(n2/4 + n/2) = O(n2/4) = O(n2)

This doesn't work for infinite series, mind you. There is no single recipe for the general case, though for some common cases, the following inequalities apply:

O(log N) < O(N) < O(N log N) < O(N2) < O(Nk) < O(en) < O(n!)

Detecting locked tables (locked by LOCK TABLE)

This article describes how to get information about locked MySQL resources. mysqladmin debug might also be of some use.

Why would $_FILES be empty when uploading files to PHP?

As far as the HTML you appear to have set that part up correctly. You already have the enctype="multipart/form-data" which is very important to have on the form.

As far as your php.ini setup, sometimes on systems multiple php.ini files exist. Be sure you are editing the correct one. I know you said you have configured your php.ini file to have file uploads, but did you also set your upload_max_filesize and post_max_size to be larger than the file you are trying to upload? So you should have:

file_uploads = On; sounds like you already did this
post_max_size = 8M; change this higher if needed
upload_max_filesize = 8M; change this higher if needed

Does your directory: "c:\wamp\tmp" have both read and write permissions? Did you remember to restart Apache after you made the php.ini changes?


Oracle sqlldr TRAILING NULLCOLS required, but why?

The problem here is that you have defined ID as a field in your data file when what you want is to just use an expression without any data from the data file. You can fix this by defining ID as an expression (or a sequence in this case)

ID EXPRESSION "ID_SEQ.nextval"

or

ID SEQUENCE(count)

See: http://docs.oracle.com/cd/B28359_01/server.111/b28319/ldr_field_list.htm#i1008234 for all options

Jquery mouseenter() vs mouseover()

You see the behavior when your target element contains child elements:

http://jsfiddle.net/ZCWvJ/7/

Each time your mouse enters or leaves a child element, mouseover is triggered, but not mouseenter.

_x000D_
_x000D_
$('#my_div').bind("mouseover mouseenter", function(e) {_x000D_
  var el = $("#" + e.type);_x000D_
  var n = +el.text();_x000D_
  el.text(++n);_x000D_
});
_x000D_
#my_div {_x000D_
  padding: 0 20px 20px 0;_x000D_
  background-color: #eee;_x000D_
  margin-bottom: 10px;_x000D_
  width: 90px;_x000D_
  overflow: hidden;_x000D_
}_x000D_
_x000D_
#my_div>div {_x000D_
  float: left;_x000D_
  margin: 20px 0 0 20px;_x000D_
  height: 25px;_x000D_
  width: 25px;_x000D_
  background-color: #aaa;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>_x000D_
_x000D_
<div>MouseEnter: <span id="mouseenter">0</span></div>_x000D_
<div>MouseOver: <span id="mouseover">0</span></div>_x000D_
_x000D_
<div id="my_div">_x000D_
  <div></div>_x000D_
  <div></div>_x000D_
  <div></div>_x000D_
  <div></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to set button click effect in Android?

To make your item consistent with the system look and feel try referencing the system attribute android:attr/selectableItemBackground in your desired view's background or foreground tag:

<ImageView
    ...
    android:background="?android:attr/selectableItemBackground"      
    android:foreground="?android:attr/selectableItemBackground"
    ...
/>

Use both attributes to get desired effect before/after API level 23 respectively.

https://stackoverflow.com/a/11513474/4683601

error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’

C++03 3.10/1 says: "Every expression is either an lvalue or an rvalue." It's important to remember that lvalueness versus rvalueness is a property of expressions, not of objects.

Lvalues name objects that persist beyond a single expression. For example, obj , *ptr , ptr[index] , and ++x are all lvalues.

Rvalues are temporaries that evaporate at the end of the full-expression in which they live ("at the semicolon"). For example, 1729 , x + y , std::string("meow") , and x++ are all rvalues.

The address-of operator requires that its "operand shall be an lvalue". if we could take the address of one expression, the expression is an lvalue, otherwise it's an rvalue.

 &obj; //  valid
 &12;  //invalid

How to picture "for" loop in block representation of algorithm

What's a "block scheme"?

If I were drawing it, I might draw a box with "for each x in y" written in it.

If you're drawing a flowchart, there's always a loop with a decision box.

Nassi-Schneiderman diagrams have a loop construct you could use.

JAVA_HOME should point to a JDK not a JRE

In addition to sovas' response on how to add the JAVA_HOME variable, if it was working before and stopped working, ensure that the path still exists. I updated Java recently which deleted the old version, invalidating my JAVA_HOME environment variable.

How can I create a war file of my project in NetBeans?

Just check in you projects properties >build ->packaging WAR file compress.

Disabling submit button until all fields have values

This works well since all the inputs have to meet the condition of not null.

$(function () {
    $('#submits').attr('disabled', true);
    $('#input_5').change(function () {
        if ($('#input_1').val() != '' && $('#input_2').val() != '' && $('#input_3').val() != '' && $('#input_4').val() != '' && $('#input_5').val() != '') {
            $('#submit').attr('disabled', false);
        } else {
            $('#submit').attr('disabled', true);
        }
     });
 });

ImportError: No module named PyQt4

You have to check which Python you are using. I had the same problem because the Python I was using was not the same one that brew was using. In your command line:

  1. which python
    output: /usr/bin/python
  2. which brew
    output: /usr/local/bin/brew     //so they are different
  3. cd /usr/local/lib/python2.7/site-packages
  4. ls   //you can see PyQt4 and sip are here
  5. Now you need to add usr/local/lib/python2.7/site-packages to your python path.
  6. open ~/.bash_profile   //you will open your bash_profile file in your editor
  7. Add 'export PYTHONPATH=/usr/local/lib/python2.7/site-packages:$PYTHONPATH' to your bash file and save it
  8. Close your terminal and restart it to reload the shell
  9. python
  10. import PyQt4    // it is ok now

Gson library in Android Studio

If you are going to use it with Retrofit library, I suggest you to use Square's gson library as:

implementation 'com.squareup.retrofit2:converter-gson:2.4.0'

Syntax for a single-line Bash infinite while loop

while true; do foo; sleep 2; done

By the way, if you type it as a multiline (as you are showing) at the command prompt and then call the history with arrow up, you will get it on a single line, correctly punctuated.

$ while true
> do
>    echo "hello"
>    sleep 2
> done
hello
hello
hello
^C
$ <arrow up> while true; do    echo "hello";    sleep 2; done

versionCode vs versionName in Android Manifest

It is indeed based on versionCode and not on versionName. However, I noticed that changing the versionCode in AndroidManifest.xml wasn't enough with Android Studio - Gradle build system. I needed to change it in the build.gradle.

How to take backup of a single table in a MySQL database?

We can take a mysql dump of any particular table with any given condition like below

mysqldump -uusername -p -hhost databasename tablename --skip-lock-tables

If we want to add a specific where condition on table then we can use the following command

mysqldump -uusername -p -hhost databasename tablename --where="date=20140501" --skip-lock-tables

how to copy only the columns in a DataTable to another DataTable?

Datatable.Clone is slow for large tables. I'm currently using this:

Dim target As DataTable = 
    New DataView(source, "1=2", Nothing, DataViewRowState.CurrentRows)
    .ToTable()

Note that this only copies the structure of source table, not the data.

Only Add Unique Item To List

If your requirements are to have no duplicates, you should be using a HashSet.

HashSet.Add will return false when the item already exists (if that even matters to you).

You can use the constructor that @pstrjds links to below (or here) to define the equality operator or you'll need to implement the equality methods in RemoteDevice (GetHashCode & Equals).

How to putAll on Java hashMap contents of one to another, but not replace existing keys and values?

With Java 8 there is this API method to accomplish your requirement.

map.putIfAbsent(key, value)

If the specified key is not already associated with a value (or is mapped to null) associates it with the given value and returns null, else returns the current value.

ToString() function in Go

I prefer something like the following:

type StringRef []byte

func (s StringRef) String() string {
        return string(s[:])
}

…

// rather silly example, but ...
fmt.Printf("foo=%s\n",StringRef("bar"))

Nested objects in javascript, best practices

If you know the settings in advance you can define it in a single statement:

var defaultsettings = {
                        ajaxsettings : { "ak1" : "v1", "ak2" : "v2", etc. },
                        uisettings : { "ui1" : "v1", "ui22" : "v2", etc }
                      };

If you don't know the values in advance you can just define the top level object and then add properties:

var defaultsettings = { };
defaultsettings["ajaxsettings"] = {};
defaultsettings["ajaxsettings"]["somekey"] = "some value";

Or half-way between the two, define the top level with nested empty objects as properties and then add properties to those nested objects:

var defaultsettings = {
                        ajaxsettings : {  },
                        uisettings : {  }
                      };

defaultsettings["ajaxsettings"]["somekey"] = "some value";
defaultsettings["uisettings"]["somekey"] = "some value";

You can nest as deep as you like using the above techniques, and anywhere that you have a string literal in the square brackets you can use a variable:

var keyname = "ajaxsettings";
var defaultsettings = {};
defaultsettings[keyname] = {};
defaultsettings[keyname]["some key"] = "some value";

Note that you can not use variables for key names in the { } literal syntax.

How do I add python3 kernel to jupyter (IPython)

None of the other answers were working for me immediately on ElementaryOS Freya (based on Ubuntu 14.04); I was getting the

[TerminalIPythonApp] WARNING | File not found: 'kernelspec'

error that quickbug described under Matt's answer. I had to first do:

sudo apt-get install pip3, then

sudo pip3 install ipython[all]

At that point you can then run the commands that Matt suggested; namely: ipython kernelspec install-self and ipython3 kernelspec install-self

Now when I launch ipython notebook and then open a notebook, I am able to select the Python 3 kernel from the Kernel menu.

Get current working directory in a Qt application

I'm running Qt 5.5 under Windows and the default constructor of QDir appears to pick up the current working directory, not the application directory.

I'm not sure if the getenv PWD will work cross-platform and I think it is set to the current working directory when the shell launched the application and doesn't include any working directory changes done by the app itself (which might be why the OP is seeing this behavior).

So I thought I'd add some other ways that should give you the current working directory (not the application's binary location):

// using where a relative filename will end up
QFileInfo fi("temp");
cout << fi.absolutePath() << endl;

// explicitly using the relative name of the current working directory
QDir dir(".");
cout << dir.absolutePath() << endl;

How to find my realm file?

I found my realm file by issuing this command in Terminal: sudo find / -name "*.realm".

Hope this helps!

Check to see if python script is running

Rather than developing your own PID file solution (which has more subtleties and corner cases than you might think), have a look at supervisord -- this is a process control system that makes it easy to wrap job control and daemon behaviors around an existing Python script.

C/C++ include header file order

I'm pretty sure this isn't a recommended practice anywhere in the sane world, but I like to line system includes up by filename length, sorted lexically within the same length. Like so:

#include <set>
#include <vector>
#include <algorithm>
#include <functional>

I think it's a good idea to include your own headers before other peoples, to avoid the shame of include-order dependency.

Why I get 411 Length required error?

When you make a POST HttpWebRequest, you must specify the length of the data you are sending, something like:

string data = "something you need to send"
byte[] postBytes = Encoding.ASCII.GetBytes(data);
request.ContentLength = postBytes.Length;

if you are not sending any data, just set it to 0, that means you just have to add to your code this line:

request.ContentLength = 0;

Usually, if you are not sending any data, chosing the GET method instead is wiser, as you can see in the HTTP RFC

Could not load file or assembly 'Newtonsoft.Json' or one of its dependencies. Manifest definition does not match the assembly reference

I had the same issue on a Test Project that had reference to an MVC 5 project. This happened after I merged with an MVC 5 project. I fixed it by installing Visual studio 2012 updates as explained here in Andre's response.

  • In your visual studio go to
    1. Tools> Extensions And Updates
    2. Select "Updates" in the accordion list on the left.
    3. Select "Product Updates".
    4. Update to the newest version

What is the difference between Python and IPython?

Compared to Python, IPython (created by Fernando Perez in 2001) can do every thing what python can do. Ipython provides even extra features like tab-completion, testing, debugging, system calls and many other features. You can think IPython as a powerful interface to the Python language.

You can install Ipython using pip - pip install ipython

You can run Ipython by typing ipython in your terminal window.

Getting error: ISO C++ forbids declaration of with no type

You forgot the return types in your member function definitions:

int ttTree::ttTreeInsert(int value) { ... }
^^^               

and so on.

AngularJS ngClass conditional

use this

<div ng-class="{states}[condition]"></div>

for example if the condition is [2 == 2], states are {true: '...', false: '...'}

<div ng-class="{true: 'ClassA', false: 'ClassB'}[condition]"></div>

Add image in title bar

That method will not work. The <title> only supports plain text. You will need to create an .ico image with the filename of favicon.ico and save it into the root folder of your site (where your default page is).

Alternatively, you can save the icon where ever you wish and call it whatever you want, but simply insert the following code into the <head> section of your HTML and reference your icon:

<link rel="shortcut icon" href="your_image_path_and_name.ico" />

You can use Photoshop (with a plug in) or GIMP (free) to create an .ico file, or you can just use IcoFX, which is my personal favourite as it is really easy to use and does a great job (you can get an older version of the software for free from download.com).

Update 1: You can also use a number of online tools to create favicons such as ConvertIcon, which I've used successfully. There are other free online tools available now too, which do the same (accessible by a simple Google search), but also generate other icons such as the Windows 8/10 Start Menu icons and iOS App Icons.

Update 2: You can also use .png images as icons providing IE11 is the only version of IE you need to support. You just need to reference them using the HTML code above. Note that IE10 and older still require .ico files.

Update 3: You can now use Emoji characters in the title field. On Windows 10, it should generally fall back and use the Segoe UI Emoji font and display nicely, however you'll need to test and see how other systems support and display your chosen emoji, as not all devices may have the same Emoji available.

ImportError: No module named matplotlib.pyplot

Working on the django project and faced same problem, This is what I did. Check if you have metaplotlib already simply by writing pip show metaplotlib in the python terminal.

  1. If dont, run the command pip install metaplotlib.(make sure you have pip downloaded)
  2. Run the command pip show metaplotlib again.
  3. If the library is successfully downloaded, you can run your project (py manage.py runserver)

How to subtract days from a plain Date?

_x000D_
_x000D_
function addDays (date, daysToAdd) {_x000D_
  var _24HoursInMilliseconds = 86400000;_x000D_
  return new Date(date.getTime() + daysToAdd * _24HoursInMilliseconds);_x000D_
};_x000D_
_x000D_
var now = new Date();_x000D_
_x000D_
var yesterday = addDays(now, - 1);_x000D_
_x000D_
var tomorrow = addDays(now, 1);
_x000D_
_x000D_
_x000D_

Flutter - Layout a Grid

GridView is used for implementing material grid lists. If you know you have a fixed number of items and it's not very many (16 is fine), you can use GridView.count. However, you should note that a GridView is scrollable, and if that isn't what you want, you may be better off with just rows and columns.

screenshot

import 'dart:collection';
import 'package:flutter/scheduler.dart';
import 'package:flutter/material.dart';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/foundation.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.orange,
      ),
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget{
  @override
  Widget build(BuildContext context){
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Grid Demo'),
      ),
      body: new GridView.count(
        crossAxisCount: 4,
        children: new List<Widget>.generate(16, (index) {
          return new GridTile(
            child: new Card(
              color: Colors.blue.shade200,
              child: new Center(
                child: new Text('tile $index'),
              )
            ),
          );
        }),
      ),
    );
  }
}

How to generate unique id in MySQL?

For uniqueness what I do is I take the Unix timestamp and append a random string to it and use that.

Java Thread Example?

Here is a simple example:

ThreadTest.java

public class ThreadTest
{
   public static void main(String [] args)
   {
      MyThread t1 = new MyThread(0, 3, 300);
      MyThread t2 = new MyThread(1, 3, 300);
      MyThread t3 = new MyThread(2, 3, 300);

      t1.start();
      t2.start();
      t3.start();
   }
}

MyThread.java

public class MyThread extends Thread
{
   private int startIdx, nThreads, maxIdx;

   public MyThread(int s, int n, int m)
   {
      this.startIdx = s;
      this.nThreads = n;
      this.maxIdx = m;
   }

   @Override
   public void run()
   {
      for(int i = this.startIdx; i < this.maxIdx; i += this.nThreads)
      {
         System.out.println("[ID " + this.getId() + "] " + i);
      }
   }
}

And some output:

[ID 9] 1
[ID 10] 2
[ID 8] 0
[ID 10] 5
[ID 9] 4
[ID 10] 8
[ID 8] 3
[ID 10] 11
[ID 10] 14
[ID 10] 17
[ID 10] 20
[ID 10] 23

An explanation - Each MyThread object tries to print numbers from 0 to 300, but they are only responsible for certain regions of that range. I chose to split it by indices, with each thread jumping ahead by the number of threads total. So t1 does index 0, 3, 6, 9, etc.

Now, without IO, trivial calculations like this can still look like threads are executing sequentially, which is why I just showed the first part of the output. On my computer, after this output thread with ID 10 finishes all at once, followed by 9, then 8. If you put in a wait or a yield, you can see it better:

MyThread.java

System.out.println("[ID " + this.getId() + "] " + i);
Thread.yield();

And the output:

[ID 8] 0
[ID 9] 1
[ID 10] 2
[ID 8] 3
[ID 9] 4
[ID 8] 6
[ID 10] 5
[ID 9] 7

Now you can see each thread executing, giving up control early, and the next executing.

How to get current user in asp.net core

Have another way of getting current user in Asp.NET Core - and I think I saw it somewhere here, on SO ^^

// Stores UserManager
private readonly UserManager<ApplicationUser> _manager; 

// Inject UserManager using dependency injection.
// Works only if you choose "Individual user accounts" during project creation.
public DemoController(UserManager<ApplicationUser> manager)  
{  
    _manager = manager;  
}

// You can also just take part after return and use it in async methods.
private async Task<ApplicationUser> GetCurrentUser()  
{  
    return await _manager.GetUserAsync(HttpContext.User);  
}  

// Generic demo method.
public async Task DemoMethod()  
{  
    var user = await GetCurrentUser(); 
    string userEmail = user.Email; // Here you gets user email 
    string userId = user.Id;
}  

That code goes to controller named DemoController. Won't work without both await (won't compile) ;)

How to hide element label by element id in CSS?

If you don't care about IE6 users, use the equality attribute selector.

label[for="foo"] { display:none; }

How do you test to see if a double is equal to NaN?

Use the static Double.isNaN(double) method, or your Double's .isNaN() method.

// 1. static method
if (Double.isNaN(doubleValue)) {
    ...
}
// 2. object's method
if (doubleObject.isNaN()) {
    ...
}

Simply doing:

if (var == Double.NaN) {
    ...
}

is not sufficient due to how the IEEE standard for NaN and floating point numbers is defined.

File upload along with other object in Jersey restful web service

The request type is multipart/form-data and what you are sending is essentially form fields that go out as bytes with content boundaries separating different form fields.To send an object representation as form field (string), you can send a serialized form from the client that you can then deserialize on the server.

After all no programming environment object is actually ever traveling on the wire. The programming environment on both side are just doing automatic serialization and deserialization that you can also do. That is the cleanest and programming environment quirks free way to do it.

As an example, here is a javascript client posting to a Jersey example service,

submitFile(){

    let data = new FormData();
    let account = {
        "name": "test account",
        "location": "Bangalore"
    }

    data.append('file', this.file);
    data.append("accountKey", "44c85e59-afed-4fb2-884d-b3d85b051c44");
    data.append("device", "test001");
    data.append("account", JSON.stringify(account));
    
    let url = "http://localhost:9090/sensordb/test/file/multipart/upload";

    let config = {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    }

    axios.post(url, data, config).then(function(data){
        console.log('SUCCESS!!');
        console.log(data.data);
    }).catch(function(){
        console.log('FAILURE!!');
    });
},

Here the client is sending a file, 2 form fields (strings) and an account object that has been stringified for transport. here is how the form fields look on the wire,

enter image description here

On the server, you can just deserialize the form fields the way you see fit. To finish this trivial example,

    @POST
@Path("/file/multipart/upload")
@Consumes({MediaType.MULTIPART_FORM_DATA})
public Response uploadMultiPart(@Context ContainerRequestContext requestContext,
        @FormDataParam("file") InputStream fileInputStream,
        @FormDataParam("file") FormDataContentDisposition cdh,
        @FormDataParam("accountKey") String accountKey,
        @FormDataParam("account") String json)  {
    

    
    System.out.println(cdh.getFileName());
    System.out.println(cdh.getName());
    System.out.println(accountKey);
    
    try {
        Account account = Account.deserialize(json);
        System.out.println(account.getLocation());
        System.out.println(account.getName());
        
    } catch (Exception e) {
        e.printStackTrace();
    }
    
    return Response.ok().build();
    
}

Check whether a string matches a regex in JS

You can use match() as well:

if (str.match(/^([a-z0-9]{5,})$/)) {
    alert("match!");
}

But test() seems to be faster as you can read here.

Important difference between match() and test():

match() works only with strings, but test() works also with integers.

12345.match(/^([a-z0-9]{5,})$/); // ERROR
/^([a-z0-9]{5,})$/.test(12345);  // true
/^([a-z0-9]{5,})$/.test(null);   // false

// Better watch out for undefined values
/^([a-z0-9]{5,})$/.test(undefined); // true

How to change the date format of a DateTimePicker in vb.net

You need to set the Format of the DateTimePicker to Custom and then assign the CustomFormat.

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    DateTimePicker1.Format = DateTimePickerFormat.Custom
    DateTimePicker1.CustomFormat = "dd/MM/yyyy"
End Sub

Converting integer to binary in python

Just another idea:

>>> bin(6)[2:].zfill(8)
'00000110'

Shorter way via string interpolation (Python 3.6+):

>>> f'{6:08b}'
'00000110'

What are the rules for calling the superclass constructor?

Everybody mentioned a constructor call through an initialization list, but nobody said that a parent class's constructor can be called explicitly from the derived member's constructor's body. See the question Calling a constructor of the base class from a subclass' constructor body, for example. The point is that if you use an explicit call to a parent class or super class constructor in the body of a derived class, this is actually just creating an instance of the parent class and it is not invoking the parent class constructor on the derived object. The only way to invoke a parent class or super class constructor on a derived class' object is through the initialization list and not in the derived class constructor body. So maybe it should not be called a "superclass constructor call". I put this answer here because somebody might get confused (as I did).

UnicodeEncodeError: 'ascii' codec can't encode character at special name

Try setting the system default encoding as utf-8 at the start of the script, so that all strings are encoded using that.

Example -

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

The above should set the default encoding as utf-8 .