Programs & Examples On #File location

How to get the current working directory using python 3?

It seems that IDLE changes its current working dir to location of the script that is executed, while when running the script using cmd doesn't do that and it leaves CWD as it is.

To change current working dir to the one containing your script you can use:

import os
os.chdir(os.path.dirname(__file__))
print(os.getcwd())

The __file__ variable is available only if you execute script from file, and it contains path to the file. More on it here: Python __file__ attribute absolute or relative?

Where are the recorded macros stored in Notepad++?

For Windows 7 macros are stored at C:\Users\Username\AppData\Roaming\Notepad++\shortcuts.xml.

jQuery select option elements by value

$("#h273yrjdfhgsfyiruwyiywer").children('[value="' + i + '"]').prop("selected", true);

Get immediate first child element

Both these will give you the first child node:

console.log(parentElement.firstChild); // or
console.log(parentElement.childNodes[0]);

If you need the first child that is an element node then use:

console.log(parentElement.children[0]);

Edit

Ah, I see your problem now; parentElement is an array.

If you know that getElementsByClassName will only return one result, which it seems you do, you should use [0] to dearray (yes, I made that word up) the element:

var parentElement = document.getElementsByClassName("uniqueClassName")[0];

Entity Framework 5 Updating a Record

public interface IRepository
{
    void Update<T>(T obj, params Expression<Func<T, object>>[] propertiesToUpdate) where T : class;
}

public class Repository : DbContext, IRepository
{
    public void Update<T>(T obj, params Expression<Func<T, object>>[] propertiesToUpdate) where T : class
    {
        Set<T>().Attach(obj);
        propertiesToUpdate.ToList().ForEach(p => Entry(obj).Property(p).IsModified = true);
        SaveChanges();
    }
}

Best way to encode text data for XML

Microsoft's AntiXss library AntiXssEncoder Class in System.Web.dll has methods for this:

AntiXss.XmlEncode(string s)
AntiXss.XmlAttributeEncode(string s)

it has HTML as well:

AntiXss.HtmlEncode(string s)
AntiXss.HtmlAttributeEncode(string s)

How to copy a file to a remote server in Python using SCP or SSH?

You can do something like this, to handle the host key checking as well

import os
os.system("sshpass -p password scp -o StrictHostKeyChecking=no local_file_path username@hostname:remote_path")

Java HTML Parsing

The HTMLParser project (http://htmlparser.sourceforge.net/) might be a possibility. It seems to be pretty decent at handling malformed HTML. The following snippet should do what you need:

Parser parser = new Parser(htmlInput);
CssSelectorNodeFilter cssFilter = 
    new CssSelectorNodeFilter("DIV.targetClassName");
NodeList nodes = parser.parse(cssFilter);

Align inline-block DIVs to top of container element

Because the vertical-align is set at baseline as default.

Use vertical-align:top instead:

.small{
    display: inline-block;
    width: 40%;
    height: 30%;
    border: 1px black solid;
    background: aliceblue;   
    vertical-align:top;
}

http://jsfiddle.net/Lighty_46/RHM5L/9/

Or as @f00644 said you could apply float to the child elements as well.

Magento How to debug blank white screen

This could be as simple as a template conflict. Revert to default template in System/Configuration/Design/Themes.

Resize external website content to fit iFrame width

Tip for 1 website resizing the height. But you can change to 2 websites.

Here is my code to resize an iframe with an external website. You need insert a code into the parent (with iframe code) page and in the external website as well, so, this won't work with you don't have access to edit the external website.

  • local (iframe) page: just insert a code snippet
  • remote (external) page: you need a "body onload" and a "div" that holds all contents. And body needs to be styled to "margin:0"

Local:

<IFRAME STYLE="width:100%;height:1px" SRC="http://www.remote-site.com/" FRAMEBORDER="no" BORDER="0" SCROLLING="no" ID="estframe"></IFRAME>

<SCRIPT>
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent,function(e) {
  if (e.data.substring(0,3)=='frm') document.getElementById('estframe').style.height = e.data.substring(3) + 'px';
},false);
</SCRIPT>

You need this "frm" prefix to avoid problems with other embeded codes like Twitter or Facebook plugins. If you have a plain page, you can remove the "if" and the "frm" prefix on both pages (script and onload).

Remote:

You need jQuery to accomplish about "real" page height. I cannot realize how to do with pure JavaScript since you'll have problem when resize the height down (higher to lower height) using body.scrollHeight or related. For some reason, it will return always the biggest height (pre-redimensioned).

<BODY onload="parent.postMessage('frm'+$('#master').height(),'*')" STYLE="margin:0">
<SCRIPT SRC="path-to-jquery/jquery.min.js"></SCRIPT>
<DIV ID="master">
your content
</DIV>

So, parent page (iframe) has a 1px default height. The script inserts a "wait for message/event" from the iframe. When a message (post message) is received and the first 3 chars are "frm" (to avoid the mentioned problem), will get the number from 4th position and set the iframe height (style), including 'px' unit.

The external site (loaded in the iframe) will "send a message" to the parent (opener) with the "frm" and the height of the main div (in this case id "master"). The "*" in postmessage means "any source".

Hope this helps. Sorry for my english.

Creating object with dynamic keys

You can't define an object literal with a dynamic key. Do this :

var o = {};
o[key] = value;
return o;

There's no shortcut (edit: there's one now, with ES6, see the other answer).

java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader

This is worked for me

If your having .so file in armeabi then mention inside ndk that folder alone.

defaultConfig {
        applicationId "com.xxx.yyy"
        minSdkVersion 17
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        renderscriptTargetApi 26
        renderscriptSupportModeEnabled true
        ndk {
            abiFilters "armeabi"
        }
    }

and then use this

android.useDeprecatedNdk=true;

in gradle.properties file

Open a Web Page in a Windows Batch FIle

start did not work for me.

I used:

firefox http://www.stackoverflow.com

or

chrome http://www.stackoverflow.com

Obviously not great for distributing it, but if you're using it for a specific machine, it should work fine.

How to draw vertical lines on a given plot in matplotlib

matplotlib.pyplot.vlines vs. matplotlib.pyplot.axvline

  • The difference is that vlines accepts 1 or more locations for x, while axvline permits one location.
    • Single location: x=37
    • Multiple locations: x=[37, 38, 39]
  • vlines takes ymin and ymax as a position on the y-axis, while axvline takes ymin and ymax as a percentage of the y-axis range.
    • When passing multiple lines to vlines, pass a list to ymin and ymax.
  • If you're plotting a figure with something like fig, ax = plt.subplots(), then replace plt.vlines or plt.axvline with ax.vlines or ax.axvline, respectively.
import numpy as np
import matplotlib.pyplot as plt

xs = np.linspace(1, 21, 200)

plt.figure(figsize=(10, 7))

# only one line may be specified; full height
plt.axvline(x=36, color='b', label='axvline - full height')

# only one line may be specified; ymin & ymax spedified as a percentage of y-range
plt.axvline(x=36.25, ymin=0.05, ymax=0.95, color='b', label='axvline - % of full height')

# multiple lines all full height
plt.vlines(x=[37, 37.25, 37.5], ymin=0, ymax=len(xs), colors='purple', ls='--', lw=2, label='vline_multiple - full height')

# multiple lines with varying ymin and ymax
plt.vlines(x=[38, 38.25, 38.5], ymin=[0, 25, 75], ymax=[200, 175, 150], colors='teal', ls='--', lw=2, label='vline_multiple - partial height')

# single vline with full ymin and ymax
plt.vlines(x=39, ymin=0, ymax=len(xs), colors='green', ls=':', lw=2, label='vline_single - full height')

# single vline with specific ymin and ymax
plt.vlines(x=39.25, ymin=25, ymax=150, colors='green', ls=':', lw=2, label='vline_single - partial height')

# place legend outside
plt.legend(bbox_to_anchor=(1.0, 1), loc='upper left')

plt.show()

enter image description here

Rails: Default sort order for a rails model?

default_scope

This works for Rails 4+:

class Book < ActiveRecord::Base
  default_scope { order(created_at: :desc) }
end

For Rails 2.3, 3, you need this instead:

default_scope order('created_at DESC')

For Rails 2.x:

default_scope :order => 'created_at DESC'

Where created_at is the field you want the default sorting to be done on.

Note: ASC is the code to use for Ascending and DESC is for descending (desc, NOT dsc !).

scope

Once you're used to that you can also use scope:

class Book < ActiveRecord::Base
  scope :confirmed, :conditions => { :confirmed => true }
  scope :published, :conditions => { :published => true }
end

For Rails 2 you need named_scope.

:published scope gives you Book.published instead of Book.find(:published => true).

Since Rails 3 you can 'chain' those methods together by concatenating them with periods between them, so with the above scopes you can now use Book.published.confirmed.

With this method, the query is not actually executed until actual results are needed (lazy evaluation), so 7 scopes could be chained together but only resulting in 1 actual database query, to avoid performance problems from executing 7 separate queries.

