Programs & Examples On #Extjs

Sencha Ext JS is a JavaScript framework for building rich Internet applications (RIAs).

How to stop a setTimeout loop?

var myVar = null;

if(myVar)
   clearTimeout(myVar);

myVar = setTimeout(function(){ alert("Hello"); }, 3000);

How to display binary data as image - extjs 4

In ExtJs, you can use

xtype: 'image'

to render a image.

Here is a fiddle showing rendering of binary data with extjs.

atob -- > converts ascii to binary

btoa -- > converts binary to ascii

Ext.application({
    name: 'Fiddle',

    launch: function () {
        var srcBase64 = "data:image/jpeg;base64," + btoa(atob("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8H8hYDwAFegHS8+X7mgAAAABJRU5ErkJggg=="));

        Ext.create("Ext.panel.Panel", {
            title: "Test",
            renderTo: Ext.getBody(),
            height: 400,
            items: [{
                xtype: 'image',
                width: 100,
                height: 100,
                src: srcBase64
            }]
        })
    }
});

https://fiddle.sencha.com/#view/editor&fiddle/28h0

How can I let a user download multiple files when a button is clicked?

//It is possible when using Tampermonkey (Firefox or Chrome).
//They added the GM_Download command.
//You can use it like this download multiple files One time:


// ==UserScript==
// @name        
// @description 
// @match       
// @grant       
// @grant       GM_download
function setup_reader(file) {
    var name = file.name;
    var reader = new FileReader();
    reader.onload = function (e) {
        var bin = e.target.result; //get file content
        var lines = bin.split('\n');
        for (var line = 0; line < lines.length; line++) {
            console.log(lines[line]);
            GM_download(lines[line], line + '.jpg');
        }
    }
    // reader.readAsBinaryString(file);
    reader.readAsText(file, 'utf-8');//
}

Explain ExtJS 4 event handling

One more trick for controller event listeners.

You can use wildcards to watch for an event from any component:

this.control({
   '*':{ 
       myCustomEvent: this.doSomething
   }
});

How to retrieve Request Payload

If I understand the situation correctly, you are just passing json data through the http body, instead of application/x-www-form-urlencoded data.

You can fetch this data with this snippet:

$request_body = file_get_contents('php://input');

If you are passing json, then you can do:

$data = json_decode($request_body);

$data then contains the json data is php array.

php://input is a so called wrapper.

php://input is a read-only stream that allows you to read raw data from the request body. In the case of POST requests, it is preferable to use php://input instead of $HTTP_RAW_POST_DATA as it does not depend on special php.ini directives. Moreover, for those cases where $HTTP_RAW_POST_DATA is not populated by default, it is a potentially less memory intensive alternative to activating always_populate_raw_post_data. php://input is not available with enctype="multipart/form-data".

What are alternatives to ExtJS?

Nothing compares to in terms of community size and presence on StackOverflow. Despite previous controversy, Ext JS now has a GPLv3 open source license. Its learning curve is long, but it can be quite rewarding once learned. Ext JS lacks a Material Design theme, and the team has repeatedly refused to release the source code on GitHub. For mobile, one must use the separate Sencha Touch library.

Have in mind also that,

large JavaScript libraries, such as YUI, have been receiving less attention from the community. Many developers today look at large JavaScript libraries as walled gardens they don’t want to be locked into.

-- Announcement of YUI development being ceased

That said, below are a number of Ext JS alternatives currently available.

Leading client widget libraries

  1. Blueprint is a React-based UI toolkit developed by big data analytics company Palantir in TypeScript, and "optimized for building complex data-dense interfaces for desktop applications". Actively developed on GitHub as of May 2019, with comprehensive documentation. Components range from simple (chips, toast, icons) to complex (tree, data table, tag input with autocomplete, date range picker. No accordion or resizer.

    Blueprint targets modern browsers (Chrome, Firefox, Safari, IE 11, and Microsoft Edge) and is licensed under a modified Apache license.

    Sandbox / demoGitHubDocs

  2. Webix - an advanced, easy to learn, mobile-friendly, responsive and rich free&open source JavaScript UI components library. Webix spun off from DHTMLX Touch (a project with 8 years of development behind it - see below) and went on to become a standalone UI components framework. The GPL3 edition allows commercial use and lets non-GPL applications using Webix keep their license, e.g. MIT, via a license exemption for FLOSS. Webix has 55 UI widgets, including trees, grids, treegrids and charts. Funding comes from a commercial edition with some advanced widgets (Pivot, Scheduler, Kanban, org chart etc.). Webix has an extensive list of free and commercial widgets, and integrates with most popular frameworks (React, Vue, Meteor, etc) and UI components.

    Webix

    Skins look modern, and include a Material Design theme. The Touch theme also looks quite Material Design-ish. See also the Skin Builder.

    Minimal GitHub presence, but includes the library code, and the documentation (which still needs major improvements). Webix suffers from a having a small team and a lack of marketing. However, they have been responsive to user feedback, both on GitHub and on their forum.

    The library was lean (128Kb gzip+minified for all 55 widgets as of ~2015), faster than ExtJS, dojo and others, and the design is pleasant-looking. The current version of Webix (v6, as of Nov 2018) got heavier (400 - 676kB minified but NOT gzipped).

    The demos on Webix.com look and function great. The developer, XB Software, uses Webix in solutions they build for paying customers, so there's likely a good, funded future ahead of it.

    Webix aims for backwards compatibility down to IE8, and as a result carries some technical debt.

    WikipediaGitHubPlayground/sandboxAdmin dashboard demoDemosWidget samples

  3. react-md - MIT-licensed Material Design UI components library for React. Responsive, accessible. Implements components from simple (buttons, cards) to complex (sortable tables, autocomplete, tags input, calendars). One lead author, ~1900 GitHub stars.

  4. - jQuery-based UI toolkit with 40+ basic open-source widgets, plus commercial professional widgets (grids, trees, charts etc.). Responsive&mobile support. Works with Bootstrap and AngularJS. Modern, with Material Design themes. The documentation is available on GitHub, which has enabled numerous contributions from users (4500+ commits, 500+ PRs as of Jan 2015).

    enter image description here

    Well-supported commercially, claiming millions of developers, and part of a large family of developer tools. Telerik has received many accolades, is a multi-national company (Bulgaria, US), was acquired by Progress Software, and is a thought leader.

    A Kendo UI Professional developer license costs $700 and posting access to most forums is conditioned upon having a license or being in the trial period.

    [Wikipedia] • GitHub/TelerikDemosPlaygroundTools

  5. OpenUI5 - jQuery-based UI framework with 180 widgets, Apache 2.0-licensed and fully-open sourced and funded by German software giant SAP SE.

    OpenUI5

    The community is much larger than that of Webix, SAP is hiring developers to grow OpenUI5, and they presented OpenUI5 at OSCON 2014.

    The desktop themes are rather lackluster, but the Fiori design for web and mobile looks clean and neat.

    WikipediaGitHubMobile-first controls demosDesktop controls demosSO

  6. DHTMLX - JavaScript library for building rich Web and Mobile apps. Looks most like ExtJS - check the demos. Has been developed since 2005 but still looks modern. All components except TreeGrid are available under GPLv2 but advanced features for many components are only available in the commercial PRO edition - see for example the tree. Claims to be used by many Fortune 500 companies.

    DHTMLX

    Minimal presence on GitHub (the main library code is missing) and StackOverflow but active forum. The documentation is not available on GitHub, which makes it difficult to improve by the community.

  7. Polymer, a Web Components polyfill, plus Polymer Paper, Google's implementation of the Material design. Aimed at web and mobile apps. Doesn't have advanced widgets like trees or even grids but the controls it provides are mobile-first and responsive. Used by many big players, e.g. IBM or USA Today.

    Polymer Paper Elements

  8. Ant Design claims it is "a design language for background applications", influenced by "nature" and helping designers "create low-entropy atmosphere for developer team". That's probably a poor translation from Chinese for "UI components for enterprise web applications". It's a React UI library written in TypeScript, with many components, from simple (buttons, cards) to advanced (autocomplete, calendar, tag input, table).

    The project was born in China, is popular with Chinese companies, and parts of the documentation are available only in Chinese. Quite popular on GitHub, yet it makes the mistake of splitting the community into Chinese and English chat rooms. The design looks Material-ish, but fonts are small and the information looks lost in a see of whitespace.

  9. PrimeUI - collection of 45+ rich widgets based on jQuery UI. Apache 2.0 license. Small GitHub community. 35 premium themes available.

  10. qooxdoo - "a universal JavaScript framework with a coherent set of individual components", developed and funded by German hosting provider 1&1 (see the contributors, one of the world's largest hosting companies. GPL/EPL (a business-friendly license).

    Mobile themes look modern but desktop themes look old (gradients).

    Qooxdoo

    WikipediaGitHubWeb/Mobile/Desktop demosWidgets Demo browserWidget browserSOPlaygroundCommunity

  11. jQuery UI - easy to pick up; looks a bit dated; lacks advanced widgets. Of course, you can combine it with independent widgets for particular needs, e.g. trees or other UI components, but the same can be said for any other framework.

  12. + Angular UI. While Angular is backed by Google, it's being radically revamped in the upcoming 2.0 version, and "users will need to get to grips with a new kind of architecture. It's also been confirmed that there will be no migration path from Angular 1.X to 2.0". Moreover, the consensus seems to be that Angular 2 won't really be ready for use until a year or two from now. Angular UI has relatively few widgets (no trees, for example).

  13. DojoToolkit and their powerful Dijit set of widgets. Completely open-sourced and actively developed on GitHub, but development is now (Nov 2018) focused on the new dojo.io framework, which has very few basic widgets. BSD/AFL license. Development started in 2004 and the Dojo Foundation is being sponsored by IBM, Google, and others - see Wikipedia. 7500 questions here on SO.

    Dojo Dijit

    Themes look desktop-oriented and dated - see the theme tester in dijit. The official theme previewer is broken and only shows "Claro". A Bootstrap theme exists, which looks a lot like Bootstrap, but doesn't use Bootstrap classes. In Jan 2015, I started a thread on building a Material Design theme for Dojo, which got quite popular within the first hours. However, there are questions regarding building that theme for the current Dojo 1.10 vs. the next Dojo 2.0. The response to that thread shows an active and wide community, covering many time zones.

    Unfortunately, Dojo has fallen out of popularity and fewer companies appear to use it, despite having (had?) a strong foothold in the enterprise world. In 2009-2012, its learning curve was steep and the documentation needed improvements; while the documentation has substantially improved, it's unclear how easy it is to pick up Dojo nowadays.

    With a Material Design theme, Dojo (2.0?) might be the killer UI components framework.

    WikipediaGitHubThemesDemosDesktop widgetsSO

  14. Enyo - front-end library aimed at mobile and TV apps (e.g. large touch-friendly controls). Developed by LG Electronix and Apache-licensed on GitHub.

  15. The radical Cappuccino - Objective-J (a superset of JavaScript) instead of HTML+CSS+DOM

  16. Mochaui, MooTools UI Library User Interface Library. <300 GitHub stars.

  17. CrossUI - cross-browser JS framework to develop and package the exactly same code and UI into Web Apps, Native Desktop Apps (Windows, OS X, Linux) and Mobile Apps (iOS, Android, Windows Phone, BlackBerry). Open sourced LGPL3. Featured RAD tool (form builder etc.). The UI looks desktop-, not web-oriented. Actively developed, small community. No presence on GitHub.

  18. ZinoUI - simple widgets. The DataTable, for instance, doesn't even support sorting.

  19. Wijmo - good-looking commercial widgets, with old (jQuery UI) widgets open-sourced on GitHub (their development stopped in 2013). Developed by ComponentOne, a division of GrapeCity. See Wijmo Complete vs. Open.

  20. CxJS - commercial JS framework based on React, Babel and webpack offering form elements, form validation, advanced grid control, navigational elements, tooltips, overlays, charts, routing, layout support, themes, culture dependent formatting and more.

CxJS

Widgets - Demo Apps - Examples - GitHub

Full-stack frameworks

  1. SproutCore - developed by Apple for web applications with native performance, handling large data sets on the client. Powers iCloud.com. Not intended for widgets.

  2. Wakanda: aimed at business/enterprise web apps - see What is Wakanda?. Architecture:

  3. Servoy - "a cross platform frontend development and deployment environment for SQL databases". Boasts a "full WYSIWIG (What You See Is What You Get) UI designer for HTML5 with built-in data-binding to back-end services", responsive design, support for HTML6 Web Components, Websockets and mobile platforms. Written in Java and generates JavaScript code using various JavaBeans.

  4. SmartClient/SmartGWT - mobile and cross-browser HTML5 UI components combined with a Java server. Aimed at building powerful business apps - see demos.

  5. Vaadin - full-stack Java/GWT + JavaScript/HTML3 web app framework

  6. Backbase - portal software

  7. Shiny - front-end library on top R, with visualization, layout and control widgets

  8. ZKOSS: Java+jQuery+Bootstrap framework for building enterprise web and mobile apps.

CSS libraries + minimal widgets

These libraries don't implement complex widgets such as tables with sorting/filtering, autocompletes, or trees.

  1. Bootstrap

  2. Foundation for Apps - responsive front-end framework on top of AngularJS; more of a grid/layout/navigation library

  3. UI Kit - similar to Bootstrap, with fewer widgets, but with official off-canvas.

Libraries using HTML Canvas

Using the canvas elements allows for complete control over the UI, and great cross-browser compatibility, but comes at the cost of missing native browser functionality, e.g. page search via Ctrl/Cmd+F.

  1. Zebra - demos

No longer developed as of Dec 2014

  1. Yahoo! User Interface - YUI, launched in 2005, but no longer maintained by the core contributors - see the announcement, which highlights reasons why large UI widget libraries are perceived as walled gardens that developers don't want to be locked into.
  2. echo3, GitHub. Supports writing either server-side Java applications that don't require developer knowledge of HTML, HTTP, or JavaScript, or client-side JavaScript-based applications do not require a server, but can communicate with one via AJAX. Last update: July 2013.
  3. ampleSDK
  4. Simpler widgets livepipe.net
  5. JxLib
  6. rialto
  7. Simple UI kit
  8. Prototype-ui

Other lists

ExtJs Gridpanel store refresh

Try refreshing the view:

Ext.getCmp('yourGridId').getView().refresh();

How to retrieve JSON Data Array from ExtJS Store

A simple way to do this is

var jsonArray = store.data.items

So if your JSON store is

[{"text": "ABC"}, {"text": "DEF"},{"text": "GHI"},{"text": "JKL"}]

Then you can retreive "DEF" as

jsonArray[1].data.text

In the following code, I noticed that it converts each and every character into an array item.

var jsonData = Ext.encode(Ext.pluck(store.data.items, 'data'));

Javascript how to parse JSON array

Just as a heads up...

var data = JSON.parse(responseBody);

has been deprecated.

Postman Learning Center now suggests

var jsonData = pm.response.json();

Select only rows if its value in a particular column is less than the value in the other column

df[df$aged <= df$laclen, ] 

Should do the trick. The square brackets allow you to index based on a logical expression.

background:none vs background:transparent what is the difference?

To complement the other answers: if you want to reset all background properties to their initial value (which includes background-color: transparent and background-image: none) without explicitly specifying any value such as transparent or none, you can do so by writing:

background: initial;

Soft hyphen in HTML (<wbr> vs. &shy;)

There is an ongoing effort to standardize hyphenation in CSS3.

Some modern browsers, notably Safari and Firefox, already support this. Here is a good and up to date reference on browser support.

Once the CSS hyphenation gets implemented universally, that would be the best solution. In the meantime, I can recommend Hyphenator - a JS script that figures out how to hyphenate your text in the way most appropriate for a particular browser.

Hyphenator:

  • relies on Franklin M. Liangs hyphenation algorithm, commonly known from LaTeX and OpenOffice.
  • uses CSS3 hyphenation where it is available,
  • automatically inserts &shy; on most other browsers,
  • supports multiple languages,
  • is highly configurable,
  • gracefully falls back in case javascript is not enabled.

I've used it and it works great!

Calling a Sub and returning a value

Sub don't return values and functions don't have side effects.

Sometimes you want both side effect and return value.

This is easy to be done once you know that VBA passes arguments by default by reference so you can write your code in this way:

Sub getValue(retValue as Long)
    ...
    retValue = 42 
End SUb 

Sub Main()
    Dim retValue As Long
    getValue retValue 
    ... 
End SUb

jQuery send string as POST parameters

Not sure whether this is still actual.. just for future readers. If what you really want is to pass your parameters as part of the URL, you should probably use jQuery.param().

Reset MySQL root password using ALTER USER statement after install on Mac

If you use MySQL 5.7.6 and later:

ALTER USER 'root'@'localhost' IDENTIFIED BY 'MyNewPass';

If you use MySQL 5.7.5 and earlier:

SET PASSWORD FOR 'root'@'localhost' = PASSWORD('MyNewPass');

MySQL Documentation

What is the Java ?: operator called and what does it do?

Ternary, conditional; tomato, tomatoh. What it's really valuable for is variable initialization. If (like me) you're fond of initializing variables where they are defined, the conditional ternary operator (for it is both) permits you to do that in cases where there is conditionality about its value. Particularly notable in final fields, but useful elsewhere, too.

e.g.:

public class Foo {
    final double    value;

    public Foo(boolean positive, double value) {
        this.value = positive ? value : -value;
    }
}

Without that operator - by whatever name - you would have to make the field non-final or write a function simply to initialize it. Actually, that's not right - it can still be initialized using if/else, at least in Java. But I find this cleaner.

How can I set the form action through JavaScript?

Do as Rabbott says, or if you refuse jQuery:

<script type="text/javascript">
function get_action() { // inside script tags
  return form_action;
}
</script>

<form action="" onsubmit="this.action=get_action();">
...
</form>

Difference between Spring MVC and Struts MVC

If you wanna compare Spring MVC with struts consider below benefit of Spring MVC over Struts.

  1. Spring provides a very clean division between controllers, JavaBean models, and views.
  2. Spring's MVC is very flexible. Unlike Struts, which forces your Action and Form objects into concrete inheritance (thus taking away your single shot at concrete inheritance in Java), Spring MVC is entirely based on interfaces. Furthermore, just about every part of the Spring MVC framework is configurable via plugging in your own interface. Of course we also provide convenience classes as an implementation option.
  3. Spring, like WebWork, provides interceptors as well as controllers, making it easy to factor out behavior common to the handling of many requests.
  4. Spring MVC is truly view-agnostic. You don't get pushed to use JSP if you don't want to; you can use Velocity, XLST or other view technologies. If you want to use a custom view mechanism - for example, your own templating language - you can easily implement the Spring View interface to integrate it.
  5. Spring Controllers are configured via IoC like any other objects. This makes them easy to test, and beautifully integrated with other objects managed by Spring.
  6. Spring MVC web tiers are typically easier to test than Struts web tiers, due to the avoidance of forced concrete inheritance and explicit dependence of controllers on the dispatcher servlet.
  7. The web tier becomes a thin layer on top of a business object layer. This encourages good practice. Struts and other dedicated web frameworks leave you on your own in implementing your business objects; Spring provides an integrated framework for all tiers of your application

How to use the ConfigurationManager.AppSettings

ConfigurationManager.AppSettings is actually a property, so you need to use square brackets.

Overall, here's what you need to do:

SqlConnection con= new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]);