You can use a passed in parameter such as a date or a user_id (something that will change at run-time and so will need that 'lazy evaluation', with a lambda, like this:

scope :recent_books, lambda 
  { |since_when| where("created_at >= ?", since_when) }
  # Note the `where` is making use of AREL syntax added in Rails 3.

Finally you can disable default scope with:

Book.with_exclusive_scope { find(:all) } 

or even better:

Book.unscoped.all

which will disable any filter (conditions) or sort (order by).

Note that the first version works in Rails2+ whereas the second (unscoped) is only for Rails3+


So ... if you're thinking, hmm, so these are just like methods then..., yup, that's exactly what these scopes are!
They are like having def self.method_name ...code... end but as always with ruby they are nice little syntactical shortcuts (or 'sugar') to make things easier for you!

In fact they are Class level methods as they operate on the 1 set of 'all' records.

Their format is changing however, with rails 4 there are deprecation warning when using #scope without passing a callable object. For example scope :red, where(color: 'red') should be changed to scope :red, -> { where(color: 'red') }.

As a side note, when used incorrectly, default_scope can be misused/abused.
This is mainly about when it gets used for actions like where's limiting (filtering) the default selection (a bad idea for a default) rather than just being used for ordering results.
For where selections, just use the regular named scopes. and add that scope on in the query, e.g. Book.all.published where published is a named scope.

In conclusion, scopes are really great and help you to push things up into the model for a 'fat model thin controller' DRYer approach.

Select DISTINCT individual columns in django?

It's quite simple actually if you're using PostgreSQL, just use distinct(columns) (documentation).

Productorder.objects.all().distinct('category')

Note that this feature has been included in Django since 1.4

Manually Set Value for FormBuilder Control

You could try this:

deptSelected(selected: { id: string; text: string }) {
  console.log(selected) // Shows proper selection!

  // This is how I am trying to set the value
  this.form.controls['dept'].updateValue(selected.id);
}

For more details, you could have a look at the corresponding JS Doc regarding the second parameter of the updateValue method: https://github.com/angular/angular/blob/master/modules/angular2/src/common/forms/model.ts#L269.

How to use goto statement correctly

Java also does not use line numbers, which is a necessity for a GOTO function. Unlike C/C++, Java does not have goto statement, but java supports label. The only place where a label is useful in Java is right before nested loop statements. We can specify label name with break to break out a specific outer loop.

How to implement history.back() in angular.js

In AngularJS2 I found a new way, maybe is just the same thing but in this new version :

import {Router, RouteConfig, ROUTER_DIRECTIVES, Location} from 'angular2/router'; 

(...)

constructor(private _router: Router, private _location: Location) {}

onSubmit() {
    (...)
    self._location.back();
}

After my function, I can see that my application is going to the previous page usgin location from angular2/router.

https://angular.io/docs/ts/latest/api/common/index/Location-class.html

Calling JMX MBean method from a shell script

A little risky, but you could run a curl POST command with the values from the form from the JMX console, its URL and http authentication (if required):

curl -s -X POST --user 'myuser:mypass'
  --data "action=invokeOp&name=App:service=ThisServiceOp&methodIndex=3&arg0=value1&arg1=value1&submit=Invoke"
  http://yourhost.domain.com/jmx-console/HtmlAdaptor

Beware: the method index may change with changes to the software. And the implementation of the web form could change.

The above is based on source of the JMX service page for the operation you want to perform:

http://yourhost.domain.com/jmx-console/HtmlAdaptor?action=inspectMBean&name=YourJMXServiceName

Source of the form:

form method="post" action="HtmlAdaptor">
   <input type="hidden" name="action" value="invokeOp">
   <input type="hidden" name="name" value="App:service=ThisServiceOp">
   <input type="hidden" name="methodIndex" value="3">
   <hr align='left' width='80'>
   <h4>void ThisOperation()</h4>
   <p>Operation exposed for management</p>
    <table cellspacing="2" cellpadding="2" border="1">
        <tr class="OperationHeader">
            <th>Param</th>
            <th>ParamType</th>
            <th>ParamValue</th>
            <th>ParamDescription</th>
        </tr>
        <tr>
            <td>p1</td>
           <td>java.lang.String</td>
         <td> 
            <input type="text" name="arg0">
         </td>
         <td>(no description)</td>
        </tr>
        <tr>
            <td>p2</td>
           <td>arg1Type</td>
         <td> 
            <input type="text" name="arg1">
         </td>
         <td>(no description)</td>
        </tr>
    </table>
    <input type="submit" value="Invoke">
</form>

Iterating through array - java

If you are using an array (and purely an array), the lookup of "contains" is O(N), because worst case, you must iterate the entire array. Now if the array is sorted you can use a binary search, which reduces the search time to log(N) with the overhead of the sort.

If this is something that is invoked repeatedly, place it in a function:

private boolean inArray(int[] array, int value)
{  
     for (int i = 0; i < array.length; i++)
     {
        if (array[i] == value) 
        {
            return true;
        }
     }
    return false;  
}  

PDOException “could not find driver”

I had the same problem during running tests with separate php.ini. I had to add these lines to my own php.ini file:

[PHP]
extension = mysqlnd.so
extension = pdo.so
extension = pdo_mysql.so

Notice: Exactly in this order

Set focus on TextBox in WPF from view model

public class DummyViewModel : ViewModelBase
    {
        private bool isfocused= false;
        public bool IsFocused
        {
            get
            {
                return isfocused;
            }
            set
            {
                isfocused= value;
                OnPropertyChanged("IsFocused");
            }
        }
    }

Java - Check if input is a positive integer, negative integer, natural number and so on.

(You should you as Else-If statement to check the for the three different state (positive, negative, 0)

Here is a simple example (excludes the possibility of non-integer values)

  import java.util.Scanner;

  public class Compare {

   public static void main(String[] args) { 

    Scanner input = new Scanner(System.in);

    System.out.print("Enter a number: ");
    int number = input.nextInt();

    if( number == 0)
    { System.out.println("Number is equal to zero"); }
    else if (number > 0)
    { System.out.println("Number is positive"); }
    else 
    { System.out.println("Number is negative"); }


  }
 }

How to get all the AD groups for a particular user?

I would like to say that Microsoft LDAP has some special ways to search recursively for all of memberships of a user.

  1. The Matching Rule you can specify for the "member" attribute. In particular, using the Microsoft Exclusive LDAP_MATCHING_RULE_IN_CHAIN rule for "member" attribute allows recursive/nested membership searching. The rule is used when you add it after the member attribute. Ex. (member:1.2.840.113556.1.4.1941:= XXXXX )

  2. For the same Domain as the Account, The filter can use <SID=S-1-5-21-XXXXXXXXXXXXXXXXXXXXXXX> instead of an Accounts DistinguishedName attribute which is very handy to use cross domain if needed. HOWEVER it appears you need to use the ForeignSecurityPrincipal <GUID=YYYY> as it will not resolve your SID as it appears the <SID=> tag does not consider ForeignSecurityPrincipal object type. You can use the ForeignSecurityPrincipal DistinguishedName as well.

Using this knowledge, you can LDAP query those hard to get memberships, such as the "Domain Local" groups an Account is a member of but unless you looked at the members of the group, you wouldn't know if user was a member.

//Get Direct+Indirect Memberships of User (where SID is XXXXXX)

string str = "(& (objectCategory=group)(member:1.2.840.113556.1.4.1941:=<SID=XXXXXX>) )";

//Get Direct+Indirect **Domain Local** Memberships of User (where SID is XXXXXX)

string str2 = "(& (objectCategory=group)(|(groupType=-2147483644)(groupType=4))(member:1.2.840.113556.1.4.1941:=<SID=XXXXXX>) )";

//TAA DAA



Feel free to try these LDAP queries after substituting the SID of a user you want to retrieve all group memberships of. I figure this is similiar if not the same query as what the PowerShell Command Get-ADPrincipalGroupMembership uses behind the scenes. The command states "If you want to search for local groups in another domain, use the ResourceContextServer parameter to specify the alternate server in the other domain."

If you are familiar enough with C# and Active Directory, you should know how to perform an LDAP search using the LDAP queries provided.

Additional Documentation:

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

Yep, just use the trailing slash to recursively pull the directory. Works for me with Nexus 5 and current version of adb (March 2014).

Read XML Attribute using XmlDocument

You should look into XPath. Once you start using it, you'll find its a lot more efficient and easier to code than iterating through lists. It also lets you directly get the things you want.

Then the code would be something similar to

string attrVal = doc.SelectSingleNode("/MyConfiguration/@SuperNumber").Value;

Note that XPath 3.0 became a W3C Recommendation on April 8, 2014.

htaccess redirect all pages to single page

If your aim is to redirect all pages to a single maintenance page (as the title could suggest also this), then use:

RewriteEngine on
RewriteCond %{REQUEST_URI} !/maintenance.php$ 
RewriteCond %{REMOTE_HOST} !^000\.000\.000\.000
RewriteRule $ /maintenance.php [R=302,L] 

Where 000 000 000 000 should be replaced by your ip adress.

Source:

http://www.techiecorner.com/97/redirect-to-maintenance-page-during-upgrade-using-htaccess/

How to programmatically take a screenshot on Android?

For system applications only!

Process process;
process = Runtime.getRuntime().exec("screencap -p " + outputPath);
process.waitFor();

Note: System applications don't need to run "su" to execute this command.

How to jQuery clone() and change id?

I have created a generalised solution. The function below will change ids and names of cloned object. In most cases, you will need the row number so Just add "data-row-id" attribute to the object.

function renameCloneIdsAndNames( objClone ) {

    if( !objClone.attr( 'data-row-id' ) ) {
        console.error( 'Cloned object must have \'data-row-id\' attribute.' );
    }

    if( objClone.attr( 'id' ) ) {
        objClone.attr( 'id', objClone.attr( 'id' ).replace( /\d+$/, function( strId ) { return parseInt( strId ) + 1; } ) );
    }

    objClone.attr( 'data-row-id', objClone.attr( 'data-row-id' ).replace( /\d+$/, function( strId ) { return parseInt( strId ) + 1; } ) );

    objClone.find( '[id]' ).each( function() {

        var strNewId = $( this ).attr( 'id' ).replace( /\d+$/, function( strId ) { return parseInt( strId ) + 1; } );

        $( this ).attr( 'id', strNewId );

        if( $( this ).attr( 'name' ) ) {
            var strNewName  = $( this ).attr( 'name' ).replace( /\[\d+\]/g, function( strName ) {
                strName = strName.replace( /[\[\]']+/g, '' );
                var intNumber = parseInt( strName ) + 1;
                return '[' + intNumber + ']'
            } );
            $( this ).attr( 'name', strNewName );
        }
    });

    return objClone;
}

How can I check if my python object is a number?

Use Number from the numbers module to test isinstance(n, Number) (available since 2.6).

isinstance(n, numbers.Number)

Here it is in action with various kinds of numbers and one non-number:

>>> from numbers import Number
... from decimal import Decimal
... from fractions import Fraction
... for n in [2, 2.0, Decimal('2.0'), complex(2,0), Fraction(2,1), '2']:
...     print '%15s %s' % (n.__repr__(), isinstance(n, Number))
              2 True
            2.0 True
 Decimal('2.0') True
         (2+0j) True
 Fraction(2, 1) True
            '2' False

This is, of course, contrary to duck typing. If you are more concerned about how an object acts rather than what it is, perform your operations as if you have a number and use exceptions to tell you otherwise.

Changing the Status Bar Color for specific ViewControllers using Swift in iOS8

Works for Navigation Based for particular view controller in swift4

   let app = UIApplication.shared
   let statusBarHeight: CGFloat = app.statusBarFrame.size.height

   let statusbarView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: statusBarHeight))
   statusbarView.backgroundColor = UIColor.red
   view.addSubview(statusbarView)

How to convert a datetime to string in T-SQL

There are many different ways to convert a datetime to a string. Here is one way:

SELECT convert(varchar(25), getdate(), 121)  – yyyy-mm-dd hh:mm:ss.mmm

See Demo

Here is a website that has a list of all of the conversions:

How to Format datetime & date in SQL Server

pip installation /usr/local/opt/python/bin/python2.7: bad interpreter: No such file or directory

All you need to do is... close the terminal window and reopen new one to fix this issue.

The issue is, new python path is not added to bashrc(Either source or new terminal window would help).

Tomcat won't stop or restart

Have you try $ sudo ./catalina.sh stop? It worked in my case.

How to bind bootstrap popover on dynamic elements

This is how I made the code so it can handle dynamically created elements using popover feature. Using this code, you can trigger the popover to show by default.

HTML:

<div rel="this-should-be-the-target">
</div>

JQuery:

$(function() {
    var targetElement = 'rel="this-should-be-the-target"';
    initPopover(targetElement, "Test Popover Content");

    // use this line if you want it to show by default
    $(targetElement).popover('show');
    
    function initPopover(target, popOverContent) {
        $(target).each(function(i, obj) {
            $(this).popover({
                placement : 'auto',
                trigger : 'hover',
                "html": true,
                content: popOverContent
            });
         });
     }
});

Specifying java version in maven - differences between properties and compiler plugin

Consider the alternative:

<properties>
    <javac.src.version>1.8</javac.src.version>
    <javac.target.version>1.8</javac.target.version>
</properties>

It should be the same thing of maven.compiler.source/maven.compiler.target but the above solution works for me, otherwise the second one gets the parent specification (I have a matrioska of .pom)

What is the difference between DAO and Repository patterns?

In the spring framework, there is an annotation called the repository, and in the description of this annotation, there is useful information about the repository, which I think it is useful for this discussion.

Indicates that an annotated class is a "Repository", originally defined by Domain-Driven Design (Evans, 2003) as "a mechanism for encapsulating storage, retrieval, and search behavior which emulates a collection of objects".

Teams implementing traditional Java EE patterns such as "Data Access Object" may also apply this stereotype to DAO classes, though care should be taken to understand the distinction between Data Access Object and DDD-style repositories before doing so. This annotation is a general-purpose stereotype and individual teams may narrow their semantics and use as appropriate.

A class thus annotated is eligible for Spring DataAccessException translation when used in conjunction with a PersistenceExceptionTranslationPostProcessor. The annotated class is also clarified as to its role in the overall application architecture for the purpose of tooling, aspects, etc.

How to "grep" for a filename instead of the contents of a file?

You can also do:

tree | grep filename

This pipes the output of the tree command to grep for a search. This will only tell you whether the file exists though.

Why is Chrome showing a "Please Fill Out this Field" tooltip on empty fields?

You need to add the attribute "formnovalidate" to the control that is triggering the browser validation, e.g.:

<input type="image" id="fblogin" formnovalidate src="/images/facebook_connect.png">

Open youtube video in Fancybox jquery

This has a regular expression so it's easier to just copy and paste the youtube url. Is great for when you use a CMS for clients.

/*fancybox yt video*/
$(".fancybox-video").click(function() {
    $.fancybox({

    padding: 0,
        'autoScale'     : false,
        'transitionIn'  : 'none',
        'transitionOut' : 'none',
        'title'         : this.title,
        'width'         : 795,
        'height'        : 447,
        'href'          : this.href.replace(new RegExp("watch.*v=","i"), "v/"),
        'type'          : 'swf',
        'swf'           : {
        'wmode'             : 'transparent',
        'allowfullscreen'   : 'true'
         }

    });
    return false;
});

Mongoose, update values in array of objects

Below is an example of how to update the value in the array of objects more dynamically.

Person.findOneAndUpdate({_id: id}, 
{ 
  "$set": {[`items.$[outer].${propertyName}`]: value} 
},
{ 
  "arrayFilters": [{ "outer.id": itemId }]
},
function(err, response) {
  ...
})

Note that by doing it that way, you would be able to update even deeper levels of the nested array by adding additional arrayFilters and positional operator like so:

"$set": {[`items.$[outer].innerItems.$[inner].${propertyName}`]: value} 

"arrayFilters":[{ "outer.id": itemId },{ "inner.id": innerItemId }]

More usage can be found in the official docs.

Linux: where are environment variables stored?

Type "set" and you will get a list of all the current variables. If you want something to persist put it in ~/.bashrc or ~/.bash_profile (if you're using bash)

Exporting to .xlsx using Microsoft.Office.Interop.Excel SaveAs Error

myBook.Saved = true;
myBook.SaveCopyAs(xlsFileName);
myBook.Close(null, null, null);
myExcel.Workbooks.Close();
myExcel.Quit();

Convert row to column header for Pandas DataFrame,

This works (pandas v'0.19.2'):

df.rename(columns=df.iloc[0])

Replace characters from a column of a data frame R

chartr is also convenient for these types of substitutions:

chartr("_", "-", data1$c)
#  [1] "A-B" "A-B" "A-B" "A-B" "A-C" "A-C" "A-C" "A-C" "A-C" "A-C"

Thus, you can just do:

data1$c <- chartr("_", "-", data1$c)

Curly braces in string in PHP

I've also found it useful to access object attributes where the attribute names vary by some iterator. For example, I have used the pattern below for a set of time periods: hour, day, month.

$periods=array('hour', 'day', 'month');
foreach ($periods as $period)
{
    $this->{'value_'.$period}=1;
}

This same pattern can also be used to access class methods. Just build up the method name in the same manner, using strings and string variables.

You could easily argue to just use an array for the value storage by period. If this application were PHP only, I would agree. I use this pattern when the class attributes map to fields in a database table. While it is possible to store arrays in a database using serialization, it is inefficient, and pointless if the individual fields must be indexed. I often add an array of the field names, keyed by the iterator, for the best of both worlds.

class timevalues
{
                             // Database table values:
    public $value_hour;      // maps to values.value_hour
    public $value_day;       // maps to values.value_day
    public $value_month;     // maps to values.value_month
    public $values=array();

    public function __construct()
    {
        $this->value_hour=0;
        $this->value_day=0;
        $this->value_month=0;
        $this->values=array(
            'hour'=>$this->value_hour,
            'day'=>$this->value_day,
            'month'=>$this->value_month,
        );
    }
}

UnicodeDecodeError: 'charmap' codec can't decode byte X in position Y: character maps to <undefined>

TLDR? Try: file = open(filename, encoding='cp437)

Why? When one use:

file = open(filename)
text = file.read()

Python assumes the file uses the same codepage as current environment (cp1252 in case of the opening post) and tries to decode it to its own default UTF-8. If the file contains characters of values not defined in this codepage (like 0x90) we get UnicodeDecodeError. Sometimes we don't know the encoding of the file, sometimes the file's encoding may be unhandled by Python (like e.g. cp790), sometimes the file can contain mixed encodings.

If such characters are unneeded, one may decide to replace them by question marks, with:

file = open(filename, errors='replace')

Another workaround is to use:

file = open(filename, errors='ignore')

The characters are then left intact, but other errors will be masked too.

Quite good solution is to specify the encoding, yet not any encoding (like cp1252), but the one which has ALL characters defined (like cp437):

file = open(filename, encoding='cp437')

Codepage 437 is the original DOS encoding. All codes are defined, so there are no errors while reading the file, no errors are masked out, the characters are preserved (not quite left intact but still distinguishable).

How to check if android checkbox is checked within its onClick method (declared in XML)?

This will do the trick:

  public void itemClicked(View v) {
    if (((CheckBox) v).isChecked()) {
        Toast.makeText(MyAndroidAppActivity.this,
           "Checked", Toast.LENGTH_LONG).show();
    }
  }

ASP.NET MVC - Getting QueryString values

I recommend using the ValueProvider property of the controller, much in the way that UpdateModel/TryUpdateModel do to extract the route, query, and form parameters required. This will keep your method signatures from potentially growing very large and being subject to frequent change. It also makes it a little easier to test since you can supply a ValueProvider to the controller during unit tests.

Run-time error '1004' - Method 'Range' of object'_Global' failed

Your range value is incorrect. You are referencing cell "75" which does not exist. You might want to use the R1C1 notation to use numeric columns easily without needing to convert to letters.

http://www.bettersolutions.com/excel/EED883/YI416010881.htm

Range("R" & DataImportRow & "C" & DataImportColumn).Offset(0, 2).Value = iFirstCustomerSales

This should fix your problem.

How to use php serialize() and unserialize()

From http://php.net/manual/en/function.serialize.php :

Generates a storable representation of a value. This is useful for storing or passing PHP values around without losing their type and structure.

Essentially, it takes a php array or object and converts it to a string (which you can then transmit or store as you see fit).

Unserialize is used to convert the string back to an object.

Define the selected option with the old input in Laravel / Blade

Okay, my 2 cents, using the default value of Laravel's old() function.

<select name="type">
    @foreach($options as $key => $text)
        <option @if((int) old('type', $selectedOption) === $key) selected @endif value="{{ $key }}">{{ $text }}</option>
    @endforeach
</select>

Is null check needed before calling instanceof?

No, a null check is not needed before using instanceof.

The expression x instanceof SomeClass is false if x is null.

From the Java Language Specification, section 15.20.2, "Type comparison operator instanceof":

"At run time, the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast to the ReferenceType without raising a ClassCastException. Otherwise the result is false."

So if the operand is null, the result is false.

Android : How to read file in bytes?

The easiest solution today is to used Apache common io :

http://commons.apache.org/proper/commons-io/javadocs/api-release/org/apache/commons/io/FileUtils.html#readFileToByteArray(java.io.File)

byte bytes[] = FileUtils.readFileToByteArray(photoFile)

The only drawback is to add this dependency in your build.gradle app :

implementation 'commons-io:commons-io:2.5'

+ 1562 Methods count

Add a fragment to the URL without causing a redirect?

window.location.hash = 'something';

That is just plain JavaScript.

Your comment...

Hi, what I really need is to add only the hash... something like this: window.location.hash = '#'; but in this way nothing is added.

Try this...

window.location = '#';

Also, don't forget about the window.location.replace() method.

How exactly does <script defer="defer"> work?

UPDATED: 2/19/2016

Consider this answer outdated. Refer to other answers on this post for information relevant to newer browser version.


Basically, defer tells the browser to wait "until it's ready" before executing the javascript in that script block. Usually this is after the DOM has finished loading and document.readyState == 4

The defer attribute is specific to internet explorer. In Internet Explorer 8, on Windows 7 the result I am seeing in your JS Fiddle test page is, 1 - 2 - 3.

The results may vary from browser to browser.

http://msdn.microsoft.com/en-us/library/ms533719(v=vs.85).aspx

Contrary to popular belief IE follows standards more often than people let on, in actuality the "defer" attribute is defined in the DOM Level 1 spec http://www.w3.org/TR/REC-DOM-Level-1/level-one-html.html

The W3C's definition of defer: http://www.w3.org/TR/REC-html40/interact/scripts.html#adef-defer:

"When set, this boolean attribute provides a hint to the user agent that the script is not going to generate any document content (e.g., no "document.write" in javascript) and thus, the user agent can continue parsing and rendering."

"No such file or directory" but it exists

I faced this error when I was trying to build Selenium source on Ubuntu. The simple shell script with correct shebang was not able to run even after I had all pre-requisites covered.

file file-name # helped me in understanding that CRLF ending were present in the file.

I opened the file in Vim and I could see that just because I once edited this file on a Windows machine, it was in DOS format. I converted the file to Unix format with below command:

dos2unix filename # actually helped me and things were fine.

I hope that we should take care whenever we edit files across platforms we should take care for the file formats as well.

Why do I get access denied to data folder when using adb?

There are two things to remember if you want to browse everything on your device.

  1. You need to have a phone with root access in order to browse the data folder on an Android phone. That means either you have a developer device (ADP1 or an ION from Google I/O) or you've found a way to 'root' your phone some other way.
  2. You need to be running ADB in root mode, do this by executing: adb root

Develop Android app using C#

You could use Mono for Android:

http://xamarin.com/monoforandroid

An alternative is dot42:

http://www.dot42.com/

dot42 provides a free community licence as well as a professional licence for $399.

Change the content of a div based on selection from dropdown menu

The accepted answer has a couple of shortcomings:

  • Don't target IDs in your JavaScript code. Use classes and data attributes to avoid repeating your code.
  • It is good practice to hide with CSS on load rather than with JavaScript—to support non-JavaScript users, and prevent a show-hide flicker on load.

Considering the above, your options could even have different values, but toggle the same class:

<select class="div-toggle" data-target=".my-info-1">
  <option value="orange" data-show=".citrus">Orange</option>
  <option value="lemon" data-show=".citrus">Lemon</option>
  <option value="apple" data-show=".pome">Apple</option>
  <option value="pear" data-show=".pome">Pear</option>
</select>

<div class="my-info-1">
  <div class="citrus hide">Citrus is...</div>
  <div class="pome hide">A pome is...</div>
</div>

jQuery:

$(document).on('change', '.div-toggle', function() {
  var target = $(this).data('target');
  var show = $("option:selected", this).data('show');
  $(target).children().addClass('hide');
  $(show).removeClass('hide');
});
$(document).ready(function(){
    $('.div-toggle').trigger('change');
});

CSS:

.hide {
  display: none;
}

Here's a JSFiddle to see it in action.

How to plot a subset of a data frame in R?

This is how I would do it, in order to get in the var4 restriction:

dfr<-data.frame(var1=rnorm(100), var2=rnorm(100), var3=rnorm(100, 160, 10), var4=rnorm(100, 27, 6))
plot( subset( dfr, var3 < 155 & var4 > 27, select = c( var1, var2 ) ) )

Rgds, Rainer

What is the difference between decodeURIComponent and decodeURI?

To explain the difference between these two let me explain the difference between encodeURI and encodeURIComponent.

The main difference is that:

  • The encodeURI function is intended for use on the full URI.
  • The encodeURIComponent function is intended to be used on .. well .. URI components that is any part that lies between separators (; / ? : @ & = + $ , #).

So, in encodeURIComponent these separators are encoded also because they are regarded as text and not special characters.

Now back to the difference between the decode functions, each function decodes strings generated by its corresponding encode counterpart taking care of the semantics of the special characters and their handling.

Does VBScript have a substring() function?

As Tmdean correctly pointed out you can use the Mid() function. The MSDN Library also has a great reference section on VBScript which you can find here:

VBScript Language Reference (MSDN Library)

Convert time span value to format "hh:mm Am/Pm" using C#

At first, you need to convert time span to DateTime structure:

var dt = new DateTime(2000, 12, 1, timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds)

Then you need to convert the value to string with Short Time format

var result = dt.ToString("t"); // Convert to string using Short Time format

Add space between HTML elements only using CSS

You should wrap your elements inside a container, then use new CSS3 features like css grid, free course, and then use grid-gap:value that was created for your specific problem

_x000D_
_x000D_
span{_x000D_
  border:1px solid red;_x000D_
}_x000D_
.inRow{_x000D_
  display:grid;_x000D_
  grid-template-columns:repeat(auto-fill,auto);_x000D_
  grid-gap:10px /*This add space between elements, only works on grid items*/_x000D_
}_x000D_
.inColumn{_x000D_
  display:grid;_x000D_
  grid-template-rows:repeat(auto-fill,auto);_x000D_
  grid-gap:15px;_x000D_
}
_x000D_
<div class="inrow">_x000D_
  <span>1</span>_x000D_
  <span>2</span>_x000D_
  <span>3</span>_x000D_
</div>_x000D_
<div class="inColumn">_x000D_
  <span>4</span>_x000D_
  <span>5</span>_x000D_
  <span>6</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Very Simple Image Slider/Slideshow with left and right button. No autoplay

Very simple code to make jquery slider Here is two div first is the slider viewer and second is the image list container. Just copy paste the code and customise with css.

    <div class="featured-image" style="height:300px">
     <img id="thumbnail" src="01.jpg"/>
    </div>

    <div class="post-margin" style="margin:10px 0px; padding:0px;" id="thumblist">
    <img src='01.jpg'>
    <img src='02.jpg'>
    <img src='03.jpg'>
    <img src='04.jpg'>
    </div>

    <script type="text/javascript">
            function changeThumbnail()
            {
            $("#thumbnail").fadeOut(200);
            var path=$("#thumbnail").attr('src');
            var arr= new Array(); var i=0;
            $("#thumblist img").each(function(index, element) {
               arr[i]=$(this).attr('src');
               i++;
            });
            var index= arr.indexOf(path);
            if(index==(arr.length-1))
            path=arr[0];
            else
            path=arr[index+1];
            $("#thumbnail").attr('src',path).fadeIn(200);
            setTimeout(changeThumbnail, 5000);  
            }
            setTimeout(changeThumbnail, 5000);
    </script>

LF will be replaced by CRLF in git - What is that and is it important?

In Unix systems the end of a line is represented with a line feed (LF). In windows a line is represented with a carriage return (CR) and a line feed (LF) thus (CRLF). when you get code from git that was uploaded from a unix system they will only have an LF.

If you are a single developer working on a windows machine, and you don't care that git automatically replaces LFs to CRLFs, you can turn this warning off by typing the following in the git command line

git config core.autocrlf true

If you want to make an intelligent decision how git should handle this, read the documentation

Here is a snippet

Formatting and Whitespace

Formatting and whitespace issues are some of the more frustrating and subtle problems that many developers encounter when collaborating, especially cross-platform. It’s very easy for patches or other collaborated work to introduce subtle whitespace changes because editors silently introduce them, and if your files ever touch a Windows system, their line endings might be replaced. Git has a few configuration options to help with these issues.

core.autocrlf

If you’re programming on Windows and working with people who are not (or vice-versa), you’ll probably run into line-ending issues at some point. This is because Windows uses both a carriage-return character and a linefeed character for newlines in its files, whereas Mac and Linux systems use only the linefeed character. This is a subtle but incredibly annoying fact of cross-platform work; many editors on Windows silently replace existing LF-style line endings with CRLF, or insert both line-ending characters when the user hits the enter key.

Git can handle this by auto-converting CRLF line endings into LF when you add a file to the index, and vice versa when it checks out code onto your filesystem. You can turn on this functionality with the core.autocrlf setting. If you’re on a Windows machine, set it to true – this converts LF endings into CRLF when you check out code:

$ git config --global core.autocrlf true

If you’re on a Linux or Mac system that uses LF line endings, then you don’t want Git to automatically convert them when you check out files; however, if a file with CRLF endings accidentally gets introduced, then you may want Git to fix it. You can tell Git to convert CRLF to LF on commit but not the other way around by setting core.autocrlf to input:

$ git config --global core.autocrlf input

This setup should leave you with CRLF endings in Windows checkouts, but LF endings on Mac and Linux systems and in the repository.

If you’re a Windows programmer doing a Windows-only project, then you can turn off this functionality, recording the carriage returns in the repository by setting the config value to false:

$ git config --global core.autocrlf false

Count elements with jQuery

$('.class').length

This one does not work for me. I'd rather use this:

$('.class').children().length

I don't really know the reason why, but the second one works only for me. Somewhy, either size doesn't work.

How to debug when Kubernetes nodes are in 'Not Ready' state

First, describe nodes and see if it reports anything:

$ kubectl describe nodes

Look for conditions, capacity and allocatable:

Conditions:
  Type              Status
  ----              ------
  OutOfDisk         False
  MemoryPressure    False
  DiskPressure      False
  Ready             True
Capacity:
 cpu:       2
 memory:    2052588Ki
 pods:      110
Allocatable:
 cpu:       2
 memory:    1950188Ki
 pods:      110

If everything is alright here, SSH into the node and observe kubelet logs to see if it reports anything. Like certificate erros, authentication errors etc.

If kubelet is running as a systemd service, you can use

$ journalctl -u kubelet

how to convert a string to a bool

I made something a little bit more extensible, Piggybacking on Mohammad Sepahvand's concept:

    public static bool ToBoolean(this string s)
    {
        string[] trueStrings = { "1", "y" , "yes" , "true" };
        string[] falseStrings = { "0", "n", "no", "false" };


        if (trueStrings.Contains(s, StringComparer.OrdinalIgnoreCase))
            return true;
        if (falseStrings.Contains(s, StringComparer.OrdinalIgnoreCase))
            return false;

        throw new InvalidCastException("only the following are supported for converting strings to boolean: " 
            + string.Join(",", trueStrings)
            + " and "
            + string.Join(",", falseStrings));
    }

How do I fetch only one branch of a remote Git repository?

  1. Pick any <remote_name> you'd like to use (feel free to use origin and skip step 1.)
  2. git remote add <remote_name> <remote_url>
  3. git fetch <remote_name> <branch>
  4. Pick any <your_local_branch_name> you'd like to use. Could be the same as <branch>.
  5. git checkout <remote_name>/<branch> -b <your_local_branch_name>

Hope that helps!

How to change Windows 10 interface language on Single Language version

You can download language pack and use "Install or Uninstall display languages" wizard. To do this:

  • Press Win+R, paste lpksetup and press Enter
  • Wizard will appear on the screen
  • Click the Install display languages button
  • In the next page of the wizard, click Browse and pick the *.cab file of the MUI language you downloaded
  • Click the Next button to install language

Android toolbar center title and custom font

You can insert this code in your xml file

 <androidx.appcompat.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/colorPrimaryDark"
    android:elevation="4dp"
    android:theme="@style/ThemeOverlay.AppCompat.ActionBar">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Toolbar Title"
        android:textColor="#000000"
        android:textSize="20dp"
        android:id="@+id/toolbar_title" />

</androidx.appcompat.widget.Toolbar>

How much RAM is SQL Server actually using?

You should explore SQL Server\Memory Manager performance counters.

how do you filter pandas dataframes by multiple columns

Using & operator, don't forget to wrap the sub-statements with ():

males = df[(df[Gender]=='Male') & (df[Year]==2014)]

To store your dataframes in a dict using a for loop:

from collections import defaultdict
dic={}
for g in ['male', 'female']:
  dic[g]=defaultdict(dict)
  for y in [2013, 2014]:
    dic[g][y]=df[(df[Gender]==g) & (df[Year]==y)] #store the DataFrames to a dict of dict

EDIT:

A demo for your getDF:

def getDF(dic, gender, year):
  return dic[gender][year]

print genDF(dic, 'male', 2014)

How to change DataTable columns order

I know this is a really old question.. and it appears it was answered.. But I got here with the same question but a different reason for the question, and so a slightly different answer worked for me. I have a nice reusable generic datagridview that takes the datasource supplied to it and just displays the columns in their default order. I put aliases and column order and selection at the dataset's tableadapter level in designer. However changing the select query order of columns doesn't seem to impact the columns returned through the dataset. I have found the only way to do this in the designer, is to remove all the columns selected within the tableadapter, adding them back in the order you want them selected.

Why does DEBUG=False setting make my django Static Files Access fail?

Support for string view arguments to url() is deprecated and will be removed in Django 1.10

My solution is just small correction to Conrado solution above.

from django.conf import settings
import os
from django.views.static import serve as staticserve

if settings.DEBUG404:
    urlpatterns += patterns('',
        (r'^static/(?P<path>.*)$', staticserve,
            {'document_root': os.path.join(os.path.dirname(__file__), 'static')} ),
        )

Adjust width of input field to its input

Here is an alternative way to solve this using a DIV and the 'contenteditable' property:

HTML:

<div contenteditable = "true" class = "fluidInput" data-placeholder = ""></div>

CSS: (to give the DIV some dimensions and make it easier to see)

.fluidInput {

    display         : inline-block;
    vertical-align  : top;

    min-width       : 1em;
    height          : 1.5em;

    font-family     : Arial, Helvetica, sans-serif;
    font-size       : 0.8em;
    line-height     : 1.5em;

    padding         : 0px 2px 0px 2px;
    border          : 1px solid #aaa;
    cursor          : text;
}


.fluidInput * {

    display         : inline;

}


.fluidInput br  {

    display         : none;

}


.fluidInput:empty:before {

    content         : attr(data-placeholder);
    color           : #ccc;

}

Note: If you are planning on using this inside of a FORM element that you plan to submit, you will need to use Javascript / jQuery to catch the submit event so that you can parse the 'value' ( .innerHTML or .html() respectively) of the DIV.

How can I easily switch between PHP versions on Mac OSX?

Example: Let us switch from php 7.4 to 7.3

brew unlink [email protected]
brew install [email protected]
brew link [email protected]

If you get Warning: [email protected] is keg-only and must be linked with --force Then try with:

brew link [email protected] --force

Easiest way to convert month name to month number in JS ? (Jan = 01)

function getMonthDays(MonthYear) {
  var months = [
    'January',
    'February',
    'March',
    'April',
    'May',
    'June',
    'July',
    'August',
    'September',
    'October',
    'November',
    'December'
  ];

  var Value=MonthYear.split(" ");      
  var month = (months.indexOf(Value[0]) + 1);      
  return new Date(Value[1], month, 0).getDate();
}

console.log(getMonthDays("March 2011"));

Value does not fall within the expected range

In case of WSS 3.0 recently I experienced same issue. It was because of column that was accessed from code was not present in the wss list.

Converting a String to Object

A String is a type of Object. So any method that accepts Object as parameter will surely accept String also. Please provide more of your code if you still do not find a solution.

How to listen to route changes in react router v4?

v5.1 introduces the useful hook useLocation

https://reacttraining.com/blog/react-router-v5-1/#uselocation

import { Switch, useLocation } from 'react-router-dom'

function usePageViews() {
  let location = useLocation()

  useEffect(
    () => {
      ga.send(['pageview', location.pathname])
    },
    [location]
  )
}

function App() {
  usePageViews()
  return <Switch>{/* your routes here */}</Switch>
}

Removing all line breaks and adding them after certain text

  • Open Notepad++
  • Paste your text
  • Control + H

In the pop up

  • Find what: \r\n
  • Replace with: BLANK_SPACE

You end up with a big line. Then

  • Control + H

In the pop up

  • Find what: (\.)
  • Replace with: \r\n

So you end up with lines that end by dot

And if you have to do the same process lots of times

  • Go to Macro
  • Start recording
  • Do the process above
  • Go to Macro
  • Stop recording
  • Save current recorded macro
  • Choose a short cut
  • Select the text you want to apply the process (Control + A)
  • Do the shortcut

SQL Server 2008 R2 Express permissions -- cannot create database or modify users

I have 2 accounts on my windows machine and I was experiencing this problem with one of them. I did not want to use the sa account, I wanted to use Windows login. It was not immediately obvious to me that I needed to simply sign into the other account that I used to install SQL Server, and add the permissions for the new account from there

(SSMS > Security > Logins > Add a login there)

Easy way to get the full domain name you need to add there open cmd echo each one.

echo %userdomain%\%username%

Add a login for that user and give it all the permissons for master db and other databases you want. When I say "all permissions" make sure NOT to check of any of the "deny" permissions since that will do the opposite.

How to backup Sql Database Programmatically in C#

you can connect to the database using SqlConnection and SqlCommand and execute the following command text for example:

BACKUP DATABASE [MyDatabase] TO  DISK = 'C:\....\MyDatabase.bak'

See here for examples.

Joining pandas dataframes by column names

you can use the left_on and right_on options as follows:

pd.merge(frame_1, frame_2, left_on='county_ID', right_on='countyid')

I was not sure from the question if you only wanted to merge if the key was in the left hand dataframe. If that is the case then the following will do that (the above will in effect do a many to many merge)

pd.merge(frame_1, frame_2, how='left', left_on='county_ID', right_on='countyid')

Procedure or function !!! has too many arguments specified

You invoke the function with 2 parameters (@GenId and @Description):

EXEC etl.etl_M_Update_Promo @GenID, @Description

However you have declared the function to take 1 argument:

ALTER PROCEDURE [etl].[etl_M_Update_Promo]
    @GenId bigint = 0

SQL Server is telling you that [etl_M_Update_Promo] only takes 1 parameter (@GenId)

You can alter the procedure to take two parameters by specifying @Description.

ALTER PROCEDURE [etl].[etl_M_Update_Promo]
    @GenId bigint = 0,
    @Description NVARCHAR(50)
AS 

.... Rest of your code.

Difference between array_push() and $array[] =

You can add more than 1 element in one shot to array using array_push,

e.g. array_push($array_name, $element1, $element2,...)

Where $element1, $element2,... are elements to be added to array.

But if you want to add only one element at one time, then other method (i.e. using $array_name[]) should be preferred.

How can I print literal curly-brace characters in a string and also use .format on it?

Although not any better, just for the reference, you can also do this:

>>> x = '{}Hello{} {}'
>>> print x.format('{','}',42)
{Hello} 42

It can be useful for example when someone wants to print {argument}. It is maybe more readable than '{{{}}}'.format('argument')

Note that you omit argument positions (e.g. {} instead of {0}) after Python 2.7

How do I plot in real-time in a while loop using matplotlib?

An example use-case to plot CPU usage in real-time.

import time
import psutil
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

i = 0
x, y = [], []

while True:
    x.append(i)
    y.append(psutil.cpu_percent())

    ax.plot(x, y, color='b')

    fig.canvas.draw()

    ax.set_xlim(left=max(0, i - 50), right=i + 50)
    fig.show()
    plt.pause(0.05)
    i += 1

Convert seconds value to hours minutes seconds?

I use this in python to convert a float representing seconds to hours, minutes, seconds, and microseconds. It's reasonably elegant and is handy for converting to a datetime type via strptime to convert. It could also be easily extended to longer intervals (weeks, months, etc.) if needed.

    def sectohmsus(seconds):
        x = seconds
        hmsus = []
        for i in [3600, 60, 1]:  # seconds in a hour, minute, and second
            hmsus.append(int(x / i))
            x %= i
        hmsus.append(int(round(x * 1000000)))  # microseconds
        return hmsus  # hours, minutes, seconds, microsecond

How do I replace text in a selection?

Windows
1- Find: CTRL + F
2- Select-in: Alt + Enter

Now you can change all the selection in one shot like "seen-on-tv" ST homepage Spot.

Credit goes to : https://superuser.com/a/921806/342825

What could cause java.lang.reflect.InvocationTargetException?

The error vanished after I did Clean->Run xDoclet->Run xPackaging.

In my workspace, in ecllipse.

Android Canvas: drawing too large bitmap

If you don't want your image to be pre-scaled you can move it to the res/drawable-nodpi/ folder.

More info: https://developer.android.com/training/multiscreen/screendensities#DensityConsiderations

How to check if the user can go back in browser history or not

Check if window.history.length is equal to 0.

Copying one structure to another

Copying by plain assignment is best, since it's shorter, easier to read, and has a higher level of abstraction. Instead of saying (to the human reader of the code) "copy these bits from here to there", and requiring the reader to think about the size argument to the copy, you're just doing a plain assignment ("copy this value from here to here"). There can be no hesitation about whether or not the size is correct.

Also, if the structure is heavily padded, assignment might make the compiler emit something more efficient, since it doesn't have to copy the padding (and it knows where it is), but mempcy() doesn't so it will always copy the exact number of bytes you tell it to copy.

If your string is an actual array, i.e.:

struct {
  char string[32];
  size_t len;
} a, b;

strcpy(a.string, "hello");
a.len = strlen(a.string);

Then you can still use plain assignment:

b = a;

To get a complete copy. For variable-length data modelled like this though, this is not the most efficient way to do the copy since the entire array will always be copied.

Beware though, that copying structs that contain pointers to heap-allocated memory can be a bit dangerous, since by doing so you're aliasing the pointer, and typically making it ambiguous who owns the pointer after the copying operation.

For these situations a "deep copy" is really the only choice, and that needs to go in a function.

How to count objects in PowerShell?

As short as @jumbo's answer is :-) you can do it even more tersely. This just returns the Count property of the array returned by the antecedent sub-expression:

@(Get-Alias).Count

A couple points to note:

  1. You can put an arbitrarily complex expression in place of Get-Alias, for example:

    @(Get-Process | ? { $_.ProcessName -eq "svchost" }).Count
    
  2. The initial at-sign (@) is necessary for a robust solution. As long as the answer is two or greater you will get an equivalent answer with or without the @, but when the answer is zero or one you will get no output unless you have the @ sign! (It forces the Count property to exist by forcing the output to be an array.)

2012.01.30 Update

The above is true for PowerShell V2. One of the new features of PowerShell V3 is that you do have a Count property even for singletons, so the at-sign becomes unimportant for this scenario.

Using Docker-Compose, how to execute multiple commands

I run pre-startup stuff like migrations in a separate ephemeral container, like so (note, compose file has to be of version '2' type):

db:
  image: postgres
web:
  image: app
  command: python manage.py runserver 0.0.0.0:8000
  volumes:
    - .:/code
  ports:
    - "8000:8000"
  links:
    - db
  depends_on:
    - migration
migration:
  build: .
  image: app
  command: python manage.py migrate
  volumes:
    - .:/code
  links:
    - db
  depends_on:
    - db

This helps things keeping clean and separate. Two things to consider:

  1. You have to ensure the correct startup sequence (using depends_on).

  2. You want to avoid multiple builds which is achieved by tagging it the first time round using build and image; you can refer to image in other containers then.

Writing .csv files from C++

There is nothing special about a CSV file. You can create them using a text editor by simply following the basic rules. The RFC 4180 (tools.ietf.org/html/rfc4180) accepted separator is the comma ',' not the semi-colon ';'. Programs like MS Excel expect a comma as a separator.

There are some programs that treat the comma as a decimal and the semi-colon as a separator, but these are technically outside of the "accepted" standard for CSV formatted files.

So, when creating a CSV you create your filestream and add your lines like so:

#include <iostream>
#include <fstream>
int main( int argc, char* argv[] )
{
      std::ofstream myfile;
      myfile.open ("example.csv");
      myfile << "This is the first cell in the first column.\n";
      myfile << "a,b,c,\n";
      myfile << "c,s,v,\n";
      myfile << "1,2,3.456\n";
      myfile << "semi;colon";
      myfile.close();
      return 0;
}

This will result in a CSV file that looks like this when opened in MS Excel:

Image of CSV file created with C++

Why is the time complexity of both DFS and BFS O( V + E )

DFS(analysis):

  • Setting/getting a vertex/edge label takes O(1) time
  • Each vertex is labeled twice
    • once as UNEXPLORED
    • once as VISITED
  • Each edge is labeled twice
    • once as UNEXPLORED
    • once as DISCOVERY or BACK
  • Method incidentEdges is called once for each vertex
  • DFS runs in O(n + m) time provided the graph is represented by the adjacency list structure
  • Recall that Sv deg(v) = 2m

BFS(analysis):

  • Setting/getting a vertex/edge label takes O(1) time
  • Each vertex is labeled twice
    • once as UNEXPLORED
    • once as VISITED
  • Each edge is labeled twice
    • once as UNEXPLORED
    • once as DISCOVERY or CROSS
  • Each vertex is inserted once into a sequence Li
  • Method incidentEdges is called once for each vertex
  • BFS runs in O(n + m) time provided the graph is represented by the adjacency list structure
  • Recall that Sv deg(v) = 2m

Why es6 react component works only with "export default"?

Exporting without default means it's a "named export". You can have multiple named exports in a single file. So if you do this,

class Template {}
class AnotherTemplate {}

export { Template, AnotherTemplate }

then you have to import these exports using their exact names. So to use these components in another file you'd have to do,

import {Template, AnotherTemplate} from './components/templates'

Alternatively if you export as the default export like this,

export default class Template {}

Then in another file you import the default export without using the {}, like this,

import Template from './components/templates'

There can only be one default export per file. In React it's a convention to export one component from a file, and to export it is as the default export.

You're free to rename the default export as you import it,

import TheTemplate from './components/templates'

And you can import default and named exports at the same time,

import Template,{AnotherTemplate} from './components/templates'

How to use NULL or empty string in SQL

If you need it in SELECT section can use like this.

    SELECT  ct.ID, 
            ISNULL(NULLIF(ct.LaunchDate, ''), null) [LaunchDate]
    FROM    [dbo].[CustomerTable] ct

you can replace the null with your substitution value.

Installing TensorFlow on Windows (Python 3.6.x)

I had the same issue, but I followed the following steps:-

  1. I had Python 3.6.5 (32 bit) installed on my desktop, but from all the research I did, I could conclude that Tensorflow runs only on Python 3.5x or 3.6x 64 bit versions. So I uninstalled it and Installed Python 3.5.0 instead.
  2. I ran Python 3.5.0 as an administrator. This step is necessary for Windows as, without it, the system doesn't get any privileges and can't install tensorflow.
  3. Install Pip3 using command:- python -m pip install --upgrade pip
  4. Once the newest version (10.0.1 in my case) is installed, you can install tensorflow usin command:- pip3 install --upgrade tensorflow
  5. Your tensorflow will be downloaded and installed. For further help on how to run tensorflow programs, go to https://www.tensorflow.org/get_started/premade_estimators

Detect Android phone via Javascript / jQuery

;(function() {
    var redirect = false
    if (navigator.userAgent.match(/iPhone/i)) {
        redirect = true
    }
    if (navigator.userAgent.match(/iPod/i)) {
        redirect = true
    }
    var isAndroid = /(android)/i.test(navigator.userAgent)
    var isMobile = /(mobile)/i.test(navigator.userAgent)
    if (isAndroid && isMobile) {
        redirect = true
    }
    if (redirect) {
        window.location.replace('jQueryMobileSite')
    }
})()

Asynchronous method call in Python?

You can use the multiprocessing module added in Python 2.6. You can use pools of processes and then get results asynchronously with:

apply_async(func[, args[, kwds[, callback]]])

E.g.:

from multiprocessing import Pool

def f(x):
    return x*x

if __name__ == '__main__':
    pool = Pool(processes=1)              # Start a worker processes.
    result = pool.apply_async(f, [10], callback) # Evaluate "f(10)" asynchronously calling callback when finished.

This is only one alternative. This module provides lots of facilities to achieve what you want. Also it will be really easy to make a decorator from this.

Python: How would you save a simple settings/config file?

If you want to use something like an INI file to hold settings, consider using configparser which loads key value pairs from a text file, and can easily write back to the file.

INI file has the format:

[Section]
key = value
key with spaces = somevalue

How to make child divs always fit inside parent div?

For width it's easy, simply remove the width: 100% rule. By default, the div will stretch to fit the parent container.

Height is not quite so simple. You could do something like the equal height column trick.

html, body {width:100%;height:100%;margin:0;padding:0;}
.border {border:1px solid black;}
.margin { margin:5px;}
#one {width:500px;height:300px; overflow: hidden;}
#two {height:50px;}
#three {width:100px; padding-bottom: 30000px; margin-bottom: -30000px;}

Display help message with python argparse when script is called without any arguments

The cleanest solution will be to manually pass default argument if none were given on the command line:

parser.parse_args(args=None if sys.argv[1:] else ['--help'])

Complete example:

import argparse, sys

parser = argparse.ArgumentParser()
parser.add_argument('--host', default='localhost', help='Host to connect to')
# parse arguments
args = parser.parse_args(args=None if sys.argv[1:] else ['--help'])

# use your args
print("connecting to {}".format(args.host))

This will print complete help (not short usage) if called w/o arguments.

How to add Button over image using CSS?

Adapt this example to your code

HTML

<div class="img-holder">
    <img src="images/img-1.png" alt="image description"/>
    <a class="link" href=""></a>
</div>

CSS

.img-holder {position: relative;}
.img-holder .link {
    position: absolute;
    bottom: 10px; /*your button position*/
    right: 10px; /*your button position*/
}

Using Excel VBA to export data to MS Access table

@Ahmed

Below is code that specifies fields from a named range for insertion into MS Access. The nice thing about this code is that you can name your fields in Excel whatever the hell you want (If you use * then the fields have to match exactly between Excel and Access) as you can see I have named an Excel column "Haha" even though the Access column is called "dte".

Sub test()
    dbWb = Application.ActiveWorkbook.FullName
    dsh = "[" & Application.ActiveSheet.Name & "$]" & "Data2"  'Data2 is a named range


sdbpath = "C:\Users\myname\Desktop\Database2.mdb"
sCommand = "INSERT INTO [main] ([dte], [test1], [values], [values2]) SELECT [haha],[test1],[values],[values2] FROM [Excel 8.0;HDR=YES;DATABASE=" & dbWb & "]." & dsh

Dim dbCon As New ADODB.Connection
Dim dbCommand As New ADODB.Command

dbCon.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & sdbpath & "; Jet OLEDB:Database Password=;"
dbCommand.ActiveConnection = dbCon

dbCommand.CommandText = sCommand
dbCommand.Execute

dbCon.Close


End Sub

Font-awesome, input type 'submit'

Also possible like this

<button type="submit" class="icon-search icon-large"></button>

How to run a .awk file?

Put the part from BEGIN....END{} inside a file and name it like my.awk.

And then execute it like below:

awk -f my.awk life.csv >output.txt

Also I see a field separator as ,. You can add that in the begin block of the .awk file as FS=","

shell init issue when click tab, what's wrong with getcwd?

By chance, is this occurring on a directory using OverlayFS (or some other special file system type)?

I just had this issue where my cross-compiled version of bash would use an internal implementation of getcwd which has issues with OverlayFS. I found information about this here:

It seems that this can be traced to an internal implementation of getcwd() in bash. When cross-compiled, it can't check for getcwd() use of malloc, so it is cautious and sets GETCWD_BROKEN and uses an internal implementation of getcwd(). This internal implementation doesn't seem to work well with OverlayFS.

http://permalink.gmane.org/gmane.linux.embedded.yocto.general/25204

You can configure and rebuild bash with bash_cv_getcwd_malloc=yes (if you're actually building bash and your C library does malloc a getcwd call).

C++ for each, pulling from vector elements

For next examples assumed that you use C++11. Example with ranged-based for loops:

for (auto &attack : m_attack) // access by reference to avoid copying
{  
    if (attack->m_num == input)
    {
        attack->makeDamage();
    }
}

You should use const auto &attack depending on the behavior of makeDamage().

You can use std::for_each from standard library + lambdas:

std::for_each(m_attack.begin(), m_attack.end(),
        [](Attack * attack)
        {
            if (attack->m_num == input)
            {
                attack->makeDamage();
            }
        }
);

If you are uncomfortable using std::for_each, you can loop over m_attack using iterators:

for (auto attack = m_attack.begin(); attack != m_attack.end(); ++attack)
{  
    if (attack->m_num == input)
    {
        attack->makeDamage();
    }
}

Use m_attack.cbegin() and m_attack.cend() to get const iterators.

How to run PyCharm in Ubuntu - "Run in Terminal" or "Run"?

First, go to that folder which is containing pycharm.sh and open terminal from there. Then type

./pycharm.sh

this will open pycharm.

bin folder contains pycharm.sh file.

Print array without brackets and commas

first

StringUtils.join(array, "");

second

Arrays.asList(arr).toString().substring(1).replaceFirst("]", "").replace(", ", "")

EDIT

probably the best one: Arrays.toString(arr)

Xml serialization - Hide null values

You can create a function with the pattern ShouldSerialize{PropertyName} which tells the XmlSerializer if it should serialize the member or not.

For example, if your class property is called MyNullableInt you could have

public bool ShouldSerializeMyNullableInt() 
{
  return MyNullableInt.HasValue;
}

Here is a full sample

public class Person
{
  public string Name {get;set;}
  public int? Age {get;set;}
  public bool ShouldSerializeAge()
  {
    return Age.HasValue;
  }
}

Serialized with the following code

Person thePerson = new Person(){Name="Chris"};
XmlSerializer xs = new XmlSerializer(typeof(Person));
StringWriter sw = new StringWriter();
xs.Serialize(sw, thePerson);

Results in the followng XML - Notice there is no Age

<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Name>Chris</Name>
</Person>

Making a UITableView scroll when text field is selected

If your UITableView is managed by a subclass of UITableViewController and not UITableView, and the text field delegate is the UITableViewController, it should manage all the scrolling automatically -- all these other comments are very difficult to implement in practice.

For a good example see the apple example code project: TaggedLocations.

You can see that it scrolls automatically, but there doesn't seem to be any code that does this. This project also has custom table view cells, so if you build your application with it as a guide, you should get the desired result.

Pipenv: Command Not Found

I tried this:

python -m pipenv # for python2

python3 -m pipenv # for python3

Hope this can help you.

find all the name using mysql query which start with the letter 'a'

I would go for substr() functionality in MySql.

Basically, this function takes account of three parameters i.e. substr(str,pos,len)

http://www.w3resource.com/mysql/string-functions/mysql-substr-function.php

SELECT * FROM artists 
WHERE lower(substr(name,1,1)) in ('a','b','c');

Check string for palindrome

package basicprogm;

public class pallindrome {

  public static void main(String[] args) {
    // TODO Auto-generated method stub

    String s= "madam" ;
    //to store the values that we got in loop
    String t="";
    for(int i=s.length()-1;i>=0;i--){
      t=t+s.charAt(i);
    }
    System.out.println("reversed word is "+ t);

    if (t.matches(s)){
      System.out.println("pallindrome");
    }
    else{
      System.out.println("not pallindrome");
    }
  }
}

Postgres could not connect to server

¿Are you recently changed the pg_hba.conf? if you did just check for any typo in:

"local" is for Unix domain socket connections only

local all all password

IPv4 local connections:

host all all 127.0.0.1/32 password

IPv6 local connections:

host all all ::1/128 password

Sometimes a simple mistake can give us a headache. I hope this help and sorry if my english is no good at all.

How can I insert new line/carriage returns into an element.textContent?

None of the above solutions worked for me. I was trying to add a line feed and additional text to a <p> element. I typically use Firefox, but I do need browser compatibility. I read that only Firefox supports the textContent property, only Internet Explorer supports the innerText property, but both support the innerHTML property. However, neither adding <br /> nor \n nor \r\n to any of those properties resulted in a new line. The following, however, did work:

<html>
<body>
<script type="text/javascript">
  function modifyParagraph() {

  var p;
  p=document.getElementById("paragraphID");
  p.appendChild(document.createElement("br"));
  p.appendChild(document.createTextNode("Additional text."));
}    
</script>

<p id="paragraphID">Original text.</p>

<input type="button" id="pbutton" value="Modify Paragraph" onClick="modifyParagraph()" />
</body>
</html>

How do I install cURL on Windows?

Note: Note to Win32 Users In order to enable this module (cURL) on a Windows environment, libeay32.dll and ssleay32.dll must be present in your PATH. You don't need libcurl.dll from the cURL site.

This note solved my problem. Thought of sharing. libeay32.dll & ssleay.dll you will find in your php installation folder.

How to use multiple LEFT JOINs in SQL?

The required SQL will be some like:-

SELECT * FROM cd
LEFT JOIN ab ON ab.sht = cd.sht
LEFT JOIN aa ON aa.sht = cd.sht
....

Hope it helps.

onchange event for input type="number"

<input type="number" id="n" value="0" step=".5" />
<input type="hidden" id="v" value = "0"/>

<script>
$("#n").bind('keyup mouseup', function () {
    var current = $("#n").val();
    var prevData = $("#v").val(); 
    if(current > prevData || current < prevData){
       $("#v").val(current);
       var newv = $("#v").val(); 
       alert(newv);
    } 
});  
</script>

http://jsfiddle.net/patrickrobles53/s10wLjL3/

I've used a hidden input type to be the container of the previous value that will be needed for the comparison on the next change.

UnsatisfiedDependencyException: Error creating bean with name

There is another instance still same error will shown after you doing everything above mentioned. When you change your codes accordingly mentioned solutions make sure to keep originals. So you can easily go back. So go and again check dispatcher-servelet configuration file's base package location. Is it scanning all relevant packages when you running application.

<context:component-scan base-package="your.pakage.path.here"/>

Pass entire form as data in jQuery Ajax function

In general use serialize() on the form element.

Please be mindful that multiple <select> options are serialized under the same key, e.g.

<select id="foo" name="foo" multiple="multiple">
    <option value="1">one</option>
    <option value="2">two</option>
    <option value="3">three</option>
</select>

will result in a query string that includes multiple occurences of the same query parameter:

[path]?foo=1&foo=2&foo=3&someotherparams...

which may not be what you want in the backend.

I use this JS code to reduce multiple parameters to a comma-separated single key (shamelessly copied from a commenter's response in a thread over at John Resig's place):

function compress(data) {
    data = data.replace(/([^&=]+=)([^&]*)(.*?)&\1([^&]*)/g, "$1$2,$4$3");
    return /([^&=]+=).*?&\1/.test(data) ? compress(data) : data;
}

which turns the above into:

[path]?foo=1,2,3&someotherparams...

In your JS code you'd call it like this:

var inputs = compress($("#your-form").serialize());

Hope that helps.

What is the right way to populate a DropDownList from a database?

You could bind the DropDownList to a data source (DataTable, List, DataSet, SqlDataSource, etc).

For example, if you wanted to use a DataTable:

ddlSubject.DataSource = subjectsTable;
ddlSubject.DataTextField = "SubjectNamne";
ddlSubject.DataValueField = "SubjectID";
ddlSubject.DataBind();

EDIT - More complete example

private void LoadSubjects()
{

    DataTable subjects = new DataTable();

    using (SqlConnection con = new SqlConnection(connectionString))
    {

        try
        {
            SqlDataAdapter adapter = new SqlDataAdapter("SELECT SubjectID, SubjectName FROM Students.dbo.Subjects", con);
            adapter.Fill(subjects);

            ddlSubject.DataSource = subjects;
            ddlSubject.DataTextField = "SubjectNamne";
            ddlSubject.DataValueField = "SubjectID";
            ddlSubject.DataBind();
        }
        catch (Exception ex)
        {
            // Handle the error
        }

    }

    // Add the initial item - you can add this even if the options from the
    // db were not successfully loaded
    ddlSubject.Items.Insert(0, new ListItem("<Select Subject>", "0"));

}

To set an initial value via the markup, rather than code-behind, specify the option(s) and set the AppendDataBoundItems attribute to true:

<asp:DropDownList ID="ddlSubject" runat="server" AppendDataBoundItems="true">
    <asp:ListItem Text="<Select Subject>" Value="0" />
</asp:DropDownList>

You could then bind the DropDownList to a DataSource in the code-behind (just remember to remove:

ddlSubject.Items.Insert(0, new ListItem("<Select Subject>", "0"));

from the code-behind, or you'll have two "" items.

How to test valid UUID/GUID?

I think a better way is using the static method fromString to avoid those regular expressions.

    id = UUID.randomUUID();
    UUID uuid = UUID.fromString(id.toString());
    Assert.assertEquals(id.toString(), uuid.toString());

On the other hand

   UUID uuidFalse = UUID.fromString("x");

throws java.lang.IllegalArgumentException: Invalid UUID string: x

Express-js can't GET my static files, why?

  1. Create a folder with 'public' name in Nodejs project
    folder.
  2. Put index.html file into of Nodejs project folder.
  3. Put all script and css file into public folder.
  4. Use app.use( express.static('public'));

  5. and in index.html correct path of scripts to <script type="text/javascript" src="/javasrc/example.js"></script>

And Now all things work fine.

"detached entity passed to persist error" with JPA/EJB code

remove

user.setId(1);

because it is auto generate on the DB, and continue with persist command.

String delimiter in string.split method

StringTokenizer st = new StringTokenizer("1||1||Abdul-Jabbar||Karim||1996||1974",
             "||");
while(st.hasMoreTokens()){
     System.out.println(st.nextElement());
}

Answer will print

1 1 Abdul-Jabbar Karim 1996 1974

How to print out the method name and line number and conditionally disable NSLog?

NSLog(@"%s %d %s %s", __FILE__, __LINE__, __PRETTY_FUNCTION__, __FUNCTION__);

Outputs file name, line number, and function name:

/proj/cocoa/cdcli/cdcli.m 121 managedObjectContext managedObjectContext

__FUNCTION__ in C++ shows mangled name __PRETTY_FUNCTION__ shows nice function name, in cocoa they look the same.

I'm not sure what is the proper way of disabling NSLog, I did:

#define NSLog

And no logging output showed up, however I don't know if this has any side effects.

Showing empty view when ListView is empty

It should be like this:

<TextView android:id="@android:id/empty"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="No Results" />

Note the id attribute.

App crashing when trying to use RecyclerView on android 5.0

For me the problem was with my activity_main.xml(21) in which the recycleView didn't have an id.

activity_main.xml(21)

 <android.support.v7.widget.RecyclerView
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/button3"
    tools:listitem="@layout/transaction_list_row" />

activity_main.xml

<android.support.v7.widget.RecyclerView

    android:id="@+id/transac_recycler_view"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/button3"
    />

It worked when i added a android:id="@+id/transac_recycler_view" to the activity_main.xml(21) recycleView

IO Error: The Network Adapter could not establish the connection

For me the basic oracle only was not installed. Please ensure you have oracle installed and then try checking host and port.

How to verify Facebook access token?

Just wanted to let you know that up until today I was first obtaining an app access token (via GET request to Facebook), and then using the received token as the app-token-or-admin-token in:

GET graph.facebook.com/debug_token?
    input_token={token-to-inspect}
    &access_token={app-token-or-admin-token}

However, I just realized a better way of doing this (with the added benefit of requiring one less GET request):

GET graph.facebook.com/debug_token?
    input_token={token-to-inspect}
    &access_token={app_id}|{app_secret}

As described in Facebook's documentation for Access Tokens here.

Read all files in a folder and apply a function to each data frame

Here is a tidyverse option that might not the most elegant, but offers some flexibility in terms of what is included in the summary:

library(tidyverse)
dir_path <- '~/path/to/data/directory/'
file_pattern <- 'Df\\.[0-9]\\.csv' # regex pattern to match the file name format

read_dir <- function(dir_path, file_name){
  read_csv(paste0(dir_path, file_name)) %>% 
    mutate(file_name = file_name) %>%                # add the file name as a column              
    gather(variable, value, A:B) %>%                 # convert the data from wide to long
    group_by(file_name, variable) %>% 
    summarize(sum = sum(value, na.rm = TRUE),
              min = min(value, na.rm = TRUE),
              mean = mean(value, na.rm = TRUE),
              median = median(value, na.rm = TRUE),
              max = max(value, na.rm = TRUE))
  }

df_summary <- 
  list.files(dir_path, pattern = file_pattern) %>% 
  map_df(~ read_dir(dir_path, .))

df_summary
# A tibble: 8 x 7
# Groups:   file_name [?]
  file_name variable   sum   min  mean median   max
  <chr>     <chr>    <int> <dbl> <dbl>  <dbl> <dbl>
1 Df.1.csv  A           34     4  5.67    5.5     8
2 Df.1.csv  B           22     1  3.67    3       9
3 Df.2.csv  A           21     1  3.5     3.5     6
4 Df.2.csv  B           16     1  2.67    2.5     5
5 Df.3.csv  A           30     0  5       5      11
6 Df.3.csv  B           43     1  7.17    6.5    15
7 Df.4.csv  A           21     0  3.5     3       8
8 Df.4.csv  B           42     1  7       6      16

HTML - Display image after selecting filename

Here You Go:

HTML

<!DOCTYPE html>
<html>
<head>
<link class="jsbin" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
  <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
  article, aside, figure, footer, header, hgroup, 
  menu, nav, section { display: block; }
</style>
</head>
<body>
  <input type='file' onchange="readURL(this);" />
    <img id="blah" src="#" alt="your image" />
</body>
</html>

Script:

function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#blah')
                    .attr('src', e.target.result)
                    .width(150)
                    .height(200);
            };

            reader.readAsDataURL(input.files[0]);
        }
    }

Live Demo

Dictionary with list of strings as value

A simpler way of doing it is:

var dictionary = list.GroupBy(it => it.Key).ToDictionary(dict => dict.Key, dict => dict.Select(item => item.value).ToList());

How do I get the height of a div's full content with jQuery?

We can also use -

$('#x').prop('scrollHeight') <!-- Height -->
$('#x').prop('scrollWidth')  <!-- Width -->

How to calculate the number of days between two dates?

From my little date difference calculator:

var startDate = new Date(2000, 1-1, 1);  // 2000-01-01
var endDate =   new Date();              // Today

// Calculate the difference of two dates in total days
function diffDays(d1, d2)
{
  var ndays;
  var tv1 = d1.valueOf();  // msec since 1970
  var tv2 = d2.valueOf();

  ndays = (tv2 - tv1) / 1000 / 86400;
  ndays = Math.round(ndays - 0.5);
  return ndays;
}

So you would call:

var nDays = diffDays(startDate, endDate);

(Full source at http://david.tribble.com/src/javascript/jstimespan.html.)

Addendum

The code can be improved by changing these lines:

  var tv1 = d1.getTime();  // msec since 1970
  var tv2 = d2.getTime();

Why there is no ConcurrentHashSet against ConcurrentHashMap

Why not use: CopyOnWriteArraySet from java.util.concurrent?

Call PowerShell script PS1 from another PS1 script inside Powershell ISE

In order to find the location of a script, use Split-Path $MyInvocation.MyCommand.Path (make sure you use this in the script context).

The reason you should use that and not anything else can be illustrated with this example script.

## ScriptTest.ps1
Write-Host "InvocationName:" $MyInvocation.InvocationName
Write-Host "Path:" $MyInvocation.MyCommand.Path

Here are some results.

PS C:\Users\JasonAr> .\ScriptTest.ps1
InvocationName: .\ScriptTest.ps1
Path: C:\Users\JasonAr\ScriptTest.ps1

PS C:\Users\JasonAr> . .\ScriptTest.ps1
InvocationName: .
Path: C:\Users\JasonAr\ScriptTest.ps1

PS C:\Users\JasonAr> & ".\ScriptTest.ps1"
InvocationName: &
Path: C:\Users\JasonAr\ScriptTest.ps1

In PowerShell 3.0 and later you can use the automatic variable $PSScriptRoot:

## ScriptTest.ps1
Write-Host "Script:" $PSCommandPath
Write-Host "Path:" $PSScriptRoot
PS C:\Users\jarcher> .\ScriptTest.ps1
Script: C:\Users\jarcher\ScriptTest.ps1
Path: C:\Users\jarcher

How to render html with AngularJS templates

To do this, I use a custom filter.

In my app:

myApp.filter('rawHtml', ['$sce', function($sce){
  return function(val) {
    return $sce.trustAsHtml(val);
  };
}]);

Then, in the view:

<h1>{{ stuff.title}}</h1>

<div ng-bind-html="stuff.content | rawHtml"></div>

Git: How to remove file from index without deleting files from any repository

The above solutions work fine for most cases. However, if you also need to remove all traces of that file (ie sensitive data such as passwords), you will also want to remove it from your entire commit history, as the file could still be retrieved from there.

Here is a solution that removes all traces of the file from your entire commit history, as though it never existed, yet keeps the file in place on your system.

https://help.github.com/articles/remove-sensitive-data/

You can actually skip to step 3 if you are in your local git repository, and don't need to perform a dry run. In my case, I only needed steps 3 and 6, as I had already created my .gitignore file, and was in the repository I wanted to work on.

To see your changes, you may need to go to the GitHub root of your repository and refresh the page. Then navigate through the links to get to an old commit that once had the file, to see that it has now been removed. For me, simply refreshing the old commit page did not show the change.

It looked intimidating at first, but really, was easy and worked like a charm ! :-)

Rename a file using Java

This is an easy way to rename a file:

        File oldfile =new File("test.txt");
        File newfile =new File("test1.txt");

        if(oldfile.renameTo(newfile)){
            System.out.println("File renamed");
        }else{
            System.out.println("Sorry! the file can't be renamed");
        }

change type of input field with jQuery

Have you tried using .prop()?

$("#password").prop('type','text');

http://api.jquery.com/prop/

How to use Fiddler to monitor WCF service

Standard WCF Tracing/Diagnostics

If for some reason you are unable to get Fiddler to work, or would rather log the requests another way, another option is to use the standard WCF tracing functionality. This will produce a file that has a nice viewer.

Docs

See https://docs.microsoft.com/en-us/dotnet/framework/wcf/samples/tracing-and-message-logging

Configuration

Add the following to your config, make sure c:\logs exists, rebuild, and make requests:

  <system.serviceModel>
    <diagnostics>
      <!-- Enable Message Logging here. -->
      <!-- log all messages received or sent at the transport or service model levels -->
      <messageLogging logEntireMessage="true"
                      maxMessagesToLog="300"
                      logMessagesAtServiceLevel="true"
                      logMalformedMessages="true"
                      logMessagesAtTransportLevel="true" />
    </diagnostics>
  </system.serviceModel>

  <system.diagnostics>
    <sources>
      <source name="System.ServiceModel" switchValue="Information,ActivityTracing"
        propagateActivity="true">
        <listeners>
          <add name="xml" />
        </listeners>
      </source>
      <source name="System.ServiceModel.MessageLogging">
        <listeners>
          <add name="xml" />
        </listeners>
      </source>
    </sources>
    <sharedListeners>
      <add initializeData="C:\logs\TracingAndLogging-client.svclog" type="System.Diagnostics.XmlWriterTraceListener"
        name="xml" />
    </sharedListeners>
    <trace autoflush="true" />
  </system.diagnostics>

Regex (grep) for multi-line search needed

I am not very good in grep. But your problem can be solved using AWK command. Just see

awk '/select/,/from/' *.sql

The above code will result from first occurence of select till first sequence of from. Now you need to verify whether returned statements are having customername or not. For this you can pipe the result. And can use awk or grep again.

Best Practice for Forcing Garbage Collection in C#

Not sure if it is a best practice, but when working with large amounts of images in a loop (i.e. creating and disposing a lot of Graphics/Image/Bitmap objects), i regularly let the GC.Collect.

I think I read somewhere that the GC only runs when the program is (mostly) idle, and not in the middle of a intensive loop, so that could look like an area where manual GC could make sense.

How do I select an element that has a certain class?

It should be this way:

h2.myClass looks for h2 with class myClass. But you actually want to apply style for h2 inside .myClass so you can use descendant selector .myClass h2.

h2 {
    color: red;
}

.myClass {
    color: green;
}

.myClass h2 {
    color: blue;
}

Demo

This ref will give you some basic idea about the selectors and have a look at descendant selectors

update to python 3.7 using anaconda

run conda navigator, you can upgrade your packages easily in the friendly GUI

Git merge errors

as suggested in git status,

Unmerged paths:                                                                                                                                
(use "git add <file>..." to mark resolution)                                                                                                 

    both modified:   a.jl                                  
    both modified:   b.jl

I used git add to finish the merging, then git checkout works fine.

Formula px to dp, dp to px android

Below funtions worked well for me across devices.

It is taken from https://gist.github.com/laaptu/7867851

public static float convertPixelsToDp(float px){
    DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
    float dp = px / (metrics.densityDpi / 160f);
    return Math.round(dp);
}

public static float convertDpToPixel(float dp){
    DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
    float px = dp * (metrics.densityDpi / 160f);
    return Math.round(px);
}

How to convert UTF-8 byte[] to string?

A general solution to convert from byte array to string when you don't know the encoding:

static string BytesToStringConverted(byte[] bytes)
{
    using (var stream = new MemoryStream(bytes))
    {
        using (var streamReader = new StreamReader(stream))
        {
            return streamReader.ReadToEnd();
        }
    }
}

How to get the last five characters of a string using Substring() in C#?

static void Main()
    {
        string input = "OneTwoThree";

            //Get last 5 characters
        string sub = input.Substring(6);
        Console.WriteLine("Substring: {0}", sub); // Output Three. 
    }
  • Substring(0, 3) - Returns substring of first 3 chars. //One

  • Substring(3, 3) - Returns substring of second 3 chars. //Two

  • Substring(6) - Returns substring of all chars after first 6. //Three

Select distinct rows from datatable in Linq

Dim distinctValues As List(Of Double) = (From r In _
DirectCast(DataTable.AsEnumerable(),IEnumerable(Of DataRow)) Where (Not r.IsNull("ColName")) _
Select r.Field(Of Double)("ColName")).Distinct().ToList()

Making HTTP Requests using Chrome Developer tools

If you want to do a POST from the same domain, you can always insert a form into the DOM using Developer tools and submit that:

Inserted form into document

Getting JavaScript object key list

Underscore.js makes the transformation pretty clean:

var keys = _.map(x, function(v, k) { return k; });

Edit: I missed that you can do this too:

var keys = _.keys(x);

How can I delay a method call for 1 second?

Swift 2.x

let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * Double(NSEC_PER_SEC)))
 dispatch_after(delayTime, dispatch_get_main_queue()) {
 print("do some work")
}

Swift 3.x --&-- Swift 4

DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
    print("do some work")
}

or pass a escaping closure

func delay(seconds: Double, completion: @escaping()-> Void) {
    DispatchQueue.main.asyncAfter(deadline: .now() + seconds, execute: completion)
}

JavaScript function in href vs. onclick

In terms of javascript, one difference is that the this keyword in the onclick handler will refer to the DOM element whose onclick attribute it is (in this case the <a> element), whereas this in the href attribute will refer to the window object.

In terms of presentation, if an href attribute is absent from a link (i.e. <a onclick="[...]">) then, by default, browsers will display the text cursor (and not the often-desired pointer cursor) since it is treating the <a> as an anchor, and not a link.

In terms of behavior, when specifying an action by navigation via href, the browser will typically support opening that href in a separate window using either a shortcut or context menu. This is not possible when specifying an action only via onclick.


However, if you're asking what is the best way to get dynamic action from the click of a DOM object, then attaching an event using javascript separate from the content of the document is the best way to go. You could do this in a number of ways. A common way is to use a javascript library like jQuery to bind an event:

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<a id="link" href="http://example.com/action">link text</a>
<script type="text/javascript">
    $('a#link').click(function(){ /* ... action ... */ })
</script>

How to get a Color from hexadecimal Color String

I use this and it works great for me for setting any color I want.

public static final int MY_COLOR = Color.rgb(255, 102, 153);

Set the colors using 0-255 for each red, green and blue then anywhere you want that color used just put MY_COLOR instead of Color.BLUE or Color.RED or any of the other static colors the Color class offers.

Just do a Google search for color chart and it you can find a chart with the correct RGB codes using 0-255.

Eclipse reported "Failed to load JNI shared library"

Installing a 64-bit version of Java will solve the issue. Go to page Java Downloads for All Operating Systems

This is a problem due to the incompatibility of the Java version and the Eclipse version both should be 64 bit if you are using a 64-bit system.

How to create a jar with external libraries included in Eclipse?

If you want to export all JAR-files of a Java web-project, open the latest generated WAR-file with a ZIP-tool (e.g. 7-Zip), navigate to the /WEB-INF/lib/ folder. Here you will find all JAR-files you need for this project (as listed in "Referenced Libraries").

Best cross-browser method to capture CTRL+S with JQuery?

@Eevee: As the browser becomes the home for richer and richer functionality and starts to replace desktop apps, it's just not going to be an option to forgo the use of keyboard shortcuts. Gmail's rich and intuitive set of keyboard commands was instrumental in my willingness to abandon Outlook. The keyboard shortcuts in Todoist, Google Reader, and Google Calendar all make my life much, much easier on a daily basis.

Developers should definitely be careful not to override keystrokes that already have a meaning in the browser. For example, the WMD textbox I'm typing into inexplicably interprets Ctrl+Del as "Blockquote" rather than "delete word forward". I'm curious if there's a standard list somewhere of "browser-safe" shortcuts that site developers can use and that browsers will commit to staying away from in future versions.

Identifier not found error on function call

Add this line before main function:

void swapCase (char* name);

int main()
{
   ...
   swapCase(name);    // swapCase prototype should be known at this point
   ...
}

This is called forward declaration: compiler needs to know function prototype when function call is compiled.

Declare a variable in DB2 SQL

I imagine this forum posting, which I quote fully below, should answer the question.


Inside a procedure, function, or trigger definition, or in a dynamic SQL statement (embedded in a host program):

BEGIN ATOMIC
 DECLARE example VARCHAR(15) ;
 SET example = 'welcome' ;
 SELECT *
 FROM   tablename
 WHERE  column1 = example ;
END

or (in any environment):

WITH t(example) AS (VALUES('welcome'))
SELECT *
FROM   tablename, t
WHERE  column1 = example

or (although this is probably not what you want, since the variable needs to be created just once, but can be used thereafter by everybody although its content will be private on a per-user basis):

CREATE VARIABLE example VARCHAR(15) ;
SET example = 'welcome' ;
SELECT *
FROM   tablename
WHERE  column1 = example ;

How do I programmatically force an onchange event on an input?

For some reason ele.onchange() is throwing a "method not found" expception for me in IE on my page, so I ended up using this function from the link Kolten provided and calling fireEvent(ele, 'change'), which worked:

function fireEvent(element,event){
    if (document.createEventObject){
        // dispatch for IE
        var evt = document.createEventObject();
        return element.fireEvent('on'+event,evt)
    }
    else{
        // dispatch for firefox + others
        var evt = document.createEvent("HTMLEvents");
        evt.initEvent(event, true, true ); // event type,bubbling,cancelable
        return !element.dispatchEvent(evt);
    }
}

I did however, create a test page that confirmed calling should onchange() work:

<input id="test1" name="test1" value="Hello" onchange="alert(this.value);"/>
<input type="button" onclick="document.getElementById('test1').onchange();" value="Say Hello"/>

Edit: The reason ele.onchange() didn't work was because I hadn't actually declared anything for the onchange event. But the fireEvent still works.

How to sparsely checkout only one single file from a git repository?

In git you do not 'checkout' files before you update them - it seems like this is what you are after.

Many systems like clearcase, csv and so on require you to 'checkout' a file before you can make changes to it. Git does not require this. You clone a repository and then make changes in your local copy of repository.

Once you updated files you can do:

git status

To see what files have been modified. You add the ones you want to commit to index first with (index is like a list to be checked in):

git add .

or

git add blah.c

Then do git status will show you which files were modified and which are in index ready to be commited or checked in.

To commit files to your copy of repository do:

git commit -a -m "commit message here"

See git website for links to manuals and guides.

GroupBy pandas DataFrame and select most common value

A little late to the game here, but I was running into some performance issues with HYRY's solution, so I had to come up with another one.

It works by finding the frequency of each key-value, and then, for each key, only keeping the value that appears with it most often.

There's also an additional solution that supports multiple modes.

On a scale test that's representative of the data I'm working with, this reduced runtime from 37.4s to 0.5s!

Here's the code for the solution, some example usage, and the scale test:

import numpy as np
import pandas as pd
import random
import time

test_input = pd.DataFrame(columns=[ 'key',          'value'],
                          data=  [[ 1,              'A'    ],
                                  [ 1,              'B'    ],
                                  [ 1,              'B'    ],
                                  [ 1,              np.nan ],
                                  [ 2,              np.nan ],
                                  [ 3,              'C'    ],
                                  [ 3,              'C'    ],
                                  [ 3,              'D'    ],
                                  [ 3,              'D'    ]])

def mode(df, key_cols, value_col, count_col):
    '''                                                                                                                                                                                                                                                                                                                                                              
    Pandas does not provide a `mode` aggregation function                                                                                                                                                                                                                                                                                                            
    for its `GroupBy` objects. This function is meant to fill                                                                                                                                                                                                                                                                                                        
    that gap, though the semantics are not exactly the same.                                                                                                                                                                                                                                                                                                         

    The input is a DataFrame with the columns `key_cols`                                                                                                                                                                                                                                                                                                             
    that you would like to group on, and the column                                                                                                                                                                                                                                                                                                                  
    `value_col` for which you would like to obtain the mode.                                                                                                                                                                                                                                                                                                         

    The output is a DataFrame with a record per group that has at least one mode                                                                                                                                                                                                                                                                                     
    (null values are not counted). The `key_cols` are included as columns, `value_col`                                                                                                                                                                                                                                                                               
    contains a mode (ties are broken arbitrarily and deterministically) for each                                                                                                                                                                                                                                                                                     
    group, and `count_col` indicates how many times each mode appeared in its group.                                                                                                                                                                                                                                                                                 
    '''
    return df.groupby(key_cols + [value_col]).size() \
             .to_frame(count_col).reset_index() \
             .sort_values(count_col, ascending=False) \
             .drop_duplicates(subset=key_cols)

def modes(df, key_cols, value_col, count_col):
    '''                                                                                                                                                                                                                                                                                                                                                              
    Pandas does not provide a `mode` aggregation function                                                                                                                                                                                                                                                                                                            
    for its `GroupBy` objects. This function is meant to fill                                                                                                                                                                                                                                                                                                        
    that gap, though the semantics are not exactly the same.                                                                                                                                                                                                                                                                                                         

    The input is a DataFrame with the columns `key_cols`                                                                                                                                                                                                                                                                                                             
    that you would like to group on, and the column                                                                                                                                                                                                                                                                                                                  
    `value_col` for which you would like to obtain the modes.                                                                                                                                                                                                                                                                                                        

    The output is a DataFrame with a record per group that has at least                                                                                                                                                                                                                                                                                              
    one mode (null values are not counted). The `key_cols` are included as                                                                                                                                                                                                                                                                                           
    columns, `value_col` contains lists indicating the modes for each group,                                                                                                                                                                                                                                                                                         
    and `count_col` indicates how many times each mode appeared in its group.                                                                                                                                                                                                                                                                                        
    '''
    return df.groupby(key_cols + [value_col]).size() \
             .to_frame(count_col).reset_index() \
             .groupby(key_cols + [count_col])[value_col].unique() \
             .to_frame().reset_index() \
             .sort_values(count_col, ascending=False) \
             .drop_duplicates(subset=key_cols)

print test_input
print mode(test_input, ['key'], 'value', 'count')
print modes(test_input, ['key'], 'value', 'count')

scale_test_data = [[random.randint(1, 100000),
                    str(random.randint(123456789001, 123456789100))] for i in range(1000000)]
scale_test_input = pd.DataFrame(columns=['key', 'value'],
                                data=scale_test_data)

start = time.time()
mode(scale_test_input, ['key'], 'value', 'count')
print time.time() - start

start = time.time()
modes(scale_test_input, ['key'], 'value', 'count')
print time.time() - start

start = time.time()
scale_test_input.groupby(['key']).agg(lambda x: x.value_counts().index[0])
print time.time() - start

Running this code will print something like:

   key value
0    1     A
1    1     B
2    1     B
3    1   NaN
4    2   NaN
5    3     C
6    3     C
7    3     D
8    3     D
   key value  count
1    1     B      2
2    3     C      2
   key  count   value
1    1      2     [B]
2    3      2  [C, D]
0.489614009857
9.19386196136
37.4375009537

Hope this helps!

ES6 export default with multiple functions referring to each other

tl;dr: baz() { this.foo(); this.bar() }

In ES2015 this construct:

var obj = {
    foo() { console.log('foo') }
}

is equal to this ES5 code:

var obj = {
    foo : function foo() { console.log('foo') }
}

exports.default = {} is like creating an object, your default export translates to ES5 code like this:

exports['default'] = {
    foo: function foo() {
        console.log('foo');
    },
    bar: function bar() {
        console.log('bar');
    },
    baz: function baz() {
        foo();bar();
    }
};

now it's kind of obvious (I hope) that baz tries to call foo and bar defined somewhere in the outer scope, which are undefined. But this.foo and this.bar will resolve to the keys defined in exports['default'] object. So the default export referencing its own methods shold look like this:

export default {
    foo() { console.log('foo') }, 
    bar() { console.log('bar') },
    baz() { this.foo(); this.bar() }
}

See babel repl transpiled code.

text flowing out of div

i recently encountered this. I used: display:block;

Java default constructor

A default constructor is automatically generated by the compiler if you do not explicitly define at least one constructor in your class. You've defined two, so your class does not have a default constructor.

Per The Java Language Specification Third Edition:

8.8.9 Default Constructor

If a class contains no constructor declarations, then a default constructor that takes no parameters is automatically provided...

Could not load file or assembly CrystalDecisions.ReportAppServer.ClientDoc

Regarding the 64-bit system wanting 32-bit support. I don't find it so bizarre:

Although deployed to a 64-bit system, this doesn't mean all the referenced assemblies are necessarily 64-bit Crystal Reports assemblies. Further to that, the Crystal Reports assemblies are largely just wrappers to a collection of legacy DLLs upon which they are based. Many 32-bit DLLs are required by the primarily referenced assembly. The error message "can not load the assembly" involves these DLLs as well. To see visually what those are, go to www.dependencywalker.com and run 'Depends' on the assembly in question, directly on that IIS server.

AngularJS check if form is valid in controller

The BusinessCtrl is initialised before the createBusinessForm's FormController. Even if you have the ngController on the form won't work the way you wanted. You can't help this (you can create your ngControllerDirective, and try to trick the priority.) this is how angularjs works.

See this plnkr for example: http://plnkr.co/edit/WYyu3raWQHkJ7XQzpDtY?p=preview

Vue template or render function not defined yet I am using neither?

I had this script in app.js in laravel which automatically adds all components in the component folder.

const files = require.context('./', true, /\.vue$/i)
files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key)))

To make it work just add default

const files = require.context('./', true, /\.vue$/i)
files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default))

Inserting a text where cursor is using Javascript/jquery

I think you could use the following JavaScript to track the last-focused textbox:

<script>
var holdFocus;

function updateFocus(x)
{
    holdFocus = x;
}

function appendTextToLastFocus(text)
{
    holdFocus.value += text;
}
</script>

Usage:

<input type="textbox" onfocus="updateFocus(this)" />
<a href="#" onclick="appendTextToLastFocus('textToAppend')" />

A previous solution (props to gclaghorn) uses textarea and calculates the position of the cursor too, so it may be better for what you want. On the other hand, this one would be more lightweight, if that's what you're looking for.

How to compare two colors for similarity/difference

The only "right" way to compare colors is to do it with deltaE in CIELab or CIELuv.

But for a lot of applications I think this is a good enough approximation:

distance = 3 * |dR| + 4 * |dG| + 3 * |dB|

I think a weighted manhattan distance makes a lot more sense when comparing colors. Remember that color primaries are only in our head. They don't have any physical significance. CIELab and CIELuv is modelled statistically from our perception of color.

C pointers and arrays: [Warning] assignment makes pointer from integer without a cast

In this case a[4] is the 5th integer in the array a, ap is a pointer to integer, so you are assigning an integer to a pointer and that's the warning.
So ap now holds 45 and when you try to de-reference it (by doing *ap) you are trying to access a memory at address 45, which is an invalid address, so your program crashes.