The problem is that you tried to set con to a string, which is not correct. You have to either pass it to the constructor or set con.ConnectionString property.

Simple example of threading in C++

#include <thread>
#include <iostream>
#include <vector>
using namespace std;

void doSomething(int id) {
    cout << id << "\n";
}

/**
 * Spawns n threads
 */
void spawnThreads(int n)
{
    std::vector<thread> threads(n);
    // spawn n threads:
    for (int i = 0; i < n; i++) {
        threads[i] = thread(doSomething, i + 1);
    }

    for (auto& th : threads) {
        th.join();
    }
}

int main()
{
    spawnThreads(10);
}

How to retrieve data from a SQL Server database in C#?

To retrieve data from database:

private SqlConnection Conn;
 private void CreateConnection()
 {
    string ConnStr =
    ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
    Conn = new SqlConnection(ConnStr);
 }
 public DataTable getData()
 {
 CreateConnection();
    string SqlString = "SELECT * FROM TableName WHERE SomeID = @SomeID;";
    SqlDataAdapter sda = new SqlDataAdapter(SqlString, Conn);
    DataTable dt = new DataTable();
    try
    {
        Conn.Open();
        sda.Fill(dt);
    }
    catch (SqlException se)
    {
        DBErLog.DbServLog(se, se.ToString());
    }
    finally
    {
        Conn.Close();
    }
    return dt;
}

How to center a label text in WPF?

Sample:

Label label = new Label();
label.HorizontalContentAlignment = HorizontalAlignment.Center;

Python script to copy text to clipboard

This is the only way that worked for me using Python 3.5.2 plus it's the easiest to implement w/ using the standard PyData suite

Shout out to https://stackoverflow.com/users/4502363/gadi-oron for the answer (I copied it completely) from How do I copy a string to the clipboard on Windows using Python?

import pandas as pd
df=pd.DataFrame(['Text to copy'])
df.to_clipboard(index=False,header=False)

I wrote a little wrapper for it that I put in my ipython profile <3

How can I express that two values are not equal to eachother?

if (!secondaryPassword.equals(initialPassword)) 

Linux command to translate DomainName to IP

You can use:

nslookup www.example.com

In C#, why is String a reference type that behaves like a value type?

Strings aren't value types since they can be huge, and need to be stored on the heap. Value types are (in all implementations of the CLR as of yet) stored on the stack. Stack allocating strings would break all sorts of things: the stack is only 1MB for 32-bit and 4MB for 64-bit, you'd have to box each string, incurring a copy penalty, you couldn't intern strings, and memory usage would balloon, etc...

(Edit: Added clarification about value type storage being an implementation detail, which leads to this situation where we have a type with value sematics not inheriting from System.ValueType. Thanks Ben.)

Nodemailer with Gmail and NodeJS

I had the same problem. Allowing "less secure apps" in my Google security settings made it work!

How to run .APK file on emulator

Step-by-Step way to do this:

  1. Install Android SDK
  2. Start the emulator by going to $SDK_root/emulator.exe
  3. Go to command prompt and go to the directory $SDK_root/platform-tools (or else add the path to windows environment)
  4. Type in the command adb install
  5. Bingo. Your app should be up and running on the emulator

When should use Readonly and Get only properties

A property that has only a getter is said to be readonly. Cause no setter is provided, to change the value of the property (from outside).

C# has has a keyword readonly, that can be used on fields (not properties). A field that is marked as "readonly", can only be set once during the construction of an object (in the constructor).

private string _name = "Foo"; // field for property Name;
private bool _enabled = false; // field for property Enabled;

public string Name{ // This is a readonly property.
  get {
    return _name;  
  }
}

public bool Enabled{ // This is a read- and writeable property.
  get{
    return _enabled;
  }
  set{
    _enabled = value;
  }
} 

Set selected option of select box

Addition to @icksde and @Korah (thx both!)

When building the options with AJAX the document.ready may be triggered before the list is built, so

This doesn't work

$(document).ready(function() {
    $("#gate").val('Gateway 2');
});

This does

A timeout does work but as @icksde says it's fragile (I did actually need 20ms in stead of 10ms). It's better to fit it inside the AJAX function like this:

$("#someObject").change(function() {
    $.get("website/page.php", {parameters}, function(data) {
        $("#gate").append("<option value='Gateway 2'">" + "Gateway 2" + "</option>");
        $("#gate").val('Gateway 2');
    }, "json");
});

How to view the roles and permissions granted to any database user in Azure SQL server instance?

Per the MSDN documentation for sys.database_permissions, this query lists all permissions explicitly granted or denied to principals in the database you're connected to:

SELECT DISTINCT pr.principal_id, pr.name, pr.type_desc, 
    pr.authentication_type_desc, pe.state_desc, pe.permission_name
FROM sys.database_principals AS pr
JOIN sys.database_permissions AS pe
    ON pe.grantee_principal_id = pr.principal_id;

Per Managing Databases and Logins in Azure SQL Database, the loginmanager and dbmanager roles are the two server-level security roles available in Azure SQL Database. The loginmanager role has permission to create logins, and the dbmanager role has permission to create databases. You can view which users belong to these roles by using the query you have above against the master database. You can also determine the role memberships of users on each of your user databases by using the same query (minus the filter predicate) while connected to them.

VBA Check if variable is empty

I had a similar issue with an integer that could be legitimately assigned 0 in Access VBA. None of the above solutions worked for me.

At first I just used a boolean var and IF statement:

Dim i as integer, bol as boolean
   If bol = false then
      i = ValueIWantToAssign
      bol = True
   End If

In my case, my integer variable assignment was within a for loop and another IF statement, so I ended up using "Exit For" instead as it was more concise.

Like so:

Dim i as integer
ForLoopStart
   If ConditionIsMet Then
      i = ValueIWantToAssign
   Exit For
   End If
ForLoopEnd

Error in Eclipse: "The project cannot be built until build path errors are resolved"

  1. Right click your Project > Properties > Java Build Path > Libraries

  2. Remove the file with red "X" (something like JRE...)

  3. Add Library

That's how I solved my problem.

Type of expression is ambiguous without more context Swift

I got this error when I put a space before a comma in the parameters when calling a function.

eg, I used:

myfunction(parameter1: parameter1 , parameter2: parameter2)

Whereas it should have been:

myfunction(parameter1: parameter1, parameter2: parameter2)

Deleting the space got rid of the error message

Entity Framework Provider type could not be loaded?

Adding Entityframework.dll and Entityframework.sqlserver.dll to the reference project solved the issue.

Save file Javascript with file name

Replace your "Save" button with an anchor link and set the new download attribute dynamically. Works in Chrome and Firefox:

var d = "ha";
$(this).attr("href", "data:image/png;base64,abcdefghijklmnop").attr("download", "file-" + d + ".png");

Here's a working example with the name set as the current date: http://jsfiddle.net/Qjvb3/

Here a compatibility table for downloadattribute: http://caniuse.com/download

Date format in dd/MM/yyyy hh:mm:ss

You could combine 2 formats:

3   dd/mm/yy   (British/French)
8   hh:mm:ss

according to CONVERT() function, and using + operator:

SELECT CONVERT(varchar(10),GETDATE(),3) + ' ' + CONVERT(varchar(10),GETDATE(),8)

Android Camera : data intent returns null

Probably because you had something like this?

Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);                        
Uri fileUri =  CommonUtilities.getTBCameraOutputMediaFileUri();                  
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);                        
startActivityForResult(takePictureIntent, 2);

However you must not put the extra output into the intent, because then the data goes into the URI instead of the data variable. For that reason, you have to take the two lines in the middle out, so that you have

Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePictureIntent, 2);

That´s what caused the problem for me, hope that helped.

angularjs ng-style: background-image isn't working

This worked for me, curly braces are not required.

ng-style="{'background-image':'url(../../../app/img/notification/'+notification.icon+'.png)'}"

notification.icon here is scope variable.

SQL Server: Importing database from .mdf?

Open SQL Management Studio Express and log in to the server to which you want to attach the database. In the 'Object Explorer' window, right-click on the 'Databases' folder and select 'Attach...' The 'Attach Databases' window will open; inside that window click 'Add...' and then navigate to your .MDF file and click 'OK'. Click 'OK' once more to finish attaching the database and you are done. The database should be available for use. best regards :)

jQuery: How to get to a particular child of a parent?

Calling .parents(".box .something1") will return all parent elements that match the selector .box .something. In other words, it will return parent elements that are .something1 and are inside of .box.

You need to get the children of the closest parent, like this:

$(this).closest('.box').children('.something1')

This code calls .closest to get the innermost parent matching a selector, then calls .children on that parent element to find the uncle you're looking for.

Css Move element from left to right animated

You should try doing it with css3 animation. Check the code bellow:

<!DOCTYPE html>
<html>
<head>
<style> 
div {
    width: 100px;
    height: 100px;
    background: red;
    position: relative;
    -webkit-animation: myfirst 5s infinite; /* Chrome, Safari, Opera */
    -webkit-animation-direction: alternate; /* Chrome, Safari, Opera */
    animation: myfirst 5s infinite;
    animation-direction: alternate;
}

/* Chrome, Safari, Opera */
@-webkit-keyframes myfirst {
    0%   {background: red; left: 0px; top: 0px;}
    25%  {background: yellow; left: 200px; top: 0px;}
    50%  {background: blue; left: 200px; top: 200px;}
    75%  {background: green; left: 0px; top: 200px;}
    100% {background: red; left: 0px; top: 0px;}
}

@keyframes myfirst {
    0%   {background: red; left: 0px; top: 0px;}
    25%  {background: yellow; left: 200px; top: 0px;}
    50%  {background: blue; left: 200px; top: 200px;}
    75%  {background: green; left: 0px; top: 200px;}
    100% {background: red; left: 0px; top: 0px;}
}
</style>
</head>
<body>

<p><strong>Note:</strong> The animation-direction property is not supported in Internet Explorer 9 and earlier versions.</p>
<div></div>

</body>
</html>

Where 'div' is your animated object.

I hope you find this useful.

Thanks.

Finding the id of a parent div using Jquery

JQUery has a .parents() method for moving up the DOM tree you can start there.

If you're interested in doing this a more semantic way I don't think using the REL attribute on a button is the best way to semantically define "this is the answer" in your code. I'd recommend something along these lines:

<p id="question1">
    <label for="input1">Volume =</label> 
    <input type="text" name="userInput1" id="userInput1" />
    <button type="button">Check answer</button>
    <input type="hidden" id="answer1" name="answer1" value="3.93e-6" />
</p>

and

$("button").click(function () {
    var correctAnswer = $(this).parent().siblings("input[type=hidden]").val();
    var userAnswer = $(this).parent().siblings("input[type=text]").val();
    validate(userAnswer, correctAnswer);
    $("#messages").html(feedback);
});

Not quite sure how your validate and feedback are working, but you get the idea.

Random numbers with Math.random() in Java

if min=10 and max=100:

(int)(Math.random() * max) + min        

gives a result between 10 and 110, while

(int)(Math.random() * (max - min) + min)

gives a result between 10 and 100, so they are very different formulas. What's important here is clarity, so whatever you do, make sure the code makes it clear what is being generated.

(PS. the first makes more sense if you change the variable 'max' to be called 'range')

How to get the path of running java program

Use

System.getProperty("java.class.path")

see http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html

You can also split it into it's elements easily

String classpath = System.getProperty("java.class.path");
String[] classpathEntries = classpath.split(File.pathSeparator);

Unlink of file Failed. Should I try again?

You might see that error less often with Git 2.29 (Q4 2020): the "unlink" emulation on MinGW has been optimized.

See commit 680e0b4 (17 Aug 2020) by Jeff Hostetler (Jeff-Hostetler).
(Merged by Junio C Hamano -- gitster -- in commit 5a04826, 19 Aug 2020)

mingw: improve performance of mingw_unlink()

Signed-off-by: Jeff Hostetler
Signed-off-by: Johannes Schindelin

Update mingw_unlink() to first try to delete the file with existing permissions before trying to force it.

Windows throws an error when trying to delete a read-only file.
The mingw_unlink() compatibility wrapper always tries to _wchmod(666) the file before calling _wunlink() to avoid that error.
However, since most files in the worktree are already writable, this is usually wasted effort.

Update mingw_unlink() to just call DeleteFileW() directly and if that succeeds return.
If that fails, fall back into the existing code path to update the permissions and use _wunlink() to get the existing error code mapping.

Newline in string attribute

May be you can use the attribute xml:space="preserve" for preserving whitespace in the source XAML

<TextBlock xml:space="preserve">
Stuff on line 1
Stuff on line 2
</TextBlock>

How can I get the current contents of an element in webdriver

My answer is based on this answer: How can I get the current contents of an element in webdriver just more like copy-paste.

from selenium import webdriver

driver = webdriver.Firefox()
driver.get('http://www.w3c.org')
element = driver.find_element_by_name('q')
element.send_keys('hi mom')

element_text = element.text
element_attribute_value = element.get_attribute('value')

print (element)
print ('element.text: {0}'.format(element_text))
print ('element.get_attribute(\'value\'): {0}'.format(element_attribute_value))


element = driver.find_element_by_css_selector('.description.expand_description > p')
element_text = element.text
element_attribute_value = element.get_attribute('value')

print (element)
print ('element.text: {0}'.format(element_text))
print ('element.get_attribute(\'value\'): {0}'.format(element_attribute_value))
driver.quit()

How do I import a CSV file in R?

You would use the read.csv function; for example:

dat = read.csv("spam.csv", header = TRUE)

You can also reference this tutorial for more details.

Note: make sure the .csv file to read is in your working directory (using getwd()) or specify the right path to file. If you want, you can set the current directory using setwd.

The type java.io.ObjectInputStream cannot be resolved. It is indirectly referenced from required .class files

I am using Google appengine java sdk and was facing similar issue. I had to add

<runtime>java8</runtime>

in appengine-web.xml file to make it work.

How to debug in Django, the good way?

The easiest way to debug python - especially for programmers that are used to Visual Studio - is using PTVS (Python Tools for Visual Studio). The steps are simple:

  1. Download and install it from http://pytools.codeplex.com/
  2. Set breakpoints and press F5.
  3. Your breakpoint is hit, you can view/change the variables as easy as debugging C#/C++ programs.
  4. That's all :)

If you want to debug Django using PTVS, you need to do the following:

  1. In Project settings - General tab, set "Startup File" to "manage.py", the entry point of the Django program.
  2. In Project settings - Debug tab, set "Script Arguments" to "runserver --noreload". The key point is the "--noreload" here. If you don't set it, your breakpoints won't be hit.
  3. Enjoy it.

jQuery - Getting the text value of a table cell in the same row as a clicked element

it should work fine:

var Something = $(this).children("td:nth-child(n)").text();

nginx error "conflicting server name" ignored

I assume that you're running a Linux, and you're using gEdit to edit your files. In the /etc/nginx/sites-enabled, it may have left a temp file e.g. default~ (watch the ~).

Depending on your editor, the file could be named .save or something like it. Just run $ ls -lah to see which files are unintended to be there and remove them (Thanks @Tisch for this).

Delete this file, and it will solve your problem.

JSON response parsing in Javascript to get key/value pair

There are two ways to access properties of objects:

var obj = {a: 'foo', b: 'bar'};

obj.a //foo
obj['b'] //bar

Or, if you need to dynamically do it:

var key = 'b';
obj[key] //bar

If you don't already have it as an object, you'll need to convert it.

For a more complex example, let's assume you have an array of objects that represent users:

var users = [{name: 'Corbin', age: 20, favoriteFoods: ['ice cream', 'pizza']},
             {name: 'John', age: 25, favoriteFoods: ['ice cream', 'skittle']}];

To access the age property of the second user, you would use users[1].age. To access the second "favoriteFood" of the first user, you'd use users[0].favoriteFoods[2].

Another example: obj[2].key[3]["some key"]

That would access the 3rd element of an array named 2. Then, it would access 'key' in that array, go to the third element of that, and then access the property name some key.


As Amadan noted, it might be worth also discussing how to loop over different structures.

To loop over an array, you can use a simple for loop:

var arr = ['a', 'b', 'c'],
    i;
for (i = 0; i < arr.length; ++i) {
    console.log(arr[i]);
}

To loop over an object is a bit more complicated. In the case that you're absolutely positive that the object is a plain object, you can use a plain for (x in obj) { } loop, but it's a lot safer to add in a hasOwnProperty check. This is necessary in situations where you cannot verify that the object does not have inherited properties. (It also future proofs the code a bit.)

var user = {name: 'Corbin', age: 20, location: 'USA'},
    key;

for (key in user) {
    if (user.hasOwnProperty(key)) {
        console.log(key + " = " + user[key]);
    }
}    

(Note that I've assumed whatever JS implementation you're using has console.log. If not, you could use alert or some kind of DOM manipulation instead.)

Replace None with NaN in pandas dataframe

DataFrame['Col_name'].replace("None", np.nan, inplace=True)

How to SSH to a VirtualBox guest externally through a host?

The best way to login to a guest Linux VirtualBox VM is port forwarding. By default, you should have one interface already which is using NAT. Then go to the Network settings and click the Port Forwarding button. Add a new Rule. As the rule name, insert "ssh". As "Host port", insert 3022. As "Guest port", insert 22. Everything else of the rule can be left blank.

or from the command line

VBoxManage modifyvm myserver --natpf1 "ssh,tcp,,3022,,22"

where 'myserver' is the name of the created VM. Check the added rules:

VBoxManage showvminfo myserver | grep 'Rule'

That's all! Please be sure you don't forget to install an SSH server in the VM:

sudo apt-get install openssh-server

To SSH into the guest VM, write:

ssh -p 3022 [email protected]

Where user is your username within the VM.

Percentage width in a RelativeLayout

This does not quite answer the original question, which was for a 70/30 split, but in the special case of a 50/50 split between the components there is a way: place an invisible strut at the center and use it to position the two components of interest.

<RelativeLayout 
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <View android:id="@+id/strut"
        android:layout_width="0dp"
        android:layout_height="0dp" 
        android:layout_centerHorizontal="true"/>
    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_alignRight="@id/strut"
        android:layout_alignParentLeft="true"
        android:text="Left"/> 
    <Button 
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@id/strut"
        android:layout_alignParentRight="true"
        android:text="Right"/>
</RelativeLayout>

As this is a pretty common case, this solution is more than a curiosity. It is a bit of a hack but an efficient one because the empty, zero-sized strut should cost very little.

In general, though, it's best not to expect too much from the stock Android layouts...

How to add /usr/local/bin in $PATH on Mac

In MAC OS Catalina, this are the steps that worked for me, all the above solutions did help but didn't solve my problem.

  1. check node --version, still the old one in use.
  2. cd ~/
  3. atom .bash_profile
  4. Remove the $PATH pointing to old node version, in my case it was /usr/local/bin/node/@node8
  5. Add & save this to $PATH instead "export PATH=$PATH:/usr/local/git/bin:/usr/local/bin"
  6. Close all applications using node (terminal, simulator, browser expo etc)
  7. restart terminal and check node --version

Android M Permissions: onRequestPermissionsResult() not being called

You can try this:

requestPermissions(permissions, PERMISSIONS_CODE);

If you are calling this code from a fragment it has it's own requestPermissions method. I believe the problem is that you are calling static method.

Pro Tip if you want the onRequestPermissionsResult() in a fragment: FragmentCompat.requestPermissions(Fragment fragment, String[] permissions, int requestCode)

What is the color code for transparency in CSS?

In the CSS write:

.exampleclass {
    background:#000000;
    opacity: 10; /* you can always adjust this */
}

Why does the 260 character path length limit exist in Windows?

You can mount a folder as a drive. From the command line, if you have a path C:\path\to\long\folder you can map it to drive letter X: using:

subst x: \path\to\long\folder

Why XML-Serializable class need a parameterless constructor

During an object's de-serialization, the class responsible for de-serializing an object creates an instance of the serialized class and then proceeds to populate the serialized fields and properties only after acquiring an instance to populate.

You can make your constructor private or internal if you want, just so long as it's parameterless.

Is there a performance difference between CTE , Sub-Query, Temporary Table or Table Variable?

There is no rule. I find CTEs more readable, and use them unless they exhibit some performance problem, in which case I investigate the actual problem rather than guess that the CTE is the problem and try to re-write it using a different approach. There is usually more to the issue than the way I chose to declaratively state my intentions with the query.

There are certainly cases when you can unravel CTEs or remove subqueries and replace them with a #temp table and reduce duration. This can be due to various things, such as stale stats, the inability to even get accurate stats (e.g. joining to a table-valued function), parallelism, or even the inability to generate an optimal plan because of the complexity of the query (in which case breaking it up may give the optimizer a fighting chance). But there are also cases where the I/O involved with creating a #temp table can outweigh the other performance aspects that may make a particular plan shape using a CTE less attractive.

Quite honestly, there are way too many variables to provide a "correct" answer to your question. There is no predictable way to know when a query may tip in favor of one approach or another - just know that, in theory, the same semantics for a CTE or a single subquery should execute the exact same. I think your question would be more valuable if you present some cases where this is not true - it may be that you have discovered a limitation in the optimizer (or discovered a known one), or it may be that your queries are not semantically equivalent or that one contains an element that thwarts optimization.

So I would suggest writing the query in a way that seems most natural to you, and only deviate when you discover an actual performance problem the optimizer is having. Personally I rank them CTE, then subquery, with #temp table being a last resort.

How to Clear Console in Java?

You can easily implement clrscr() using simple for loop printing "\b".

differences in application/json and application/x-www-form-urlencoded

webRequest.ContentType = "application/x-www-form-urlencoded";

  1. Where does application/x-www-form-urlencoded's name come from?

    If you send HTTP GET request, you can use query parameters as follows:

    http://example.com/path/to/page?name=ferret&color=purple

    The content of the fields is encoded as a query string. The application/x-www-form- urlencoded's name come from the previous url query parameter but the query parameters is in where the body of request instead of url.

    The whole form data is sent as a long query string.The query string contains name- value pairs separated by & character

    e.g. field1=value1&field2=value2

  2. It can be simple request called simple - don't trigger a preflight check

    Simple request must have some properties. You can look here for more info. One of them is that there are only three values allowed for Content-Type header for simple requests

    • application/x-www-form-urlencoded
    • multipart/form-data
    • text/plain

3.For mostly flat param trees, application/x-www-form-urlencoded is tried and tested.

request.ContentType = "application/json; charset=utf-8";

  1. The data will be json format.

axios and superagent, two of the more popular npm HTTP libraries, work with JSON bodies by default.

{
  "id": 1,
  "name": "Foo",
  "price": 123,
  "tags": [
    "Bar",
    "Eek"
  ],
  "stock": {
    "warehouse": 300,
    "retail": 20
  }
}
  1. "application/json" Content-Type is one of the Preflighted requests.

Now, if the request isn't simple request, the browser automatically sends a HTTP request before the original one by OPTIONS method to check whether it is safe to send the original request. If itis ok, Then send actual request. You can look here for more info.

  1. application/json is beginner-friendly. URL encoded arrays can be a nightmare!

ld.exe: cannot open output file ... : Permission denied

Got the same issue. Read this. Disabled the antivirus software (mcaffee). Et voila

Confirmed by the antivirus log:

Blocked by Access Protection rule d:\mingw64\x86_64-w64-mingw32\bin\ld.exe d:\workspace\cpp\bar\foo.exe User-defined Rules:ctx3 Action blocked : Create

Why does git perform fast-forward merges by default?

Let me expand a bit on a VonC's very comprehensive answer:


First, if I remember it correctly, the fact that Git by default doesn't create merge commits in the fast-forward case has come from considering single-branch "equal repositories", where mutual pull is used to sync those two repositories (a workflow you can find as first example in most user's documentation, including "The Git User's Manual" and "Version Control by Example"). In this case you don't use pull to merge fully realized branch, you use it to keep up with other work. You don't want to have ephemeral and unimportant fact when you happen to do a sync saved and stored in repository, saved for the future.

Note that usefulness of feature branches and of having multiple branches in single repository came only later, with more widespread usage of VCS with good merging support, and with trying various merge-based workflows. That is why for example Mercurial originally supported only one branch per repository (plus anonymous tips for tracking remote branches), as seen in older revisions of "Mercurial: The Definitive Guide".