You should do ap = &(a[4]); or ap = a + 4;

In c array names decays to pointer, so a points to the 1st element of the array.
In this way, a is equivalent to &(a[0]).

Can you nest html forms?

In a word, no. You can have several forms in a page but they should not be nested.

From the html5 working draft:

4.10.3 The form element

Content model:

Flow content, but with no form element descendants.

Get the last inserted row ID (with SQL statement)

If your SQL Server table has a column of type INT IDENTITY (or BIGINT IDENTITY), then you can get the latest inserted value using:

INSERT INTO dbo.YourTable(columns....)
   VALUES(..........)

SELECT SCOPE_IDENTITY()

This works as long as you haven't inserted another row - it just returns the last IDENTITY value handed out in this scope here.

There are at least two more options - @@IDENTITY and IDENT_CURRENT - read more about how they works and in what way they're different (and might give you unexpected results) in this excellent blog post by Pinal Dave here.

Is it possible to get the current spark context settings in PySpark?

Spark 1.6+

sc.getConf.getAll.foreach(println)

.NET obfuscation tools/strategy

I have tried a product called Rummage and it does a good job in giving you some control ... Although it lacks many things that Eziriz offers but price for Rummage is too good...

Android - set TextView TextStyle programmatically?

textview.setTypeface(Typeface.DEFAULT_BOLD);