Second, when following best practices of using feature branches, namely that feature branches should all start from stable version (usually from last release), to be able to cherry-pick and select which features to include by selecting which feature branches to merge, you are usually not in fast-forward situation... which makes this issue moot. You need to worry about creating a true merge and not fast-forward when merging a very first branch (assuming that you don't put single-commit changes directly on 'master'); all other later merges are of course in non fast-forward situation.

HTH

Does Hive have a String split function?

Another interesting usecase for split in Hive is when, for example, a column ipname in the table has a value "abc11.def.ghft.com" and you want to pull "abc11" out:

SELECT split(ipname,'[\.]')[0] FROM tablename;

How can I nullify css property?

I had an issue that even when I did overwrite "height" to "unset" or "initial", it behaved differently from when I removed the previous setting.

It turned out I needed to remove the min-height property too!

height: unset;
min-height: none

Edit: I tested on IE 7 and it doesn't recognize "unset", so "auto" works better".

Loop over html table and get checked checkboxes (JQuery)

The following code snippet enables/disables a button depending on whether at least one checkbox on the page has been checked.
$('input[type=checkbox]').change(function () {
    $('#test > tbody  tr').each(function () {
        if ($('input[type=checkbox]').is(':checked')) {
            $('#btnexcellSelect').removeAttr('disabled');
        } else {
            $('#btnexcellSelect').attr('disabled', 'disabled');
        }
        if ($(this).is(':checked')){
            console.log( $(this).attr('id'));
         }else{
             console.log($(this).attr('id'));
         }
     });
});

Here is demo in JSFiddle.

How to programmatically set the Image source

try this

PictureBox picture = new PictureBox
        {
            Name = "pictureBox",
            Size = new Size(100, 50),
            Location = new Point(14, 17),
            Image = Image.FromFile(@"c:\Images\test.jpg"),
            SizeMode = PictureBoxSizeMode.CenterImage
        };
p.Controls.Add(picture);

How to set the From email address for mailx command?

On debian where bsd-mailx is installed by default, the -r option does not work. However you can use mailx -s subject [email protected] -- -f [email protected] instead. According to man page, you can specify sendmail options after --.

SQLite - UPSERT *not* INSERT or REPLACE

SELECT COUNT(*) FROM table1 WHERE id = 1;

if COUNT(*) = 0

INSERT INTO table1(col1, col2, cole) VALUES(var1,var2,var3);

else if COUNT(*) > 0

UPDATE table1 SET col1 = var4, col2 = var5, col3 = var6 WHERE id = 1;

How can I get a list of all values in select box?

As per the DOM structure you can use below code:

var x = document.getElementById('mySelect');
     var txt = "";
     var val = "";
     for (var i = 0; i < x.length; i++) {
         txt +=x[i].text + ",";
         val +=x[i].value + ",";
      }

Update Android SDK Tool to 22.0.4(Latest Version) from 22.0.1

I viewed the Eclipse ADT documentation and found out the way to get around this issue. I was able to Update My SDK Tool to 22.0.4 (Latest Version).

Solution is: First Update ADT to 22.0.4(Latest version) and then Update SDK Tool to 22.0.4(Latest Version)

The above link says,

ADT 22.0.4 is designed for use with SDK Tools r22.0.4. If you haven't already installed SDK Tools r22.0.4 into your SDK, use the Android SDK Manager to do so

What I had to do was update my ADT to 22.0.4 (Latest Version) and then I was able to update SDK tool to 22.0.4. I thought only SDK Tool has been updated not ADT, so I was updating the SDK Tool with Older ADT Version (22.0.1).

How to Update your ADT to Latest Version

  1. In Eclipse go to Help
  2. Install New Software ---> Add
  3. inside Add Repository write the Name: ADT (or whatever you want)
  4. and Location: https://dl-ssl.google.com/android/eclipse/
  5. after loading you should get Developer Tools and NDK Plugins
  6. check both if you want to use the Native Developer Kit (NDK) in the future or check Developer Tool only
  7. click Next
  8. Finish

How to resolve Error listenerStart when deploying web-app in Tomcat 5.5?

/var/lib/tomcat5.5/webapps/spaghetti/WEB-INF/lib/jsp-api-6.0.16.jar
/var/lib/tomcat5.5/webapps/spaghetti/WEB-INF/lib/servlet-api-6.0.16.jar

You should not have any server-specific libraries in the /WEB-INF/lib. Leave them in the appserver's own library. It would only lead to collisions in the classpath. Get rid of all appserver-specific libraries in /WEB-INF/lib (and also in JRE/lib and JRE/lib/ext if you have placed any of them there).

A common cause that the appserver-specific libraries are included in the webapp's library is that starters think that it is the right way to fix compilation errors of among others the javax.servlet classes not being resolveable. Putting them in webapp's library is the wrong solution. You should reference them in the classpath during compilation, i.e. javac -cp /path/to/server/lib/servlet.jar and so on, or if you're using an IDE, you should integrate the server in the IDE and associate the web project with the server. The IDE will then automatically take server-specific libraries in the classpath (buildpath) of the webapp project.

How is Perl's @INC constructed? (aka What are all the ways of affecting where Perl modules are searched for?)

We will look at how the contents of this array are constructed and can be manipulated to affect where the Perl interpreter will find the module files.

  1. Default @INC

    Perl interpreter is compiled with a specific @INC default value. To find out this value, run env -i perl -V command (env -i ignores the PERL5LIB environmental variable - see #2) and in the output you will see something like this:

    $ env -i perl -V
    ...
    @INC:
     /usr/lib/perl5/site_perl/5.18.0/x86_64-linux-thread-multi-ld
     /usr/lib/perl5/site_perl/5.18.0
     /usr/lib/perl5/5.18.0/x86_64-linux-thread-multi-ld
     /usr/lib/perl5/5.18.0
     .
    

Note . at the end; this is the current directory (which is not necessarily the same as the script's directory). It is missing in Perl 5.26+, and when Perl runs with -T (taint checks enabled).

To change the default path when configuring Perl binary compilation, set the configuration option otherlibdirs:

Configure -Dotherlibdirs=/usr/lib/perl5/site_perl/5.16.3

  1. Environmental variable PERL5LIB (or PERLLIB)

    Perl pre-pends @INC with a list of directories (colon-separated) contained in PERL5LIB (if it is not defined, PERLLIB is used) environment variable of your shell. To see the contents of @INC after PERL5LIB and PERLLIB environment variables have taken effect, run perl -V.

    $ perl -V
    ...
    %ENV:
      PERL5LIB="/home/myuser/test"
    @INC:
     /home/myuser/test
     /usr/lib/perl5/site_perl/5.18.0/x86_64-linux-thread-multi-ld
     /usr/lib/perl5/site_perl/5.18.0
     /usr/lib/perl5/5.18.0/x86_64-linux-thread-multi-ld
     /usr/lib/perl5/5.18.0
     .
    
  2. -I command-line option

    Perl pre-pends @INC with a list of directories (colon-separated) passed as value of the -I command-line option. This can be done in three ways, as usual with Perl options:

    • Pass it on command line:

      perl -I /my/moduledir your_script.pl
      
    • Pass it via the first line (shebang) of your Perl script:

      #!/usr/local/bin/perl -w -I /my/moduledir
      
    • Pass it as part of PERL5OPT (or PERLOPT) environment variable (see chapter 19.02 in Programming Perl)

  3. Pass it via the lib pragma

    Perl pre-pends @INC with a list of directories passed in to it via use lib.

    In a program:

    use lib ("/dir1", "/dir2");
    

    On the command line:

    perl -Mlib=/dir1,/dir2
    

    You can also remove the directories from @INC via no lib.

  4. You can directly manipulate @INC as a regular Perl array.

    Note: Since @INC is used during the compilation phase, this must be done inside of a BEGIN {} block, which precedes the use MyModule statement.

    • Add directories to the beginning via unshift @INC, $dir.

    • Add directories to the end via push @INC, $dir.

    • Do anything else you can do with a Perl array.

Note: The directories are unshifted onto @INC in the order listed in this answer, e.g. default @INC is last in the list, preceded by PERL5LIB, preceded by -I, preceded by use lib and direct @INC manipulation, the latter two mixed in whichever order they are in Perl code.

References:

There does not seem to be a comprehensive @INC FAQ-type post on Stack Overflow, so this question is intended as one.

When to use each approach?

  • If the modules in a directory need to be used by many/all scripts on your site, especially run by multiple users, that directory should be included in the default @INC compiled into the Perl binary.

  • If the modules in the directory will be used exclusively by a specific user for all the scripts that user runs (or if recompiling Perl is not an option to change default @INC in previous use case), set the users' PERL5LIB, usually during user login.

    Note: Please be aware of the usual Unix environment variable pitfalls - e.g. in certain cases running the scripts as a particular user does not guarantee running them with that user's environment set up, e.g. via su.

  • If the modules in the directory need to be used only in specific circumstances (e.g. when the script(s) is executed in development/debug mode, you can either set PERL5LIB manually, or pass the -I option to perl.

  • If the modules need to be used only for specific scripts, by all users using them, use use lib/no lib pragmas in the program itself. It also should be used when the directory to be searched needs to be dynamically determined during runtime - e.g. from the script's command line parameters or script's path (see the FindBin module for very nice use case).

  • If the directories in @INC need to be manipulated according to some complicated logic, either impossible to too unwieldy to implement by combination of use lib/no lib pragmas, then use direct @INC manipulation inside BEGIN {} block or inside a special purpose library designated for @INC manipulation, which must be used by your script(s) before any other modules are used.

    An example of this is automatically switching between libraries in prod/uat/dev directories, with waterfall library pickup in prod if it's missing from dev and/or UAT (the last condition makes the standard "use lib + FindBin" solution fairly complicated. A detailed illustration of this scenario is in How do I use beta Perl modules from beta Perl scripts?.

  • An additional use case for directly manipulating @INC is to be able to add subroutine references or object references (yes, Virginia, @INC can contain custom Perl code and not just directory names, as explained in When is a subroutine reference in @INC called?).

Detecting negative numbers

I assume that the main idea is to find if number is negative and display it in correct format.

For those who use PHP5.3 might be interested in using Number Formatter Class - http://php.net/manual/en/class.numberformatter.php. This function, as well as range of other useful things, can format your number.

$profitLoss = 25000 - 55000;

$a= new \NumberFormatter("en-UK", \NumberFormatter::CURRENCY); 
$a->formatCurrency($profitLoss, 'EUR');
// would display (€30,000.00)

Here also a reference to why brackets are used for negative numbers: http://www.open.edu/openlearn/money-management/introduction-bookkeeping-and-accounting/content-section-1.7

Error while retrieving information from the server RPC:s-7:AEC-0 in Google play?

As a last resort, if all other suggestions fail, then backup all your data and do a factory reset.

java: HashMap<String, int> not working

You cannot use primitive types in HashMap. int, or double don't work. You have to use its enclosing type. for an example

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

Now both are objects, so this will work.

How do I specify different layouts for portrait and landscape orientations?

  1. Right click res folder,
  2. New -> Android Resource File
  3. in Available qualifiers, select Orientation,
  4. add to Chosen qualifier
  5. in Screen orientation, select Landscape
  6. Press OK

Using Android Studio 3.4.1, it no longer creates layout-land folder. It will create a folder and put two layout files together.

enter image description here

How to get value by class name in JavaScript or jquery?

Without jQuery:

textContent:

var text = document.querySelector('.someClassname').textContent;

Markup:

var text = document.querySelector('.someClassname').innerHTML;

Markup including the matched element:

var text = document.querySelector('.someClassname').outerHTML;

though outerHTML may not be supported by all browsers of interest and document.querySelector requires IE 8 or higher.

How to decode Unicode escape sequences like "\u00ed" to proper UTF-8 encoded characters?

There is also a solution:
http://www.welefen.com/php-unicode-to-utf8.html

function entity2utf8onechar($unicode_c){
    $unicode_c_val = intval($unicode_c);
    $f=0x80; // 10000000
    $str = "";
    // U-00000000 - U-0000007F:   0xxxxxxx
    if($unicode_c_val <= 0x7F){         $str = chr($unicode_c_val);     }     //U-00000080 - U-000007FF:  110xxxxx 10xxxxxx
    else if($unicode_c_val >= 0x80 && $unicode_c_val <= 0x7FF){         $h=0xC0; // 11000000
        $c1 = $unicode_c_val >> 6 | $h;
        $c2 = ($unicode_c_val & 0x3F) | $f;
        $str = chr($c1).chr($c2);
    } else if($unicode_c_val >= 0x800 && $unicode_c_val <= 0xFFFF){         $h=0xE0; // 11100000
        $c1 = $unicode_c_val >> 12 | $h;
        $c2 = (($unicode_c_val & 0xFC0) >> 6) | $f;
        $c3 = ($unicode_c_val & 0x3F) | $f;
        $str=chr($c1).chr($c2).chr($c3);
    }
    //U-00010000 - U-001FFFFF:  11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
    else if($unicode_c_val >= 0x10000 && $unicode_c_val <= 0x1FFFFF){         $h=0xF0; // 11110000
        $c1 = $unicode_c_val >> 18 | $h;
        $c2 = (($unicode_c_val & 0x3F000) >>12) | $f;
        $c3 = (($unicode_c_val & 0xFC0) >>6) | $f;
        $c4 = ($unicode_c_val & 0x3F) | $f;
        $str = chr($c1).chr($c2).chr($c3).chr($c4);
    }
    //U-00200000 - U-03FFFFFF:  111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
    else if($unicode_c_val >= 0x200000 && $unicode_c_val <= 0x3FFFFFF){         $h=0xF8; // 11111000
        $c1 = $unicode_c_val >> 24 | $h;
        $c2 = (($unicode_c_val & 0xFC0000)>>18) | $f;
        $c3 = (($unicode_c_val & 0x3F000) >>12) | $f;
        $c4 = (($unicode_c_val & 0xFC0) >>6) | $f;
        $c5 = ($unicode_c_val & 0x3F) | $f;
        $str = chr($c1).chr($c2).chr($c3).chr($c4).chr($c5);
    }
    //U-04000000 - U-7FFFFFFF:  1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
    else if($unicode_c_val >= 0x4000000 && $unicode_c_val <= 0x7FFFFFFF){         $h=0xFC; // 11111100
        $c1 = $unicode_c_val >> 30 | $h;
        $c2 = (($unicode_c_val & 0x3F000000)>>24) | $f;
        $c3 = (($unicode_c_val & 0xFC0000)>>18) | $f;
        $c4 = (($unicode_c_val & 0x3F000) >>12) | $f;
        $c5 = (($unicode_c_val & 0xFC0) >>6) | $f;
        $c6 = ($unicode_c_val & 0x3F) | $f;
        $str = chr($c1).chr($c2).chr($c3).chr($c4).chr($c5).chr($c6);
    }
    return $str;
}
function entities2utf8($unicode_c){
    $unicode_c = preg_replace("/\&\#([\da-f]{5})\;/es", "entity2utf8onechar('\\1')", $unicode_c);
    return $unicode_c;
}

Passing a 2D array to a C++ function

One important thing for passing multidimensional arrays is:

  • First array dimension need not be specified.
  • Second(any any further)dimension must be specified.

1.When only second dimension is available globally (either as a macro or as a global constant)

const int N = 3;

void print(int arr[][N], int m)
{
int i, j;
for (i = 0; i < m; i++)
  for (j = 0; j < N; j++)
    printf("%d ", arr[i][j]);
}

int main()
{
int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
print(arr, 3);
return 0;
}

2.Using a single pointer: In this method,we must typecast the 2D array when passing to function.

void print(int *arr, int m, int n)
{
int i, j;
for (i = 0; i < m; i++)
  for (j = 0; j < n; j++)
    printf("%d ", *((arr+i*n) + j));
 }

int main()
{
int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int m = 3, n = 3;

// We can also use "print(&arr[0][0], m, n);"
print((int *)arr, m, n);
return 0;
}

Use of 'const' for function parameters

I say const your value parameters.

Consider this buggy function:

bool isZero(int number)
{
  if (number = 0)  // whoops, should be number == 0
    return true;
  else
    return false;
}

If the number parameter was const, the compiler would stop and warn us of the bug.

How to serve all existing static files directly with NGINX, but proxy the rest to a backend server.

Try this:

location / {
    root /path/to/root;
    expires 30d;
    access_log off;
}

location ~* ^.*\.php$ {
    if (!-f $request_filename) {
        return 404;
    }
    proxy_set_header X-Real-IP  $remote_addr;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass http://127.0.0.1:8080;
}

Hopefully it works. Regular expressions have higher priority than plain strings, so all requests ending in .php should be forwared to Apache if only a corresponding .php file exists. Rest will be handled as static files. The actual algorithm of evaluating location is here.

Batch file for PuTTY/PSFTP file transfer automation

set DSKTOPDIR="D:\test"
set IPADDRESS="23.23.3.23"

>%DSKTOPDIR%\script.ftp ECHO cd %PAY_REP%
>>%DSKTOPDIR%\script.ftp ECHO mget *.report
>>%DSKTOPDIR%\script.ftp ECHO bye

:: run PSFTP Commands
psftp <domain>@%IPADDRESS% -b %DSKTOPDIR%\script.ftp

Set values using set commands before above lines.

I believe this helps you.

Referre psfpt setup for below link https://www.ssh.com/ssh/putty/putty-manuals/0.68/Chapter6.html

How to get bean using application context in spring boot

You can use ApplicationContextAware.

ApplicationContextAware:

Interface to be implemented by any object that wishes to be notified of the ApplicationContext that it runs in. Implementing this interface makes sense for example when an object requires access to a set of collaborating beans.

There are a few methods for obtaining a reference to the application context. You can implement ApplicationContextAware as in the following example:

package hello;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
 
@Component
public class ApplicationContextProvider implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    } 

 public ApplicationContext getContext() {
        return applicationContext;
    }
    
}

Update:

When Spring instantiates beans, it looks for ApplicationContextAware implementations, If they are found, the setApplicationContext() methods will be invoked.

In this way, Spring is setting current applicationcontext.

Code snippet from Spring's source code:

private void invokeAwareInterfaces(Object bean) {
        .....
        .....
 if (bean instanceof ApplicationContextAware) {                
  ((ApplicationContextAware)bean).setApplicationContext(this.applicationContext);
   }
}

Once you get the reference to Application context, you get fetch the bean whichever you want by using getBean().

Java file path in Linux

The Official Documentation is clear about Path.

Linux Syntax: /home/joe/foo

Windows Syntax: C:\home\joe\foo


Note: joe is your username for these examples.

How to hide a <option> in a <select> menu with CSS?

For HTML5, you can use the 'hidden' attribute.

<option hidden>Hidden option</option>

It is not supported by IE < 11. But if you need only to hide a few elements, maybe it would be better to just set the hidden attribute in combination with disabled in comparison to adding/removing elements or doing not semantically correct constructions.

_x000D_
_x000D_
<select>  _x000D_
  <option>Option1</option>_x000D_
  <option>Option2</option>_x000D_
  <option hidden>Hidden Option</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Reference.

Plotting categorical data with pandas and matplotlib

You can simply use value_counts on the series:

df['colour'].value_counts().plot(kind='bar')

enter image description here

Upload file to FTP using C#

public static void UploadFileToFtp(string url, string filePath, string username, string password)
{
    var fileName = Path.GetFileName(filePath);
    var request = (FtpWebRequest)WebRequest.Create(url + fileName);

    request.Method = WebRequestMethods.Ftp.UploadFile;
    request.Credentials = new NetworkCredential(username, password);
    request.UsePassive = true;
    request.UseBinary = true;
    request.KeepAlive = false;

    using (var fileStream = File.OpenRead(filePath))
    {
        using (var requestStream = request.GetRequestStream())
        {
            fileStream.CopyTo(requestStream);
            requestStream.Close();
        }
    }

    var response = (FtpWebResponse)request.GetResponse();
    Console.WriteLine("Upload done: {0}", response.StatusDescription);
    response.Close();
}

Iterate a certain number of times without storing the iteration number anywhere

Others have addressed the inability to completely avoid an iteration variable in a for loop, but there are options to reduce the work a tiny amount. range has to generate a whole bunch of numbers after all, which involves a tiny amount of work; if you want to avoid even that, you can use itertools.repeat to just get the same (ignored) value back over and over, which involves no creation/retrieval of different objects:

from itertools import repeat

for _ in repeat(None, 200):  # Runs the loop 200 times
    ...

This will run faster in microbenchmarks than for _ in range(200):, but if the loop body does meaningful work, it's a drop in the bucket. And unlike multiplying some anonymous sequence for your loop iterable, repeat has only a trivial setup cost, with no memory overhead dependent on length.

In where shall I use isset() and !empty()

isset() is not an effective way to validate text inputs and text boxes from a HTML form

You can rewrite that as "isset() is not a way to validate input." To validate input, use PHP's filter extension. filter_has_var() will tell you whether the variable exists while filter_input() will actually filter and/or sanitize the input.

Note that you don't have to use filter_has_var() prior to filter_input() and if you ask for a variable that is not set, filter_input() will simply return null.

Scroll to element on click in Angular 4

I need to do this trick, maybe because I use a custom HTML element. If I do not do this, target in onItemAmounterClick won't have the scrollIntoView method

.html

<div *ngFor"...">
      <my-component #target (click)="clicked(target)"></my-component>
</div>

.ts

onItemAmounterClick(target){
  target.__ngContext__[0].scrollIntoView({behavior: 'smooth'});
}

Print ArrayList

assium that you have a numbers list like that

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);

if you print the list

//method 1
// Conventional way of printing arraylist
for (int number : numbers) {
    System.out.print(number);
}

//method 2
// Lambda Expression to print arraylist
numbers.forEach((Integer value) -> System.out.print(value));

//method 3
// Lambda Expression to print arraylist
numbers.forEach(value -> System.out.print(value));


//method 4
// Lambda Expression (method reference) to print arraylist
numbers.forEach(System.out::print);

C# Public Enums in Classes

Just declare the enum outside the bounds of the class. Like this:

public enum card_suits
{
    Clubs,
    Hearts,
    Spades,
    Diamonds
}

public class Card
{
    ...
}

Remember that an enum is a type. You might also consider putting the enum in its own file if it's going to be used by other classes. (You're programming a card game and the suit is a very important attribute of the card that, in well-structured code, will need to be accessible by a number of classes.)

Install tkinter for Python

If, like me, you don't have root privileges on your network because of your wonderful friends in I.S., and you are working in a local install you may have some problems with the above approaches.

I spent ages on Google - but in the end, it's easy.

Download the tcl and tk from http://www.tcl.tk/software/tcltk/download.html and install them locally too.

To install locally on Linux (I did it to my home directory), extract the .tar.gz files for tcl and tk. Then open up the readme files inside the ./unix directory. I ran

cd ~/tcl8.5.11/unix
./configure --prefix=/home/cnel711 --exec-prefix=/home/cnel711
make
make install

cd ~/tk8.5.11/unix
./configure --prefix=/home/cnel711 --exec-prefix=/home/cnel711 --with-tcl=/home/cnel711/tcl8.5.11/unix
make
make install

It may seem a pain, but the files are tiny and installation is very fast.

Then re-run python setup.py build and python setup.py install in your python installation directory - and it should work. It worked for me - and I can now import Tkinter etc to my heart's content - yipidy-yay. An entire afternoon spent on this - hope this note saves others from the pain.

VBA - If a cell in column A is not blank the column B equals

Another way (Using Formulas in VBA). I guess this is the shortest VBA code as well?

Sub Sample()
    Dim ws As Worksheet
    Dim lRow As Long

    Set ws = ThisWorkbook.Sheets("Sheet1")

    With ws
        lRow = .Range("A" & .Rows.Count).End(xlUp).Row

        .Range("B1:B" & lRow).Formula = "=If(A1<>"""",""My Text"","""")"
        .Range("B1:B" & lRow).Value = .Range("B1:B" & lRow).Value
    End With
End Sub

ERROR in The Angular Compiler requires TypeScript >=3.1.1 and <3.2.0 but 3.2.1 was found instead

For following Error:

ERROR in The Angular Compiler requires TypeScript >=3.4.0 and <3.6.0 but 3.6.3 was found instead.

Run following NPM command:

$ npm install [email protected]

Source Link

Disable XML validation in Eclipse

You have two options:

  1. Configure Workspace Settings (disable the validation for the current workspace): Go to Window > Preferences > Validation and uncheck the manual and build for: XML Schema Validator, XML Validator

  2. Check enable project specific settings (disable the validation for this project): Right-click on the project, select Properties > Validation and uncheck the manual and build for: XML Schema Validator, XML Validator

Right-click on the project and select Validate to make the errors disappear.

Javascript (+) sign concatenates instead of giving sum of variables

Another alternative could be using:

divID = "question-" + (i - -1);

Subtracting a negative is the same as adding, and a minus cannot be used for concatenation

Edit: Forgot that brackets are still necessary since code is read from left to right.

Create PDF with Java

Following are few libraries to create PDF with Java:

  1. iText
  2. Apache PDFBox
  3. BFO

I have used iText for genarating PDF's with a little bit of pain in the past.

Or you can try using FOP: FOP is an XSL formatter written in Java. It is used in conjunction with an XSLT transformation engine to format XML documents into PDF.

How to execute a command in a remote computer?

I use the little utility which comes with PureMPI.net called execcmd.exe. Its syntax is as follows:

execcmd \\yourremoteserver <your command here>

Doesn't get any simpler than this :)

Disable submit button on form submit

How to disable submit button

just call a function on onclick event and... return true to submit and false to disable submit. OR call a function on window.onload like :

window.onload = init();

and in init() do something like this :

var theForm = document.getElementById(‘theForm’);
theForm.onsubmit =  // what ever you want to do 

Entity Framework - Include Multiple Levels of Properties

I also had to use multiple includes and at 3rd level I needed multiple properties

(from e in context.JobCategorySet
                      where e.Id == id &&
                            e.AgencyId == agencyId
                      select e)
                      .Include(x => x.JobCategorySkillDetails)
                      .Include(x => x.Shifts.Select(r => r.Rate).Select(rt => rt.DurationType))
                      .Include(x => x.Shifts.Select(r => r.Rate).Select(rt => rt.RuleType))
                      .Include(x => x.Shifts.Select(r => r.Rate).Select(rt => rt.RateType))
                      .FirstOrDefaultAsync();

This may help someone :)

Where Is Machine.Config?

It semi-depends though... mine is:

C:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG

and

C:\Windows\Microsoft.NET\Framework64\v2.0.50727\CONFIG

Python assigning multiple variables to same value? list behavior

Yes, that's the expected behavior. a, b and c are all set as labels for the same list. If you want three different lists, you need to assign them individually. You can either repeat the explicit list, or use one of the numerous ways to copy a list:

b = a[:] # this does a shallow copy, which is good enough for this case
import copy
c = copy.deepcopy(a) # this does a deep copy, which matters if the list contains mutable objects

Assignment statements in Python do not copy objects - they bind the name to an object, and an object can have as many labels as you set. In your first edit, changing a[0], you're updating one element of the single list that a, b, and c all refer to. In your second, changing e, you're switching e to be a label for a different object (4 instead of 3).

Delete all nodes and relationships in neo4j 1.8

It will do the trick..

Match (n)-[r]-()
Delete n,r;

Convert pandas timezone-aware DateTimeIndex to naive timestamp, but in certain timezone

The most important thing is add tzinfo when you define a datetime object.

from datetime import datetime, timezone
from tzinfo_examples import HOUR, Eastern
u0 = datetime(2016, 3, 13, 5, tzinfo=timezone.utc)
for i in range(4):
     u = u0 + i*HOUR
     t = u.astimezone(Eastern)
     print(u.time(), 'UTC =', t.time(), t.tzname())

Xcode project not showing list of simulators

I could not find any solution that would fix my issue. All simulators were there for all projects but the one that I needed them.

Solution:

Build Settings -> Architectures -> Supported Platforms:

changed from iphoneos to iOS

How to change the port number for Asp.Net core app?

In Asp.net core 2.0 WebApp, if you are using visual studio search LaunchSettings.json. I am adding my LaunchSettings.json, you can change port no as u can see.

enter image description here

Change GridView row color based on condition

\\loop throgh all rows of the grid view  

if (GridView1.Rows[i - 1].Cells[4].Text.ToString() == "value1")
{
   GridView1.Rows[i - 1].ForeColor = Color.Black;
}
else if (GridView1.Rows[i - 1].Cells[4].Text.ToString() == "value2")
{
   GridView1.Rows[i - 1].ForeColor = Color.Blue;
}
else if (GridView1.Rows[i - 1].Cells[4].Text.ToString() == "value3")
{
   GridView1.Rows[i - 1].ForeColor = Color.Red;
}
else if (GridView1.Rows[i - 1].Cells[4].Text.ToString() == "value4")
{
   GridView1.Rows[i - 1].ForeColor = Color.Green;
}

Revert to a commit by a SHA hash in Git?

This might work:

git checkout 56e05f
echo ref: refs/heads/master > .git/HEAD
git commit

Python: How to pip install opencv2 with specific version 2.4.9?

python3.6 -m pip install opencv-python

will install cv2 in linux in branch python3.6

iPhone: How to get current milliseconds?

So far I found gettimeofday a good solution on iOS (iPad), when you want to perform some interval evaluation (say, framerate, timing of a rendering frame...) :

#include <sys/time.h>
struct timeval time;
gettimeofday(&time, NULL);
long millis = (time.tv_sec * 1000) + (time.tv_usec / 1000);

What is managed or unmanaged code in programming?

Managed Code:
Code that runs under a "contract of cooperation" with the common language runtime. Managed code must supply the metadata necessary for the runtime to provide services such as memory management, cross-language integration, code access security, and automatic lifetime control of objects. All code based on Microsoft intermediate language (MSIL) executes as managed code.

Un-Managed Code:
Code that is created without regard for the conventions and requirements of the common language runtime. Unmanaged code executes in the common language runtime environment with minimal services (for example, no garbage collection, limited debugging, and so on).

Reference: http://www.dotnetspider.com/forum/11612-difference-between-managed-and-unmanaged-code.aspx

The remote server returned an error: (403) Forbidden

    private class GoogleShortenedURLResponse
    {
        public string id { get; set; }
        public string kind { get; set; }
        public string longUrl { get; set; }
    }

    private class GoogleShortenedURLRequest
    {
        public string longUrl { get; set; }
    }

    public ActionResult Index1()
    {
        return View();
    }

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult ShortenURL(string longurl)
    {
        string googReturnedJson = string.Empty;
        JavaScriptSerializer javascriptSerializer = new JavaScriptSerializer();

        GoogleShortenedURLRequest googSentJson = new GoogleShortenedURLRequest();
        googSentJson.longUrl = longurl;
        string jsonData = javascriptSerializer.Serialize(googSentJson);

        byte[] bytebuffer = Encoding.UTF8.GetBytes(jsonData);

        WebRequest webreq = WebRequest.Create("https://www.googleapis.com/urlshortener/v1/url");
        webreq.Method = WebRequestMethods.Http.Post;
        webreq.ContentLength = bytebuffer.Length;
        webreq.ContentType = "application/json";

        using (Stream stream = webreq.GetRequestStream())
        {
            stream.Write(bytebuffer, 0, bytebuffer.Length);
            stream.Close();
        }

        using (HttpWebResponse webresp = (HttpWebResponse)webreq.GetResponse())
        {
            using (Stream dataStream = webresp.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(dataStream))
                {
                    googReturnedJson = reader.ReadToEnd();
                }
            }
        }

        //GoogleShortenedURLResponse googUrl = javascriptSerializer.Deserialize<googleshortenedurlresponse>(googReturnedJson);

        //ViewBag.ShortenedUrl = googUrl.id;
        return View();
    }

Compression/Decompression string with C#

The code to compress/decompress a string

public static void CopyTo(Stream src, Stream dest) {
    byte[] bytes = new byte[4096];

    int cnt;

    while ((cnt = src.Read(bytes, 0, bytes.Length)) != 0) {
        dest.Write(bytes, 0, cnt);
    }
}

public static byte[] Zip(string str) {
    var bytes = Encoding.UTF8.GetBytes(str);

    using (var msi = new MemoryStream(bytes))
    using (var mso = new MemoryStream()) {
        using (var gs = new GZipStream(mso, CompressionMode.Compress)) {
            //msi.CopyTo(gs);
            CopyTo(msi, gs);
        }

        return mso.ToArray();
    }
}

public static string Unzip(byte[] bytes) {
    using (var msi = new MemoryStream(bytes))
    using (var mso = new MemoryStream()) {
        using (var gs = new GZipStream(msi, CompressionMode.Decompress)) {
            //gs.CopyTo(mso);
            CopyTo(gs, mso);
        }

        return Encoding.UTF8.GetString(mso.ToArray());
    }
}

static void Main(string[] args) {
    byte[] r1 = Zip("StringStringStringStringStringStringStringStringStringStringStringStringStringString");
    string r2 = Unzip(r1);
}