setTypeface is the Attribute textStyle.

As Shankar V added, to preserve the previously set typeface attributes you can use:

textview.setTypeface(textview.getTypeface(), Typeface.BOLD);

Visual Studio: Relative Assembly References Paths

Yes, just create a directory in your solution like lib/, and then add your dll to that directory in the filesystem and add it in the project (Add->Existing Item->etc). Then add the reference based on your project.

I have done this several times under svn and under cvs.

How to handle floats and decimal separators with html5 input type number

According to w3.org the value attribute of the number input is defined as a floating-point number. The syntax of the floating-point number seems to only accept dots as decimal separators.

I've listed a few options below that might be helpful to you:

1. Using the pattern attribute

With the pattern attribute you can specify the allowed format with a regular expression in a HTML5 compatible way. Here you could specify that the comma character is allowed and a helpful feedback message if the pattern fails.

<input type="number" pattern="[0-9]+([,\.][0-9]+)?" name="my-num"
           title="The number input must start with a number and use either comma or a dot as a decimal character."/>

Note: Cross-browser support varies a lot. It may be complete, partial or non-existant..

2. JavaScript validation

You could try to bind a simple callback to for example the onchange (and/or blur) event that would either replace the comma or validate all together.

3. Disable browser validation ##

Thirdly you could try to use the formnovalidate attribute on the number inputs with the intention of disabling browser validation for that field all together.