Remember that Zip returns a byte[], while Unzip returns a string. If you want a string from Zip you can Base64 encode it (for example by using Convert.ToBase64String(r1)) (the result of Zip is VERY binary! It isn't something you can print to the screen or write directly in an XML)

The version suggested is for .NET 2.0, for .NET 4.0 use the MemoryStream.CopyTo.

IMPORTANT: The compressed contents cannot be written to the output stream until the GZipStream knows that it has all of the input (i.e., to effectively compress it needs all of the data). You need to make sure that you Dispose() of the GZipStream before inspecting the output stream (e.g., mso.ToArray()). This is done with the using() { } block above. Note that the GZipStream is the innermost block and the contents are accessed outside of it. The same goes for decompressing: Dispose() of the GZipStream before attempting to access the data.

Mipmaps vs. drawable folders

The mipmap folders are for placing your app/launcher icons (which are shown on the homescreen) in only. Any other drawable assets you use should be placed in the relevant drawable folders as before.

According to this Google blogpost:

It’s best practice to place your app icons in mipmap- folders (not the drawable- folders) because they are used at resolutions different from the device’s current density.

When referencing the mipmap- folders ensure you are using the following reference:

android:icon="@mipmap/ic_launcher"

The reason they use a different density is that some launchers actually display the icons larger than they were intended. Because of this, they use the next size up.

mongodb, replicates and error: { "$err" : "not master and slaveOk=false", "code" : 13435 }

slaveOk does not work anymore. One needs to use readPreference https://docs.mongodb.com/v3.0/reference/read-preference/#primaryPreferred

e.g.

const client = new MongoClient(mongoURL + "?readPreference=primaryPreferred", { useUnifiedTopology: true, useNewUrlParser: true });

What are the differences between a clustered and a non-clustered index?

Clustered indexes are stored physically on the table. This means they are the fastest and you can only have one clustered index per table.

Non-clustered indexes are stored separately, and you can have as many as you want.

The best option is to set your clustered index on the most used unique column, usually the PK. You should always have a well selected clustered index in your tables, unless a very compelling reason--can't think of a single one, but hey, it may be out there--for not doing so comes up.

How to set JAVA_HOME in Linux for all users

This is a very simple script to solve the problem

export JAVA_HOME_BIN=`which java`
export JAVA_HOME_DIR=`dirname $JAVA_HOME_BIN`
export JAVA_HOME=`dirname $JAVA_HOME_DIR`

And for testing:

echo $JAVA_HOME

Failed to read artifact descriptor for org.apache.maven.plugins:maven-source-plugin:jar:2.4

org.apache.maven.plugins:maven-source-plugin does not exist in the repository http://repo.maven.apache.org/maven2.

You have to download it from Maven central where it exists => maven-source-plugin

Verify your pom definition or your settings.xml file.

Changing CSS style from ASP.NET code

I find that code gets messy fast when C# code is used to modify CSS values. Perhaps a better approach is for your code to dynamically set the class attribute on the div tag and then store any specific CSS settings in the style sheet.

That might not work for your situation, but its a decent default position if you need to change the style on the fly in server side code.

Recreate the default website in IIS

You can try to restore your previous state by doing the following:

  1. Go to IIS Manager
  2. Right-click on your Local Computer.
  3. Point to All Tasks
  4. Point to Backup/Restore Configuration
  5. Select the configuration you want to restore
  6. Wait untill configuration applies

How do I show multiple recaptchas on a single page?

Here is a nice guide for doing exactly that:

http://mycodde.blogspot.com.ar/2014/12/multiple-recaptcha-demo-same-page.html

Basically you add some parameters to the api call and manually render each recaptcha:

<script src="https://www.google.com/recaptcha/api.js?onload=myCallBack&render=explicit" async defer></script>
<script>
        var recaptcha1;
        var recaptcha2;
        var myCallBack = function() {
            //Render the recaptcha1 on the element with ID "recaptcha1"
            recaptcha1 = grecaptcha.render('recaptcha1', {
                'sitekey' : '6Lc_0f4SAAAAAF9ZA', //Replace this with your Site key
                'theme' : 'light'
            });

            //Render the recaptcha2 on the element with ID "recaptcha2"
            recaptcha2 = grecaptcha.render('recaptcha2', {
                'sitekey' : '6Lc_0f4SAAAAAF9ZA', //Replace this with your Site key
                'theme' : 'dark'
            });
        };
</script>

PS: The "grecaptcha.render" method receives an ID

Using Google Translate in C#

If you want to translate your resources, just download MAT (Multilingual App Toolkit) for Visual Studio. https://marketplace.visualstudio.com/items?itemName=MultilingualAppToolkit.MultilingualAppToolkit-18308 This is the way to go to translate your projects in Visual Studio. https://blogs.msdn.microsoft.com/matdev/

SQL Server : export query as a .txt file

You can use bcp utility.

To copy the result set from a Transact-SQL statement to a data file, use the queryout option. The following example copies the result of a query into the Contacts.txt data file. The example assumes that you are using Windows Authentication and have a trusted connection to the server instance on which you are running the bcp command. At the Windows command prompt, enter:

bcp "<your query here>" queryout Contacts.txt -c -T

You can use BCP by directly calling as operating sytstem command in SQL Agent job.

Get checkbox list values with jQuery

Not tested but should work:

$("#MyDiv td input:checked").each(function()
{
    alert($(this).attr("id"));
});

jQuery-- Populate select from json

I just used the javascript console in Chrome to do this. I replaced some of your stuff with placeholders.

var temp= ['one', 'two', 'three']; //'${temp}';
//alert(options);
var $select = $('<select>'); //$('#down');                        
$select.find('option').remove();                          
$.each(temp, function(key, value) {              
    $('<option>').val(key).text(value).appendTo($select);
});
console.log($select.html());

Output:

<option value="0">one</option><option value="1">two</option><option value="2">three</option>

However it looks like your json is probably actually a string because the following will end up doing what you describe. So make your JSON actual JSON not a string.

var temp= "['one', 'two', 'three']"; //'${temp}';
//alert(options);
var $select = $('<select>'); //$('#down');                        
$select.find('option').remove();                          
$.each(temp, function(key, value) {              
    $('<option>').val(key).text(value).appendTo($select);
});
console.log($select.html());

What causes an HTTP 405 "invalid method (HTTP verb)" error when POSTing a form to PHP on IIS?

I don't know why but its happened when you submit a form inside a page to itself by the POST method.

So change the method="post" to method="get" or remove action="anyThings.any" from your <form> tag.

Insert an element at a specific index in a list and return the updated list

Most performance efficient approach

You may also insert the element using the slice indexing in the list. For example:

>>> a = [1, 2, 4]
>>> insert_at = 2  # Index at which you want to insert item

>>> b = a[:]   # Created copy of list "a" as "b".
               # Skip this step if you are ok with modifying the original list

>>> b[insert_at:insert_at] = [3]  # Insert "3" within "b"
>>> b
[1, 2, 3, 4]

For inserting multiple elements together at a given index, all you need to do is to use a list of multiple elements that you want to insert. For example:

>>> a = [1, 2, 4]
>>> insert_at = 2   # Index starting from which multiple elements will be inserted

# List of elements that you want to insert together at "index_at" (above) position
>>> insert_elements = [3, 5, 6]

>>> a[insert_at:insert_at] = insert_elements
>>> a   # [3, 5, 6] are inserted together in `a` starting at index "2"
[1, 2, 3, 5, 6, 4]

To know more about slice indexing, you can refer: Understanding slice notation.

Note: In Python 3.x, difference of performance between slice indexing and list.index(...) is significantly reduced and both are almost equivalent. However, in Python 2.x, this difference is quite noticeable. I have shared performance comparisons later in this answer.


Alternative using list comprehension (but very slow in terms of performance):

As an alternative, it can be achieved using list comprehension with enumerate too. (But please don't do it this way. It is just for illustration):

>>> a = [1, 2, 4]
>>> insert_at = 2

>>> b = [y for i, x in enumerate(a) for y in ((3, x) if i == insert_at else (x, ))]
>>> b
[1, 2, 3, 4]

Performance comparison of all solutions

Here's the timeit comparison of all the answers with list of 1000 elements on Python 3.9.1 and Python 2.7.16. Answers are listed in the order of performance for both the Python versions.

Python 3.9.1

  1. My answer using sliced insertion - Fastest ( 2.25 µsec per loop)

    python3 -m timeit -s "a = list(range(1000))" "b = a[:]; b[500:500] = [3]"
    100000 loops, best of 5: 2.25 µsec per loop
    
  2. Rushy Panchal's answer with most votes using list.insert(...)- Second (2.33 µsec per loop)

    python3 -m timeit -s "a = list(range(1000))" "b = a[:]; b.insert(500, 3)"
    100000 loops, best of 5: 2.33 µsec per loop
    
  3. ATOzTOA's accepted answer based on merge of sliced lists - Third (5.01 µsec per loop)

    python3 -m timeit -s "a = list(range(1000))" "b = a[:500] + [3] + a[500:]"
    50000 loops, best of 5: 5.01 µsec per loop
    
  4. My answer with List Comprehension and enumerate - Fourth (very slow with 135 µsec per loop)

    python3 -m timeit -s "a = list(range(1000))" "[y for i, x in enumerate(a) for y in ((3, x) if i == 500 else (x, )) ]"
    2000 loops, best of 5: 135 µsec per loop
    

Python 2.7.16

  1. My answer using sliced insertion - Fastest (2.09 µsec per loop)

    python -m timeit -s "a = list(range(1000))" "b = a[:]; b[500:500] = [3]"
    100000 loops, best of 3: 2.09 µsec per loop
    
  2. Rushy Panchal's answer with most votes using list.insert(...)- Second (2.36 µsec per loop)

    python -m timeit -s "a = list(range(1000))" "b = a[:]; b.insert(500, 3)"
    100000 loops, best of 3: 2.36 µsec per loop
    
  3. ATOzTOA's accepted answer based on merge of sliced lists - Third (4.44 µsec per loop)

    python -m timeit -s "a = list(range(1000))" "b = a[:500] + [3] + a[500:]"
    100000 loops, best of 3: 4.44 µsec per loop
    
  4. My answer with List Comprehension and enumerate - Fourth (very slow with 103 µsec per loop)

    python -m timeit -s "a = list(range(1000))" "[y for i, x in enumerate(a) for y in ((3, x) if i == 500 else (x, )) ]"
    10000 loops, best of 3: 103 µsec per loop
    

Default settings Raspberry Pi /etc/network/interfaces

These are the default settings I have for /etc/network/interfaces (including WiFi settings) for my Raspberry Pi 1:

auto lo

iface lo inet loopback
iface eth0 inet dhcp

allow-hotplug wlan0
iface wlan0 inet manual
wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf
iface default inet dhcp

How to select the row with the maximum value in each group

by is a version of tapply for data frames:

res <- by(group, group$Subject, FUN=function(df) df[which.max(df$pt),])

It returns an object of class by so we convert it to data frame:

do.call(rbind, b)
  Subject pt Event
1       1  5     2
2       2 17     2
3       3  5     2

Invoke-WebRequest, POST with parameters

Single command without ps variables when using JSON as body {lastName:"doe"} for POST api call:

Invoke-WebRequest -Headers @{"Authorization" = "Bearer N-1234ulmMGhsDsCAEAzmo1tChSsq323sIkk4Zq9"} `
                  -Method POST `
                  -Body (@{"lastName"="doe";}|ConvertTo-Json) `
                  -Uri https://api.dummy.com/getUsers `
                  -ContentType application/json

Reload activity in Android

I needed to update a message list in one of my applications in a hurry, so I just performed a refresh of my main UI activity before I closed the dialog I was in. I'm sure there are better ways to accomplish this as well.

// Refresh main activity upon close of dialog box
Intent refresh = new Intent(this, clsMainUIActivity.class);
startActivity(refresh);
this.finish(); //

How to count days between two dates in PHP?

i created a function in which if you pass two dates than it will return day wise value. For better understanding please see the output of start date : 2018-11-12 11:41:19 and End Date 2018-11-16 12:07:26

private function getTimeData($str1,$str2){
$datetime1 = strtotime($str1);
$datetime2 = strtotime($str2);
$myArray = array();
if(date('d', $datetime2) != date('d', $datetime1) ||  date('m', $datetime2) != date('m', $datetime1) || date('y', $datetime2) != date('y', $datetime1)){
    $exStr1 = explode(' ',$str1);
    $exStr2 = explode(' ',$str2);
    $datediff = strtotime($exStr2[0]) - strtotime($exStr1[0]);
    $totalDays = round($datediff / (60 * 60 * 24));
    $actualDate1 = $datetime1;
    $actualDate2 = date('Y-m-d', $datetime1)." 23:59:59";
    $interval  = abs(strtotime($actualDate2)-$actualDate1);
    $minutes   = round($interval / 60);
    $myArray[0]['startDate'] = date('Y-m-d H:i:s', $actualDate1); 
    $myArray[0]['endDate'] = $actualDate2;
    $myArray[0]['minutes'] = $minutes;
    $i = 1;
    if($totalDays > 1){    
        for($i=1; $i<$totalDays; $i++){
            $dayString = "+".$i." day";
            $edate = strtotime($dayString, $actualDate1);
            $myArray[$i]['startDate'] = date('Y-m-d', $edate)." 00:00:00"; 
            $myArray[$i]['endDate'] = date('Y-m-d', $edate)." 23:59:59"; 
            $myArray[$i]['minutes'] = 1440;
        }
    }
    $actualSecDate1 = date('Y-m-d', $datetime2)." 00:00:00";
    $actualSecDate2 = $datetime2;
    $interval  = abs(strtotime($actualSecDate1)-$actualSecDate2);
    $minutes   = round($interval / 60);
    $myArray[$i]['startDate'] = $actualSecDate1; 
    $myArray[$i]['endDate'] = date('Y-m-d H:i:s', $actualSecDate2); 
    $myArray[$i]['minutes'] = $minutes;
}
else{
    $interval  = abs($datetime2-$datetime1);
    $minutes   = round($interval / 60);
    $myArray[0]['startDate'] = date('Y-m-d H:i:s', $datetime1); 
    $myArray[0]['endDate'] = date('Y-m-d H:i:s', $datetime2);
    $myArray[0]['minutes'] = $minutes;
}

return $myArray;
}

Output

Array
(
[0] => Array
    (
        [startDate] => 2018-11-12 11:41:19
        [endDate] => 2018-11-12 23:59:59
        [minutes] => 739
    )

[1] => Array
    (
        [startDate] => 2018-11-13 00:00:00
        [endDate] => 2018-11-13 23:59:59
        [minutes] => 1440
    )

[2] => Array
    (
        [startDate] => 2018-11-14 00:00:00
        [endDate] => 2018-11-14 23:59:59
        [minutes] => 1440
    )

[3] => Array
    (
        [startDate] => 2018-11-15 00:00:00
        [endDate] => 2018-11-15 23:59:59
        [minutes] => 1440
    )

[4] => Array
    (
        [startDate] => 2018-11-16 00:00:00
        [endDate] => 2018-11-16 12:07:26
        [minutes] => 727
    )
)

dyld: Library not loaded: /usr/local/lib/libpng16.16.dylib with anything php related

I followed the above (never a bad idea to keep up to date with brew anyhow) and still had the same exact issue:

LAPTOP:folder Username$ php -v
dyld: Library not loaded: /usr/local/lib/libpng15.15.dylib
  Referenced from: /usr/local/bin/php
  Reason: image not found
Trace/BPT trap: 5

Then figured out a simpler way:

Search for your libpng version(s) on your box:

# Requires locate & updatedb for mac os x
# See Link [1] 
LAPTOP:folder Username$ locate libpng15.15.dylib
/Applications/GIMP.app/Contents/Resources/lib/libpng15.15.dylib
/usr/X11/lib/libpng15.15.dylib
/usr/local/Cellar/libpng/1.5.14/lib/libpng15.15.dylib

Make a symlink:

LAPTOP:folder Username$ ln -s /usr/local/Cellar/libpng/1.5.14/lib/libpng15.15.dylib /usr/local/lib/libpng15.15.dylib

Try again:

LAPTOP:folder Username$ php -v
PHP 5.3.26 (cli) (built: Aug 25 2013 16:07:23) 
Copyright (c) 1997-2013 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2013 Zend Technologies
    with Xdebug v2.2.3, Copyright (c) 2002-2013, by Derick Rethans

1) Mac OS X equivalent of locate

Explanation of the UML arrows

Here is simplified tutorial:

Practical UML

For more I recommend to get some literature.

How to use QueryPerformanceCounter?

#include <windows.h>

double PCFreq = 0.0;
__int64 CounterStart = 0;

void StartCounter()
{
    LARGE_INTEGER li;
    if(!QueryPerformanceFrequency(&li))
    cout << "QueryPerformanceFrequency failed!\n";

    PCFreq = double(li.QuadPart)/1000.0;

    QueryPerformanceCounter(&li);
    CounterStart = li.QuadPart;
}
double GetCounter()
{
    LARGE_INTEGER li;
    QueryPerformanceCounter(&li);
    return double(li.QuadPart-CounterStart)/PCFreq;
}

int main()
{
    StartCounter();
    Sleep(1000);
    cout << GetCounter() <<"\n";
    return 0;
}

This program should output a number close to 1000 (windows sleep isn't that accurate, but it should be like 999).

The StartCounter() function records the number of ticks the performance counter has in the CounterStart variable. The GetCounter() function returns the number of milliseconds since StartCounter() was last called as a double, so if GetCounter() returns 0.001 then it has been about 1 microsecond since StartCounter() was called.

If you want to have the timer use seconds instead then change

PCFreq = double(li.QuadPart)/1000.0;

to

PCFreq = double(li.QuadPart);

or if you want microseconds then use

PCFreq = double(li.QuadPart)/1000000.0;

But really it's about convenience since it returns a double.

Chain-calling parent initialisers in python

You can simply write :

class A(object):

    def __init__(self):
        print "Initialiser A was called"

class B(A):

    def __init__(self):
        A.__init__(self)
        # A.__init__(self,<parameters>) if you want to call with parameters
        print "Initialiser B was called"

class C(B):

    def __init__(self):
        # A.__init__(self) # if you want to call most super class...
        B.__init__(self)
        print "Initialiser C was called"

How do I display Ruby on Rails form validation error messages one at a time?

I resolved it like this:

<% @user.errors.each do |attr, msg| %>
  <li>
    <%= @user.errors.full_messages_for(attr).first if @user.errors[attr].first == msg %>
  </li>
<% end %>

This way you are using the locales for the error messages.

How to perform .Max() on a property of all objects in a collection and return the object with maximum value

We have an extension method to do exactly this in MoreLINQ. You can look at the implementation there, but basically it's a case of iterating through the data, remembering the maximum element we've seen so far and the maximum value it produced under the projection.

In your case you'd do something like:

var item = items.MaxBy(x => x.Height);

This is better (IMO) than any of the solutions presented here other than Mehrdad's second solution (which is basically the same as MaxBy):

  • It's O(n) unlike the previous accepted answer which finds the maximum value on every iteration (making it O(n^2))
  • The ordering solution is O(n log n)
  • Taking the Max value and then finding the first element with that value is O(n), but iterates over the sequence twice. Where possible, you should use LINQ in a single-pass fashion.
  • It's a lot simpler to read and understand than the aggregate version, and only evaluates the projection once per element

How does lock work exactly?

The part within the lock statement can only be executed by one thread, so all other threads will wait indefinitely for it the thread holding the lock to finish. This can result in a so-called deadlock.

What is the recommended project structure for spring boot rest projects?

Though this question has an accepted answer, still I would like to share my project structure for RESTful services.

src/main/java
    +- com
        +- example
            +- Application.java
            +- ApplicationConstants.java
                +- configuration
                |   +- ApplicationConfiguration.java
                +- controller
                |   +- ApplicationController.java
                +- dao
                |   +- impl
                |   |   +- ApplicationDaoImpl.java
                |   +- ApplicationDao.java
                +- dto
                |   +- ApplicationDto.java
                +- service
                |   +- impl
                |   |   +- ApplicationServiceImpl.java
                |   +- ApplicationService.java
                +- util
                |   +- ApplicationUtils.java
                +- validation
                |   +- impl
                |   |   +- ApplicationValidationImpl.java
                |   +- ApplicationValidation.java

DAO = Data Access Object.
DTO = Data Transfer Object.

TypeError: 'module' object is not callable

socket is a module, containing the class socket.

You need to do socket.socket(...) or from socket import socket:

>>> import socket
>>> socket
<module 'socket' from 'C:\Python27\lib\socket.pyc'>
>>> socket.socket
<class 'socket._socketobject'>
>>>
>>> from socket import socket
>>> socket
<class 'socket._socketobject'>

This is what the error message means:
It says module object is not callable, because your code is calling a module object. A module object is the type of thing you get when you import a module. What you were trying to do is to call a class object within the module object that happens to have the same name as the module that contains it.

Here is a way to logically break down this sort of error:

  • "module object is not callable. Python is telling me my code trying to call something that cannot be called. What is my code trying to call?"
  • "The code is trying to call on socket. That should be callable! Is the variable socket is what I think it is?`
  • I should print out what socket is and check print socket

Get Filename Without Extension in Python

If I had to do this with a regex, I'd do it like this:

s = re.sub(r'\.jpg$', '', s)

Select NOT IN multiple columns

I use a way that may look stupid but it works for me. I simply concat the columns I want to compare and use NOT IN:

SELECT *
FROM table1 t1
WHERE CONCAT(t1.first_name,t1.last_name) NOT IN (SELECT CONCAT(t2.first_name,t2.last_name) FROM table2 t2)

How to add a Hint in spinner in XML

Step 1:

Your array looks like. last item your hint

Ex : private String[] yourArray = new String[] {"Staff", "Student","Your Hint"};

Step 2:

Create HintAdpater.java (Just copy & paste)

This class not return last item.. So your Hint not displays.

HintAdapter.java

package ajax.com.vvcoe.utils;

import android.content.Context;
import android.widget.ArrayAdapter;

import java.util.List;


public class HintAdapter  extends ArrayAdapter<String> {


public HintAdapter(Context context, int resource) {
    super(context, resource);
}

public HintAdapter(Context context, int resource, int textViewResourceId) {
    super(context, resource, textViewResourceId);
}

public HintAdapter(Context context, int resource, String[] objects) {
    super(context, resource, objects);
}

public HintAdapter(Context context, int resource, int textViewResourceId, String[] objects) {
    super(context, resource, textViewResourceId, objects);
}

public HintAdapter(Context context, int resource, List<String> objects) {
    super(context, resource, objects);
}

public HintAdapter(Context context, int resource, int textViewResourceId, List<String> objects) {
    super(context, resource, textViewResourceId, objects);
}

@Override
public int getCount() {
    // don't display last item. It is used as hint.
    int count = super.getCount();
    return count > 0 ? count - 1 : count;
}
}

Step 3:

Set spinner adapter like this

    HintAdapter hintAdapter=new HintAdapter(this,android.R.layout.simple_list_item_1,yourArray);
    yourSpinner.setAdapter(hintAdapter);
    // show hint
    yourSpinner.setSelection(hintAdapter.getCount());

Credit goes to @Yakiv Mospan from this answer - https://stackoverflow.com/a/22774285/3879847

I modify some changes only..

Removing the first 3 characters from a string

Just use substring: "apple".substring(3); will return le

sql: check if entry in table A exists in table B

This also works

SELECT *
FROM tableB
WHERE ID NOT IN (
  SELECT ID FROM tableA
);

How to set Spring profile from system variable?

I normally configure the applicationContext using Annotation based configuration rather than XML based configuration. Anyway, I believe both of them have the same priority.

*Answering your question, system variable has higher priority *


Getting profile based beans from applicationContext

  • Use @Profile on a Bean

@Component
@Profile("dev")
public class DatasourceConfigForDev

Now, the profile is dev

Note : if the Profile is given as @Profile("!dev") then the profile will exclude dev and be for all others.

  • Use profiles attribute in XML

<beans profile="dev">
    <bean id="DatasourceConfigForDev" class="org.skoolguy.profiles.DatasourceConfigForDev"/>
</beans>

Set the value for profile:

  • Programmatically via WebApplicationInitializer interface

    In web applications, WebApplicationInitializer can be used to configure the ServletContext programmatically
@Configuration
public class MyWebApplicationInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
            servletContext.setInitParameter("spring.profiles.active", "dev");
    }
}
  • Programmatically via ConfigurableEnvironment

    You can also set profiles directly on the environment:
    @Autowired
    private ConfigurableEnvironment env;

    // ...

    env.setActiveProfiles("dev");
  • Context Parameter in web.xml

    profiles can be activated in the web.xml of the web application as well, using a context parameter:
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/app-config.xml</param-value>
    </context-param>
    <context-param>
        <param-name>spring.profiles.active</param-name>
        <param-value>dev</param-value>
    </context-param>
  • JVM System Parameter

    The profile names passed as the parameter will be activated during application start-up:

    -Dspring.profiles.active=dev
    

    In IDEs, you can set the environment variables and values to use when an application runs. The following is the Run Configuration in Eclipse:

Eclipse Run Configuration - screenshot is unavailable

  • Environment Variable

    to set via command line : export spring_profiles_active=dev

Any bean that does not specify a profile belongs to “default” profile.


The priority order is :

  1. Context parameter in web.xml
  2. WebApplicationInitializer
  3. JVM System parameter
  4. Environment variable

If else on WHERE clause

IF is used to select the field, then the LIKE clause is placed after it:

SELECT  `id` ,  `naam` 
FROM  `klanten` 
WHERE IF(`email` != '', `email`, `email2`) LIKE  '%@domain.nl%'

How to create a DateTime equal to 15 minutes ago?

I have provide two methods for doing so for minutes as well as for years and hours if you want to see more examples:

import datetime
print(datetime.datetime.now())
print(datetime.datetime.now() - datetime.timedelta(minutes = 15))
print(datetime.datetime.now() + datetime.timedelta(minutes = -15))
print(datetime.timedelta(hours = 5))
print(datetime.datetime.now() + datetime.timedelta(days = 3))
print(datetime.datetime.now() + datetime.timedelta(days = -9))
print(datetime.datetime.now() - datetime.timedelta(days = 9))

I get the following results:

2016-06-03 16:04:03.706615
2016-06-03 15:49:03.706622
2016-06-03 15:49:03.706642
5:00:00
2016-06-06 16:04:03.706665
2016-05-25 16:04:03.706676
2016-05-25 16:04:03.706687
2016-06-03
16:04:03.706716

Pandas: Subtracting two date columns and the result being an integer

You can use datetime module to help here. Also, as a side note, a simple date subtraction should work as below:

import datetime as dt
import numpy as np
import pandas as pd

#Assume we have df_test:
In [222]: df_test
Out[222]: 
   first_date second_date
0  2016-01-31  2015-11-19
1  2016-02-29  2015-11-20
2  2016-03-31  2015-11-21
3  2016-04-30  2015-11-22
4  2016-05-31  2015-11-23
5  2016-06-30  2015-11-24
6         NaT  2015-11-25
7         NaT  2015-11-26
8  2016-01-31  2015-11-27
9         NaT  2015-11-28
10        NaT  2015-11-29
11        NaT  2015-11-30
12 2016-04-30  2015-12-01
13        NaT  2015-12-02
14        NaT  2015-12-03
15 2016-04-30  2015-12-04
16        NaT  2015-12-05
17        NaT  2015-12-06

In [223]: df_test['Difference'] = df_test['first_date'] - df_test['second_date'] 

In [224]: df_test
Out[224]: 
   first_date second_date  Difference
0  2016-01-31  2015-11-19     73 days
1  2016-02-29  2015-11-20    101 days
2  2016-03-31  2015-11-21    131 days
3  2016-04-30  2015-11-22    160 days
4  2016-05-31  2015-11-23    190 days
5  2016-06-30  2015-11-24    219 days
6         NaT  2015-11-25         NaT
7         NaT  2015-11-26         NaT
8  2016-01-31  2015-11-27     65 days
9         NaT  2015-11-28         NaT
10        NaT  2015-11-29         NaT
11        NaT  2015-11-30         NaT
12 2016-04-30  2015-12-01    151 days
13        NaT  2015-12-02         NaT
14        NaT  2015-12-03         NaT
15 2016-04-30  2015-12-04    148 days
16        NaT  2015-12-05         NaT
17        NaT  2015-12-06         NaT

Now, change type to datetime.timedelta, and then use the .days method on valid timedelta objects.

In [226]: df_test['Diffference'] = df_test['Difference'].astype(dt.timedelta).map(lambda x: np.nan if pd.isnull(x) else x.days)

In [227]: df_test
Out[227]: 
   first_date second_date  Difference  Diffference
0  2016-01-31  2015-11-19     73 days           73
1  2016-02-29  2015-11-20    101 days          101
2  2016-03-31  2015-11-21    131 days          131
3  2016-04-30  2015-11-22    160 days          160
4  2016-05-31  2015-11-23    190 days          190
5  2016-06-30  2015-11-24    219 days          219
6         NaT  2015-11-25         NaT          NaN
7         NaT  2015-11-26         NaT          NaN
8  2016-01-31  2015-11-27     65 days           65
9         NaT  2015-11-28         NaT          NaN
10        NaT  2015-11-29         NaT          NaN
11        NaT  2015-11-30         NaT          NaN
12 2016-04-30  2015-12-01    151 days          151
13        NaT  2015-12-02         NaT          NaN
14        NaT  2015-12-03         NaT          NaN
15 2016-04-30  2015-12-04    148 days          148
16        NaT  2015-12-05         NaT          NaN
17        NaT  2015-12-06         NaT          NaN

Hope that helps.

How to update TypeScript to latest version with npm?

Use the command where in prompt to find the current executable in path

C:\> where tsc
C:\Users\user\AppData\Roaming\npm\tsc
C:\Users\user\AppData\Roaming\npm\tsc.cmd

NodeJs : TypeError: require(...) is not a function

I've faced to something like this too. in your routes file , export the function as an object like this :

 module.exports = {
     hbd: handlebar
 }

and in your app file , you can have access to the function by .hbd and there is no ptoblem ....!

Is There a Better Way of Checking Nil or Length == 0 of a String in Ruby?

In rails you can try #blank?.

Warning: it will give you positives when string consists of spaces:

nil.blank? # ==> true
''.blank? # ==> true
'  '.blank? # ==> true
'false'.blank? # ==> false

Just wanted to point it out. Maybe it suits your needs

UPD. why am i getting old questions in my feed? Sorry for necroposting.

How to include scripts located inside the node_modules folder?

As mentioned by jfriend00 you should not expose your server structure. You could copy your project dependency files to something like public/scripts. You can do this very easily with dep-linker like this:

var DepLinker = require('dep-linker');
DepLinker.copyDependenciesTo('./public/scripts')
// Done

AngularJS: Service vs provider vs factory

All the good answers already. I would like to add few more points on Service and Factory. Along with the difference between service/factory. And one can also have questions like:

  1. Should I use service or factory? What’s the difference?
  2. Is they do same or have same behaviour?

Lets start with the difference between Service and factory:

  1. Both are Singletons: Whenever Angular find these as a dependency first time,it create a single instance of service/factory. Once the instance is created, same instance is used forever.

  2. Can be used to model an object with behavior: They can both have methods, internal state variables, and so on. Though the way you write that code will differ.

Services:

A service is a constructor function, and Angular will instantiate it by calling new yourServiceName(). This means a couple of things.

  1. Functions and instance variables will be properties of this.
  2. You don’t need to return a value. When Angular calls new yourServiceName(), it’ll receive the this object with all the properties you put on it.

Sample Example:

angular.service('MyService', function() {
  this.aServiceVariable = "Ved Prakash"
  this.aServiceMethod = function() {
    return //code
  };
});

When Angular injects this MyService service into a controller that depends on it, that controller will get a MyService that it can call functions on, e.g. MyService.aServiceMethod ().

Be careful with this:

Since the constructed service is an object, the methods inside it can refer to this when they’re called:

angular.service('ScoreKeeper', function($http) {
  this.score = 0;

  this.getScore = function() {
    return this.score;
  };

  this.setScore = function(newScore) {
    this.score = newScore;
  };

  this.addOne = function() {
    this.score++;
  };
});

You might be tempted to call ScoreKeeper.setScore in a promise chain, for instance if you initialized the score by grabbing it from the server: $http.get('/score').then(ScoreKeeper.setScore). The trouble with this is that ScoreKeeper.setScore will be called with this bound to null and you’ll get errors. The better way would be $http.get('/score').then(ScoreKeeper.setScore.bind(ScoreKeeper)). Whether you choose to use this in your service methods or not, be careful how you call them.

Returning a Value from a Service:

Due to how JavaScript constructors work, if you return a complex value (i.e., an Object) from a constructor function, the caller will get that Object instead of the this instance.

This means that you can basically copy-paste the factory example from below, replace factory with service, and it’ll work:

angular.service('MyService', function($http) {
  var api = {};

  api.aServiceMethod= function() {
    return $http.get('/users');
  };
  return api;
});

So when Angular constructs your service with new MyService(), it’ll get that api object instead of the MyService instance.

This is the behavior for any complex values (objects, functions) but not for primitive types.

Factories:

A factory is a plain old function that returns a value. The return value is what gets injected into things that depend on the factory. A typical factory pattern in Angular is to return an object with functions as properties, like this:

angular.factory('MyFactory', function($http) {
  var api = {};

  api.aFactoryMethod= function() {
    return $http.get('/users');
  };

  return api;
});

The injected value for a factory dependency is the factory’s return value, and it doesn’t have to be an object. It could be a function

Answers for above 1 and 2 questions:

For the most part, just stick with using factories for everything. Their behavior is easier to understand. There’s no choice to make about whether to return a value or not, and furthermore, no bugs to be introduced if you do the wrong thing.

I still refer to them as “services” when I’m talking about injecting them as dependencies, though.

Service/Factory behavior is very similar, and some people will say that either one is fine. That’s somewhat true, but I find it easier to follow the advice of John Papa’s style guide and just stick with factories.**

what is Array.any? for javascript

I believe this to be the cleanest and readable option:

var empty = [];
empty.some(x => x); //returns false

An error occurred while signing: SignTool.exe not found

None of the answers above talk about disabling ClickOnce. In my situation, I never used ClickOnce for my applications but after I upgraded to VS 2015 it was suddenly enabled and I got the 'SignTool.exe not found' error when I tried to compile.

To disable you go into the properties of your Project (right click) and choose Security | Uncheck Enable ClickOnce security settings.

You can leave the manifest checked in the Signing tab because it has nothing to sign if it's been disabled.

I've confirmed that unchecking the security resolved the compile error on my projects.

How to create python bytes object from long hex string?

You can do this with the hex codec. ie:

>>> s='000000000000484240FA063DE5D0B744ADBED63A81FAEA390000C8428640A43D5005BD44'
>>> s.decode('hex')
'\x00\x00\x00\x00\x00\x00HB@\xfa\x06=\xe5\xd0\xb7D\xad\xbe\xd6:\x81\xfa\xea9\x00\x00\xc8B\x86@\xa4=P\x05\xbdD'

Stateless vs Stateful

I suggest that you start from a question in StackOverflow that discusses the advantages of stateless programming. This is more in the context of functional programming, but what you will read also applies in other programming paradigms.

Stateless programming is related to the mathematical notion of a function, which when called with the same arguments, always return the same results. This is a key concept of the functional programming paradigm and I expect that you will be able to find many relevant articles in that area.

Another area that you could research in order to gain more understanding is RESTful web services. These are by design "stateless", in contrast to other web technologies that try to somehow keep state. (In fact what you say that ASP.NET is stateless isn't correct - ASP.NET tries hard to keep state using ViewState and are definitely to be characterized as stateful. ASP.NET MVC on the other hand is a stateless technology). There are many places that discuss "statelessness" of RESTful web services (like this blog spot), but you could again start from an SO question.

How to add a changed file to an older (not last) commit in Git

You can try a rebase --interactive session to amend your old commit (provided you did not already push those commits to another repo).

Sometimes the thing fixed in b.2. cannot be amended to the not-quite perfect commit it fixes, because that commit is buried deeply in a patch series.
That is exactly what interactive rebase is for: use it after plenty of "a"s and "b"s, by rearranging and editing commits, and squashing multiple commits into one.

Start it with the last commit you want to retain as-is:

git rebase -i <after-this-commit>

An editor will be fired up with all the commits in your current branch (ignoring merge commits), which come after the given commit.
You can reorder the commits in this list to your heart's content, and you can remove them. The list looks more or less like this:

pick deadbee The oneline of this commit
pick fa1afe1 The oneline of the next commit
...

The oneline descriptions are purely for your pleasure; git rebase will not look at them but at the commit names ("deadbee" and "fa1afe1" in this example), so do not delete or edit the names.

By replacing the command "pick" with the command "edit", you can tell git rebase to stop after applying that commit, so that you can edit the files and/or the commit message, amend the commit, and continue rebasing.

How to fix Terminal not loading ~/.bashrc on OS X Lion

Terminal opens a login shell. This means, ~/.bash_profile will get executed, ~/.bashrc not.

The solution on most systems is to "require" the ~/.bashrc in the ~/.bash_profile: just put this snippet in your ~/.bash_profile:

[[ -s ~/.bashrc ]] && source ~/.bashrc

rsync: how can I configure it to create target directory on server?

Assuming you are using ssh to connect rsync, what about to send a ssh command before:

ssh user@server mkdir -p existingdir/newdir

if it already exists, nothing happens

Android: resizing imageview in XML

for example:

<ImageView android:id="@+id/image_view"     
  android:layout_width="wrap_content"  
  android:layout_height="wrap_content"  
  android:adjustViewBounds="true"  
  android:maxWidth="42dp"  
  android:maxHeight="42dp"  
  android:scaleType="fitCenter"  
  android:layout_marginLeft="3dp"  
  android:src="@drawable/icon"  
  /> 

Add property android:scaleType="fitCenter" and android:adjustViewBounds="true".

How do you setLayoutParams() for an ImageView?

An ImageView gets setLayoutParams from View which uses ViewGroup.LayoutParams. If you use that, it will crash in most cases so you should use getLayoutParams() which is in View.class. This will inherit the parent View of the ImageView and will work always. You can confirm this here: ImageView extends view

Assuming you have an ImageView defined as 'image_view' and the width/height int defined as 'thumb_size'

The best way to do this:

ViewGroup.LayoutParams iv_params_b = image_view.getLayoutParams();
iv_params_b.height = thumb_size;
iv_params_b.width = thumb_size;
image_view.setLayoutParams(iv_params_b);

React.createElement: type is invalid -- expected a string

Most of the time this is due to an incorrect export/import.

Common error:

// File: LeComponent.js
export class LeComponent extends React.Component { ... }

// File: App.js
import LeComponent from './LeComponent';

Possible option:

// File: LeComponent.js 
export default class LeComponent extends React.Component { ... }

// File: App.js
import LeComponent from './LeComponent';

There are a few ways it could be wrong, but that error is because of an import/export mismatch 60% of the time, everytime.

Edit

Typically you should get a stacktrace that indicates an approximate location of where the failure occurs. This generally follows straight after the message you have in your original question.

If it doesn't show, it might be worth investigating why (it might be a build setting that you're missing). Regardless, if it doesn't show, the only course of action is narrowing down where the export/import is failing.

Sadly, the only way to do it, without a stacktrace is to manually remove each module/submodule until you don't get the error anymore, then work your way back up the stack.

Edit 2

Via comments, it was indeed an import issue, specifically importing a module that didn't exist

Eclipse - debugger doesn't stop at breakpoint

This is what works for me:

I had to put my local server address in the PHP Server configuration like this:

enter image description here

Note: that address, is the one I configure in my Apache .conf file.

Note: the only breakpoint that was working was the 'Break at first line', after that, the breakpoints didn't work.

Note: check your xdebug properties in your php.ini file, and remove any you think is not required.

How to make an element in XML schema optional?

Try this

<xs:element name="description" type="xs:string" minOccurs="0" maxOccurs="1" />

if you want 0 or 1 "description" elements, Or

<xs:element name="description" type="xs:string" minOccurs="0" maxOccurs="unbounded" />

if you want 0 to infinity number of "description" elements.

Height of status bar in Android

Since multi-window mode is available now, your app may not have statusbar on top.

Following solution handle all the cases automatically for you.

android:fitsSystemWindows="true"

or programatically

findViewById(R.id.your_root_view).setFitsSystemWindows(true);

you may also get root view by

findViewById(android.R.id.content).getRootView();
or
getWindow().getDecorView().findViewById(android.R.id.content)

For more details on getting root-view refer - https://stackoverflow.com/a/4488149/9640177

MySQL 'Order By' - sorting alphanumeric correctly

I hate this, but this will work

order by lpad(name, 10, 0)  <-- assuming maximum string length is 10
                            <-- you can adjust to a bigger length if you want to

javascript popup alert on link click

In order to do this you need to attach the handler to a specific anchor on the page. For operations like this it's much easier to use a standard framework like jQuery. For example if I had the following HTML

HTML:

<a id="theLink">Click Me</a>

I could use the following jQuery to hookup an event to that specific link.

// Use ready to ensure document is loaded before running javascript
$(document).ready(function() {

  // The '#theLink' portion is a selector which matches a DOM element
  // with the id 'theLink' and .click registers a call back for the 
  // element being clicked on 
  $('#theLink').click(function (event) {

    // This stops the link from actually being followed which is the 
    // default action 
    event.preventDefault();

    var answer confirm("Please click OK to continue");
    if (!answer) {
      window.location="http://www.continue.com"
    }
  });

});

JSON formatter in C#?

The main reason of writing your own function is that JSON frameworks usually perform parsing of strings into .net types and converting them back to string, which may result in losing original strings. For example 0.0002 becomes 2E-4