<input type="number" formnovalidate />

4. Combination..?

<input type="number" pattern="[0-9]+([,\.][0-9]+)?" 
           name="my-num" formnovalidate
           title="The number input must start with a number and use either comma or a dot as a decimal character."/>

How do I copy a hash in Ruby?

you can use below to deep copy Hash objects.

deeply_copied_hash = Marshal.load(Marshal.dump(original_hash))

How to concatenate multiple lines of output to one line?

Piping output to xargs will concatenate each line of output to a single line with spaces:

grep pattern file | xargs

Or any command, eg. ls | xargs. The default limit of xargs output is ~4096 characters, but can be increased with eg. xargs -s 8192.

Entity Framework Join 3 Tables

I think it will be easier using syntax-based query:

var entryPoint = (from ep in dbContext.tbl_EntryPoint
                 join e in dbContext.tbl_Entry on ep.EID equals e.EID
                 join t in dbContext.tbl_Title on e.TID equals t.TID
                 where e.OwnerID == user.UID
                 select new {
                     UID = e.OwnerID,
                     TID = e.TID,
                     Title = t.Title,
                     EID = e.EID
                 }).Take(10);

And you should probably add orderby clause, to make sure Top(10) returns correct top ten items.

How to get the selected value from RadioButtonList?

The ASPX code will look something like this:

 <asp:RadioButtonList ID="rblist1" runat="server">

    <asp:ListItem Text ="Item1" Value="1" />
    <asp:ListItem Text ="Item2" Value="2" />
    <asp:ListItem Text ="Item3" Value="3" />
    <asp:ListItem Text ="Item4" Value="4" />

    </asp:RadioButtonList>

    <asp:Button ID="btn1" runat="server" OnClick="Button1_Click" Text="select value" />