I do not post my function (it's pretty same as other here) but here are the test cases

using System.IO;

using Newtonsoft.Json;

using NUnit.Framework;

namespace json_formatter.tests
{
    [TestFixture]
    internal class FormatterTests
    {
        [Test]
        public void CompareWithNewtonsofJson()
        {
            string file = Path.Combine(TestContext.CurrentContext.TestDirectory, "json", "minified.txt");

            string json = File.ReadAllText(file);

            string newton = JsonPrettify(json);
            // Double space are indent symbols which newtonsoft framework uses
            string my = new Formatter("  ").Format(json);

            Assert.AreEqual(newton, my);
        }

        [Test]
        public void EmptyArrayMustNotBeFormatted()
        {
            var input = "{\"na{me\": []}";
            var expected = "{\r\n\t\"na{me\": []\r\n}";

            Assert.AreEqual(expected, new Formatter().Format(input));
        }

        [Test]
        public void EmptyObjectMustNotBeFormatted()
        {
            var input = "{\"na{me\": {}}";
            var expected = "{\r\n\t\"na{me\": {}\r\n}";

            Assert.AreEqual(expected, new Formatter().Format(input));
        }

        [Test]
        public void MustAddLinebreakAfterBraces()
        {
            var input = "{\"name\": \"value\"}";
            var expected = "{\r\n\t\"name\": \"value\"\r\n}";

            Assert.AreEqual(expected, new Formatter().Format(input));
        }

        [Test]
        public void MustFormatNestedObject()
        {
            var input = "{\"na{me\":\"val}ue\", \"name1\": {\"name2\":\"value\"}}";
            var expected = "{\r\n\t\"na{me\": \"val}ue\",\r\n\t\"name1\": {\r\n\t\t\"name2\": \"value\"\r\n\t}\r\n}";

            Assert.AreEqual(expected, new Formatter().Format(input));
        }

        [Test]
        public void MustHandleArray()
        {
            var input = "{\"name\": \"value\", \"name2\":[\"a\", \"b\", \"c\"]}";
            var expected = "{\r\n\t\"name\": \"value\",\r\n\t\"name2\": [\r\n\t\t\"a\",\r\n\t\t\"b\",\r\n\t\t\"c\"\r\n\t]\r\n}";
            Assert.AreEqual(expected, new Formatter().Format(input));
        }

        [Test]
        public void MustHandleArrayOfObject()
        {
            var input = "{\"name\": \"value\", \"name2\":[{\"na{me\":\"val}ue\"}, {\"nam\\\"e2\":\"val\\\\\\\"ue\"}]}";
            var expected =
                "{\r\n\t\"name\": \"value\",\r\n\t\"name2\": [\r\n\t\t{\r\n\t\t\t\"na{me\": \"val}ue\"\r\n\t\t},\r\n\t\t{\r\n\t\t\t\"nam\\\"e2\": \"val\\\\\\\"ue\"\r\n\t\t}\r\n\t]\r\n}";
            Assert.AreEqual(expected, new Formatter().Format(input));
        }

        [Test]
        public void MustHandleEscapedString()
        {
            var input = "{\"na{me\":\"val}ue\", \"name1\": {\"nam\\\"e2\":\"val\\\\\\\"ue\"}}";
            var expected = "{\r\n\t\"na{me\": \"val}ue\",\r\n\t\"name1\": {\r\n\t\t\"nam\\\"e2\": \"val\\\\\\\"ue\"\r\n\t}\r\n}";
            Assert.AreEqual(expected, new Formatter().Format(input));
        }

        [Test]
        public void MustIgnoreEscapedQuotesInsideString()
        {
            var input = "{\"na{me\\\"\": \"val}ue\"}";
            var expected = "{\r\n\t\"na{me\\\"\": \"val}ue\"\r\n}";

            Assert.AreEqual(expected, new Formatter().Format(input));
        }

        [TestCase(" ")]
        [TestCase("\"")]
        [TestCase("{")]
        [TestCase("}")]
        [TestCase("[")]
        [TestCase("]")]
        [TestCase(":")]
        [TestCase(",")]
        public void MustIgnoreSpecialSymbolsInsideString(string symbol)
        {
            string input = "{\"na" + symbol + "me\": \"val" + symbol + "ue\"}";
            string expected = "{\r\n\t\"na" + symbol + "me\": \"val" + symbol + "ue\"\r\n}";

            Assert.AreEqual(expected, new Formatter().Format(input));
        }

        [Test]
        public void StringEndsWithEscapedBackslash()
        {
            var input = "{\"na{me\\\\\": \"val}ue\"}";
            var expected = "{\r\n\t\"na{me\\\\\": \"val}ue\"\r\n}";

            Assert.AreEqual(expected, new Formatter().Format(input));
        }

        private static string PrettifyUsingNewtosoft(string json)
        {
            using (var stringReader = new StringReader(json))
            using (var stringWriter = new StringWriter())
            {
                var jsonReader = new JsonTextReader(stringReader);
                var jsonWriter = new JsonTextWriter(stringWriter)
                                {
                                    Formatting = Formatting.Indented
                                };
                jsonWriter.WriteToken(jsonReader);
                return stringWriter.ToString();
            }
        }
    }
}

How do I use valgrind to find memory leaks?

You can create an alias in .bashrc file as follows

alias vg='valgrind --leak-check=full -v --track-origins=yes --log-file=vg_logfile.out'

So whenever you want to check memory leaks, just do simply

vg ./<name of your executable> <command line parameters to your executable>

This will generate a Valgrind log file in the current directory.

Array of Matrices in MATLAB

Use cell arrays. This has an advantage over 3D arrays in that it does not require a contiguous memory space to store all the matrices. In fact, each matrix can be stored in a different space in memory, which will save you from Out-of-Memory errors if your free memory is fragmented. Here is a sample function to create your matrices in a cell array:

function result = createArrays(nArrays, arraySize)
    result = cell(1, nArrays);
    for i = 1 : nArrays
        result{i} = zeros(arraySize);
    end
end

To use it:

myArray = createArrays(requiredNumberOfArrays, [500 800]);

And to access your elements:

myArray{1}(2,3) = 10;

If you can't know the number of matrices in advance, you could simply use MATLAB's dynamic indexing to make the array as large as you need. The performance overhead will be proportional to the size of the cell array, and is not affected by the size of the matrices themselves. For example:

myArray{1} = zeros(500, 800);
if twoRequired, myArray{2} = zeros(500, 800); end

How to write a simple Java program that finds the greatest common divisor between two numbers?

import java.util.Scanner;

class CalculateGCD 
{   
  public static int calGCD(int a, int b) 
  { 
   int c=0,d=0;  
   if(a>b){c=b;} 
   else{c=a;}  
   for(int i=c; i>0; i--) 
   { 
    if(((a%i)+(b%i))==0) 
    { 
     d=i; 
     break; 
    } 
   } 
   return d;  
  }  

  public static void main(String args[]) 
  { 
   Scanner sc=new Scanner(System.in); 
   System.out.println("Enter the nos whose GCD is to be calculated:"); 
   int a=sc.nextInt(); 
   int b=sc.nextInt(); 
   System.out.println(calGCD(a,b));  
  } 
 } 

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

h2.myClass refers to all h2 with class="myClass".

.myClass h2 refers to all h2 that are children of (i.e. nested in) elements with class="myClass".

If you want the h2 in your HTML to appear blue, change the CSS to the following:

.myClass h2 {
    color: blue;
}

If you want to be able to reference that h2 by a class rather than its tag, you should leave the CSS as it is and give the h2 a class in the HTML:

<h2 class="myClass">This header should be BLUE to match the element.class selector</h2>

How can I produce an effect similar to the iOS 7 blur view?

You can find your solution from apple's DEMO in this page: WWDC 2013 , find out and download UIImageEffects sample code.

Then with @Jeremy Fox's code. I changed it to

- (UIImage*)getDarkBlurredImageWithTargetView:(UIView *)targetView
{
    CGSize size = targetView.frame.size;

    UIGraphicsBeginImageContext(size);
    CGContextRef c = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(c, 0, 0);
    [targetView.layer renderInContext:c]; // view is the view you are grabbing the screen shot of. The view that is to be blurred.
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return [image applyDarkEffect];
}

Hope this will help you.

moving committed (but not pushed) changes to a new branch after pull

A simpler approach, which I have been using (assuming you want to move 4 commits):

git format-patch HEAD~4

(Look in the directory from which you executed the last command for the 4 .patch files)

git reset HEAD~4 --hard

git checkout -b tmp/my-new-branch

Then:

git apply /path/to/patch.patch

In whatever order you wanted.

How to determine the first and last iteration in a foreach loop?

Using reset($array) and end($array)

<?php

    $arrays = [1,2,3,4,5];

    $first  = reset($arrays);
    $last   = end($arrays);    

    foreach( $arrays as $array )
    {

        if ( $first == $array )
        {
            echo "<li>{$array} first</li>";
        }
        else if ( $last == $array )
        {
            echo "<li>{$array} last</li>";
        }
        else
        {
            echo "<li>{$array}</li>";
        }                

    }

Demo repl.it

C++: variable 'std::ifstream ifs' has initializer but incomplete type

This seems to be answered - #include <fstream>.

The message means :-

incomplete type - the class has not been defined with a full class. The compiler has seen statements such as class ifstream; which allow it to understand that a class exists, but does not know how much memory the class takes up.

The forward declaration allows the compiler to make more sense of :-

void BindInput( ifstream & inputChannel ); 

It understands the class exists, and can send pointers and references through code without being able to create the class, see any data within the class, or call any methods of the class.

The has initializer seems a bit extraneous, but is saying that the incomplete object is being created.

Extract filename and extension in Bash

From the answers above, the shortest oneliner to mimic Python's

file, ext = os.path.splitext(path)

presuming your file really does have an extension, is

EXT="${PATH##*.}"; FILE=$(basename "$PATH" .$EXT)

Get month and year from date cells Excel

I had a requirement to provide a report showing details by month where the date field was formatted as date & time, I simply changed the formatting of the date column to "General" and then used the following formula in a new column,

=CONCATENATE(YEAR(C2),MONTH(C2)) 

Jquery find nearest matching element

Get the .column parent of the this element, get its previous sibling, then find any input there:

$(this).closest(".column").prev().find("input:first").val();

Demo: http://jsfiddle.net/aWhtP/

Are there other whitespace codes like &nbsp for half-spaces, em-spaces, en-spaces etc useful in HTML?

There are codes for other space characters, and the codes as such work well, but the characters themselves are legacy character. They have been included into character sets only due to their presence in existing character data, rather than for use in new documents. For some combinations of font and browser version, they may cause a generic glyph of unrepresentable character to be shown. For details, check my page about Unicode spaces.

So using CSS is safer and lets you specify any desired amount of spacing, not just the specific widths of fixed-width spaces. If you just want to have added spacing around your h2 elements, as it seems to me, then setting padding on those elements (changing the value of the padding: 0 settings that you already have) should work fine.

Python DNS module import error

I was getting an error while using "import dns.resolver". I tried dnspython, py3dns but they failed. dns won't install. after much hit and try I installed pubdns module and it solved my problem.

How to list all the files in android phone by using adb shell?

I might be wrong but "find -name __" works fine for me. (Maybe it's just my phone.) If you just want to list all files, you can try

adb shell ls -R /

You probably need the root permission though.

Edit: As other answers suggest, use ls with grep like this:

adb shell ls -Ral yourDirectory | grep -i yourString

eg.

adb shell ls -Ral / | grep -i myfile

-i is for ignore-case. and / is the root directory.

What's the difference between a temp table and table variable in SQL Server?

Differences between Temporary Tables (##temp/#temp) and Table Variables (@table) are as:

  1. Table variable (@table) is created in the memory. Whereas, a Temporary table (##temp/#temp) is created in the tempdb database. However, if there is a memory pressure the pages belonging to a table variable may be pushed to tempdb.

  2. Table variables cannot be involved in transactions, logging or locking. This makes @table faster then #temp. So table variable is faster then temporary table.

  3. Temporary table allows Schema modifications unlike Table variables.

  4. Temporary tables are visible in the created routine and also in the child routines. Whereas, Table variables are only visible in the created routine.

  5. Temporary tables are allowed CREATE INDEXes whereas, Table variables aren’t allowed CREATE INDEX instead they can have index by using Primary Key or Unique Constraint.

How is TeamViewer so fast?

would take time to route through TeamViewer's servers (TeamViewer bypasses corporate Symmetric NATs by simply proxying traffic through their servers)

You'll find that TeamViewer rarely needs to relay traffic through their own servers. TeamViewer penetrates NAT and networks complicated by NAT using NAT traversal (I think it is UDP hole-punching, like Google's libjingle).

They do use their own servers to middle-man in order to do the handshake and connection set-up, but most of the time the relationship between client and server will be P2P (best case, when the hand-shake is successful). If NAT traversal fails, then TeamViewer will indeed relay traffic through its own servers.

I've only ever seen it do this when a client has been behind double-NAT, though.

How can I read and manipulate CSV file data in C++?

More information would be useful.

But the simplest form:

#include <iostream>
#include <sstream>
#include <fstream>
#include <string>

int main()
{
    std::ifstream  data("plop.csv");

    std::string line;
    while(std::getline(data,line))
    {
        std::stringstream  lineStream(line);
        std::string        cell;
        while(std::getline(lineStream,cell,','))
        {
            // You have a cell!!!!
        }
    }
 }

Also see this question: CSV parser in C++

How do I install a Python package with a .whl file?

I would be suggesting you the exact way how to install .whl file. Initially I faced many issues but then I solved it, Here is my trick to install .whl files.

Follow The Steps properly in order to get a module imported

  1. Make sure your .whl file is kept in the python 2.7/3.6/3.7/.. folder. Initially when you download the .whl file the file is kept in downloaded folder, my suggestion is to change the folder. It makes it easier to install the file.
  2. Open command prompt and open the folder where you have kept the file by entering

cd c:\python 3.7

3.Now, enter the command written below

>py -3.7(version name) -m pip install (file name).whl
  1. Click enter and make sure you enter the version you are currently using with correct file name.

  2. Once you press enter, wait for few minutes and the file will be installed and you will be able to import the particular module.

  3. In order to check if the module is installed successfully, import the module in idle and check it.

Thank you:)

Pythonically add header to a csv file

You just add one additional row before you execute the loop. This row contains your CSV file header name.

schema = ['a','b','c','b']
row = 4
generators = ['A','B','C','D']
with open('test.csv','wb') as csvfile:    
     writer = csv.writer(csvfile, delimiter=delimiter)
# Gives the header name row into csv
     writer.writerow([g for g in schema])   
#Data add in csv file       
     for x in xrange(rows):
         writer.writerow([g() for g in generators])

Python: Continuing to next iteration in outer loop

I think you could do something like this:

for ii in range(200):
    restart = False
    for jj in range(200, 400):
        ...block0...
        if something:
            restart = True
            break
    if restart:
        continue
    ...block1...

Why can I not switch branches?

If you don't care about the changes that git says are outstanding, then you can do a force checkout.

git checkout -f {{insert your branch name here}}

Is string in array?

You can also use LINQ to iterate over the array. or you can use the Find method which takes a delegate to search for it. However I think the find method is a bit more expensive then just looping through.

Plain Old CLR Object vs Data Transfer Object

I think a DTO can be a POCO. DTO is more about the usage of the object while POCO is more of the style of the object (decoupled from architectural concepts).

One example where a POCO is something different than DTO is when you're talking about POCO's inside your domain model/business logic model, which is a nice OO representation of your problem domain. You could use the POCO's throughout the whole application, but this could have some undesirable side effect such a knowledge leaks. DTO's are for instance used from the Service Layer which the UI communicates with, the DTO's are flat representation of the data, and are only used for providing the UI with data, and communicating changes back to the service layer. The service layer is in charge of mapping the DTO's both ways to the POCO domain objects.

Update Martin Fowler said that this approach is a heavy road to take, and should only be taken if there is a significant mismatch between the domain layer and the user interface.

$(window).scrollTop() vs. $(document).scrollTop()

Cross browser way of doing this is

var top = ($(window).scrollTop() || $("body").scrollTop());

How to go to each directory and execute a command?

If the toplevel folder is known you can just write something like this:

for dir in `ls $YOUR_TOP_LEVEL_FOLDER`;
do
    for subdir in `ls $YOUR_TOP_LEVEL_FOLDER/$dir`;
    do
      $(PLAY AS MUCH AS YOU WANT);
    done
done

On the $(PLAY AS MUCH AS YOU WANT); you can put as much code as you want.

Note that I didn't "cd" on any directory.

Cheers,

How to install JSON.NET using NuGet?

You can do this a couple of ways.

Via the "Solution Explorer"

  1. Simply right-click the "References" folder and select "Manage NuGet Packages..."
  2. Once that window comes up click on the option labeled "Online" in the left most part of the dialog.
  3. Then in the search bar in the upper right type "json.net"
  4. Click "Install" and you're done.

Via the "Package Manager Console"

  1. Open the console. "View" > "Other Windows" > "Package Manager Console"
  2. Then type the following:
    Install-Package Newtonsoft.Json

For more info on how to use the "Package Manager Console" check out the nuget docs.

What's the location of the JavaFX runtime JAR file, jfxrt.jar, on Linux?

The location of jfxrt.jar in Oracle Java 7 is:

<JRE_HOME>/lib/jfxrt.jar

The location of jfxrt.jar in Oracle Java 8 is:

<JRE_HOME>/lib/ext/jfxrt.jar

The <JRE_HOME> will depend on where you installed the Oracle Java and may differ between Linux distributions and installations.

jfxrt.jar is not in the Linux OpenJDK 7 (which is what you are using).


An open source package which provides JavaFX 8 for Debian based systems such as Ubuntu is available. To install this package it is necessary to install both the Debian OpenJDK 8 package and the Debian OpenJFX package. I don't run Debian, so I'm not sure where the Debian OpenJFX package installs jfxrt.jar.


Use Oracle Java 8.

With Oracle Java 8, JavaFX is both included in the JDK and is on the default classpath. This means that JavaFX classes will automatically be found both by the compiler during the build and by the runtime when your users use your application. So using Oracle Java 8 is currently the best solution to your issue.

OpenJDK for Java 8 could include JavaFX (as JavaFX for Java 8 is now open source), but it will depend on the OpenJDK package assemblers as to whether they choose to include JavaFX 8 with their distributions. I hope they do, as it should help remove the confusion you experienced in your question and it also provides a great deal more functionality in OpenJDK.

My understanding is that although JavaFX has been included with the standard JDK since version JDK 7u6

Yes, but only the Oracle JDK.

The JavaFX version bundled with Java 7 was not completely open source so it could not be included in the OpenJDK (which is what you are using).

In you need to use Java 7 instead of Java 8, you could download the Oracle JDK for Java 7 and use that. Then JavaFX will be included with Java 7. Due to the way Oracle configured Java 7, JavaFX won't be on the classpath. If you use Java 7, you will need to add it to your classpath and use appropriate JavaFX packaging tools to allow your users to run your application. Some tools such as e(fx)clipse and NetBeans JavaFX project type will take care of classpath issues and packaging tasks for you.

iterating through Enumeration of hastable keys throws NoSuchElementException error

Every time you call e.nextElement() you take the next object from the iterator. You have to check e.hasMoreElement() between each call.


Example:

while(e.hasMoreElements()){
    String param = e.nextElement();
    System.out.println(param);
}

How to have EditText with border in Android Lollipop

You can do it using xml.

Create an xml layout and name it like my_edit_text_border.xml

 <?xml version="1.0" encoding="utf-8"?>
 <selector xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="#ffffff"/>
            <corners android:radius="5dp" />
            <stroke
                android:width="2dp"
                android:color="#949494"
                />
        </shape>
    </item>
</selector>

Add background to your Edittext

<EditText
 android:id="@+id/editText1"
 ..
 android:background="@layout/my_edit_text_border">