And the code behind:

protected void Button1_Click(object sender, EventArgs e)
        {
            string selectedValue = rblist1.SelectedValue;
            Response.Write(selectedValue);
        }

Carriage Return\Line feed in Java

The method newLine() ensures a platform-compatible new line is added (0Dh 0Ah for DOS, 0Dh for older Macs, 0Ah for Unix/Linux). Java has no way of knowing on which platform you are going to send the text. This conversion should be taken care of by the mail sending entities.

How do I pass data between Activities in Android application?

You can use intent class to send data between Activities. It is basically a message to OS where you describe source and destination of data flow. Like data from A to B activity.

In ACTIVITY A (the source):

Intent intent = new Intent(A.this, B.class);

intent.putExtra("KEY","VALUE");

startActivity(intent);

In Activity B (the destination)->

Intent intent =getIntent();

String data =intent.getString("KEY");

Here you will get data for key "KEY"

FOR BETTER USE ALWAYS KEYS SHOULD BE STORED IN A CLASS FOR SIMPLICITY AND IT WILL HELP IN MINNIMISE THE RISK OF TYPING ERRORS

Like this:

public class Constants{
public static String KEY="KEY"
}

Now In ACTIVITY A:

intent.putExtra(Constants.KEY,"VALUE");

In Activity B:

String data =intent.getString(Constants.KEY);

C++ Get name of type in template

As a rephrasing of Andrey's answer:

The Boost TypeIndex library can be used to print names of types.

Inside a template, this might read as follows

#include <boost/type_index.hpp>
#include <iostream>

template<typename T>
void printNameOfType() {
    std::cout << "Type of T: " 
              << boost::typeindex::type_id<T>().pretty_name() 
              << std::endl;
}

Permutation of array

Here is how you can print all permutations in 10 lines of code:

public class Permute{
    static void permute(java.util.List<Integer> arr, int k){
        for(int i = k; i < arr.size(); i++){
            java.util.Collections.swap(arr, i, k);
            permute(arr, k+1);
            java.util.Collections.swap(arr, k, i);
        }
        if (k == arr.size() -1){
            System.out.println(java.util.Arrays.toString(arr.toArray()));
        }
    }
    public static void main(String[] args){
        Permute.permute(java.util.Arrays.asList(3,4,6,2,1), 0);
    }
}

You take first element of an array (k=0) and exchange it with any element (i) of the array. Then you recursively apply permutation on array starting with second element. This way you get all permutations starting with i-th element. The tricky part is that after recursive call you must swap i-th element with first element back, otherwise you could get repeated values at the first spot. By swapping it back we restore order of elements (basically you do backtracking).

Iterators and Extension to the case of repeated values

The drawback of previous algorithm is that it is recursive, and does not play nicely with iterators. Another issue is that if you allow repeated elements in your input, then it won't work as is.

For example, given input [3,3,4,4] all possible permutations (without repetitions) are

[3, 3, 4, 4]
[3, 4, 3, 4]
[3, 4, 4, 3]
[4, 3, 3, 4]
[4, 3, 4, 3]
[4, 4, 3, 3]

(if you simply apply permute function from above you will get [3,3,4,4] four times, and this is not what you naturally want to see in this case; and the number of such permutations is 4!/(2!*2!)=6)

It is possible to modify the above algorithm to handle this case, but it won't look nice. Luckily, there is a better algorithm (I found it here) which handles repeated values and is not recursive.

First note, that permutation of array of any objects can be reduced to permutations of integers by enumerating them in any order.

To get permutations of an integer array, you start with an array sorted in ascending order. You 'goal' is to make it descending. To generate next permutation you are trying to find the first index from the bottom where sequence fails to be descending, and improves value in that index while switching order of the rest of the tail from descending to ascending in this case.

Here is the core of the algorithm:

//ind is an array of integers
for(int tail = ind.length - 1;tail > 0;tail--){
    if (ind[tail - 1] < ind[tail]){//still increasing

        //find last element which does not exceed ind[tail-1]
        int s = ind.length - 1;
        while(ind[tail-1] >= ind[s])
            s--;

        swap(ind, tail-1, s);

        //reverse order of elements in the tail
        for(int i = tail, j = ind.length - 1; i < j; i++, j--){
            swap(ind, i, j);
        }
        break;
    }
}

Here is the full code of iterator. Constructor accepts an array of objects, and maps them into an array of integers using HashMap.

import java.lang.reflect.Array;
import java.util.*;
class Permutations<E> implements  Iterator<E[]>{

    private E[] arr;
    private int[] ind;
    private boolean has_next;

    public E[] output;//next() returns this array, make it public

    Permutations(E[] arr){
        this.arr = arr.clone();
        ind = new int[arr.length];
        //convert an array of any elements into array of integers - first occurrence is used to enumerate
        Map<E, Integer> hm = new HashMap<E, Integer>();
        for(int i = 0; i < arr.length; i++){
            Integer n = hm.get(arr[i]);
            if (n == null){
                hm.put(arr[i], i);
                n = i;
            }
            ind[i] = n.intValue();
        }
        Arrays.sort(ind);//start with ascending sequence of integers


        //output = new E[arr.length]; <-- cannot do in Java with generics, so use reflection
        output = (E[]) Array.newInstance(arr.getClass().getComponentType(), arr.length);
        has_next = true;
    }

    public boolean hasNext() {
        return has_next;
    }

    /**
     * Computes next permutations. Same array instance is returned every time!
     * @return
     */
    public E[] next() {
        if (!has_next)
            throw new NoSuchElementException();

        for(int i = 0; i < ind.length; i++){
            output[i] = arr[ind[i]];
        }


        //get next permutation
        has_next = false;
        for(int tail = ind.length - 1;tail > 0;tail--){
            if (ind[tail - 1] < ind[tail]){//still increasing

                //find last element which does not exceed ind[tail-1]
                int s = ind.length - 1;
                while(ind[tail-1] >= ind[s])
                    s--;

                swap(ind, tail-1, s);

                //reverse order of elements in the tail
                for(int i = tail, j = ind.length - 1; i < j; i++, j--){
                    swap(ind, i, j);
                }
                has_next = true;
                break;
            }

        }
        return output;
    }

    private void swap(int[] arr, int i, int j){
        int t = arr[i];
        arr[i] = arr[j];
        arr[j] = t;
    }

    public void remove() {

    }
}

Usage/test:

    TCMath.Permutations<Integer> perm = new TCMath.Permutations<Integer>(new Integer[]{3,3,4,4,4,5,5});
    int count = 0;
    while(perm.hasNext()){
        System.out.println(Arrays.toString(perm.next()));
        count++;
    }
    System.out.println("total: " + count);

Prints out all 7!/(2!*3!*2!)=210 permutations.

pdftk compression option

Trying to compress a PDF I made with 400ppi tiffs, mostly 8-bit, a few 24-bit, with PackBits compression, using tiff2pdf compressed with Zip/Deflate. One problem I had with every one of these methods: none of the above methods preserved the bookmarks TOC that I painstakingly manually created in Acrobat Pro X. Not even the recommended ebook setting for gs. Sure, I could just open a copy of the original with the TOC intact and do a Replace pages but unfortunately, none of these methods did a satisfactory job to begin with. Either they reduced the size so much that the quality was unacceptably pixellated, or they didn't reduce the size at all and in one case actually increased it despite quality loss.

pdftk compress:

no change in size
bookmarks TOC are gone

gs screen:

takes a ridiculously long time and 100% CPU
errors:
    sfopen: gs_parse_file_name failed.                                 ? 
    | ./base/gsicc_manage.c:1651: gsicc_set_device_profile(): cannot find device profile
74.8MB-->10.2MB hideously pixellated
bookmarks TOC are gone

gs printer:

takes a ridiculously long time and 100% CPU
no errors
74.8MB-->66.1MB
light blue background on pages 1-4
bookmarks TOC are gone

gs ebook:

errors:
    sfopen: gs_parse_file_name failed.
      ./base/gsicc_manage.c:1050: gsicc_open_search(): Could not find default_rgb.ic 
    | ./base/gsicc_manage.c:1651: gsicc_set_device_profile(): cannot find device profile
74.8MB-->32.2MB
badly pixellated
bookmarks TOC are gone

qpdf --linearize:

very fast, a few seconds
no size change
bookmarks TOC are gone

pdf2ps:

took very long time
output_pdf2ps.ps 74.8MB-->331.6MB

ps2pdf:

pretty fast
74.8MB-->79MB
very slightly degraded with sl. bluish background
bookmarks TOC are gone

Override console.log(); for production

Put this at the top of the file:

var console = {};
console.log = function(){};

For some browsers and minifiers, you may need to apply this onto the window object.

window.console = console;