Programs & Examples On #Basecamp

Basecamp is a web-based project-management tool developed by 37signals and launched in 2004. The Ruby on Rails framework was extracted from the Basecamp project. Basecamp has a "classic" and a "new" version.

INSERT INTO from two different server database

It sounds like you might need to create and query linked database servers in SQL Server

At the moment you've created a query that's going between different databases using a 3 part name mydatabase.dbo.mytable but you need to go up a level and use a 4 part name myserver.mydatabase.dbo.mytable, see this post on four part naming for more info

edit
The four part naming for your existing query would be as shown below (which I suspect you may have already tried?), but this assumes you can "get to" the remote database with the four part name, you might need to edit your host file / register the server or otherwise identify where to find database.windows.net.

INSERT INTO [DATABASE.WINDOWS.NET].[basecampdev].[dbo].[invoice]
       ([InvoiceNumber]
       ,[TotalAmount]
       ,[IsActive]
       ,[CreatedBy]
       ,[UpdatedBy]
       ,[CreatedDate]
       ,[UpdatedDate]
       ,[Remarks])
SELECT [InvoiceNumber]
       ,[TotalAmount]
       ,[IsActive]
       ,[CreatedBy]
       ,[UpdatedBy]
       ,[CreatedDate]
       ,[UpdatedDate]
       ,[Remarks] FROM [BC1-PC].[testdabse].[dbo].[invoice]

If you can't access the remote server then see if you can create a linked database server:

EXEC sp_addlinkedserver [database.windows.net];
GO
USE tempdb;
GO
CREATE SYNONYM MyInvoice FOR 
    [database.windows.net].basecampdev.dbo.invoice;
GO

Then you can just query against MyEmployee without needing the full four part name

html select option separator

we can make use of optgroup tag without options

  • can set the font-size:1px to minimize the height, and
  • some pretty background for it

_x000D_
_x000D_
.divider {
  font-size: 1px;
  background: rgba(0, 0, 0, 0.5);
}

.divider--danger {
  background: red;
}
_x000D_
<select>
  <option value="option1">option 1 key data</option>
  <option value="option2">option 2 key data</option>
  <optgroup class="divider"></optgroup>
  <option value="option3">option 3 key data</option>
  <option value="option4">option 4 key data</option>
</select>

<select>
  <option value="option1">option 1 key data</option>
  <option value="option2">option 2 key data</option>
  <optgroup class="divider divider--danger"></optgroup>
  <option value="option3">option 3 key data</option>
  <option value="option4">option 4 key data</option>
</select>
_x000D_
_x000D_
_x000D_

Codepen.io: https://codepen.io/JasneetDua/pen/yLOYwaV?editors=1100

Extract the last substring from a cell

Right(A1, Len(A1)-Find("(asterisk)",Substitute(A1, "(space)","(asterisk)",Len(A1)-Len(Substitute(A1,"(space)", "(no space)")))))

Try this. Hope it works.

What methods of ‘clearfix’ can I use?

You could also put this in your CSS:

.cb:after{
  visibility: hidden;
  display: block;
  content: ".";
  clear: both;
  height: 0;
}

*:first-child+html .cb{zoom: 1} /* for IE7 */

And add class "cb" to your parent div:

<div id="container" class="cb">

You will not need to add anything else to your original code...

Android image caching

What actually worked for me was setting ResponseCache on my Main class:

try {
   File httpCacheDir = new File(getApplicationContext().getCacheDir(), "http");
   long httpCacheSize = 10 * 1024 * 1024; // 10 MiB
   HttpResponseCache.install(httpCacheDir, httpCacheSize);
} catch (IOException e) { } 

and

connection.setUseCaches(true);

when downloading bitmap.

http://practicaldroid.blogspot.com/2013/01/utilizing-http-response-cache.html

How to Create a script via batch file that will uninstall a program if it was installed on windows 7 64-bit or 32-bit

Assuming you're dealing with Windows 7 x64 and something that was previously installed with some sort of an installer, you can open regedit and search the keys under

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall

(which references 32-bit programs) for part of the name of the program, or

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall

(if it actually was a 64-bit program).

If you find something that matches your program in one of those, the contents of UninstallString in that key usually give you the exact command you are looking for (that you can run in a script).

If you don't find anything relevant in those registry locations, then it may have been "installed" by unzipping a file. Because you mentioned removing it by the Control Panel, I gather this likely isn't then case; if it's in the list of programs there, it should be in one of the registry keys I mentioned.

Then in a .bat script you can do

if exist "c:\program files\whatever\program.exe" (place UninstallString contents here)
if exist "c:\program files (x86)\whatever\program.exe" (place UninstallString contents here)

What is the difference between pull and clone in git?

git clone URL ---> Complete project or repository will be downloaded as a seperate directory. and not just the changes git pull URL ---> fetch + merge --> It will only fetch the changes that have been done and not the entire project

Changing the git user inside Visual Studio Code

Press Ctrl + Shift + G in Visual Studio Code and go to more and select Show git output. Click Terminal and type git remote -v and verify that the origin branch has latest username in it like:

origin [email protected]:DroidPulkit/Facebook-Chat-Bot.git (fetch)

origin [email protected]:DroidPulkit/Facebook-Chat-Bot.git (push)

Here DroidPulkit is my username.

If the username is not what you wanted it to be then change it with:

git add remote origin [email protected]:newUserName/RepoName.git

How does PHP 'foreach' actually work?

Great question, because many developers, even experienced ones, are confused by the way PHP handles arrays in foreach loops. In the standard foreach loop, PHP makes a copy of the array that is used in the loop. The copy is discarded immediately after the loop finishes. This is transparent in the operation of a simple foreach loop. For example:

$set = array("apple", "banana", "coconut");
foreach ( $set AS $item ) {
    echo "{$item}\n";
}

This outputs:

apple
banana
coconut

So the copy is created but the developer doesn't notice, because the original array isn’t referenced within the loop or after the loop finishes. However, when you attempt to modify the items in a loop, you find that they are unmodified when you finish:

$set = array("apple", "banana", "coconut");
foreach ( $set AS $item ) {
    $item = strrev ($item);
}

print_r($set);

This outputs:

Array
(
    [0] => apple
    [1] => banana
    [2] => coconut
)

Any changes from the original can't be notices, actually there are no changes from the original, even though you clearly assigned a value to $item. This is because you are operating on $item as it appears in the copy of $set being worked on. You can override this by grabbing $item by reference, like so:

$set = array("apple", "banana", "coconut");
foreach ( $set AS &$item ) {
    $item = strrev($item);
}
print_r($set);

This outputs:

Array
(
    [0] => elppa
    [1] => ananab
    [2] => tunococ
)

So it is evident and observable, when $item is operated on by-reference, the changes made to $item are made to the members of the original $set. Using $item by reference also prevents PHP from creating the array copy. To test this, first we’ll show a quick script demonstrating the copy:

$set = array("apple", "banana", "coconut");
foreach ( $set AS $item ) {
    $set[] = ucfirst($item);
}
print_r($set);

This outputs:

Array
(
    [0] => apple
    [1] => banana
    [2] => coconut
    [3] => Apple
    [4] => Banana
    [5] => Coconut
)

As it is shown in the example, PHP copied $set and used it to loop over, but when $set was used inside the loop, PHP added the variables to the original array, not the copied array. Basically, PHP is only using the copied array for the execution of the loop and the assignment of $item. Because of this, the loop above only executes 3 times, and each time it appends another value to the end of the original $set, leaving the original $set with 6 elements, but never entering an infinite loop.

However, what if we had used $item by reference, as I mentioned before? A single character added to the above test:

$set = array("apple", "banana", "coconut");
foreach ( $set AS &$item ) {
    $set[] = ucfirst($item);
}
print_r($set);

Results in an infinite loop. Note this actually is an infinite loop, you’ll have to either kill the script yourself or wait for your OS to run out of memory. I added the following line to my script so PHP would run out of memory very quickly, I suggest you do the same if you’re going to be running these infinite loop tests:

ini_set("memory_limit","1M");

So in this previous example with the infinite loop, we see the reason why PHP was written to create a copy of the array to loop over. When a copy is created and used only by the structure of the loop construct itself, the array stays static throughout the execution of the loop, so you’ll never run into issues.

How do I modify a MySQL column to allow NULL?

Use: ALTER TABLE mytable MODIFY mycolumn VARCHAR(255);

How to parse a query string into a NameValueCollection in .NET

Since everyone seems to be pasting his solution.. here's mine :-) I needed this from within a class library without System.Web to fetch id parameters from stored hyperlinks.

Thought I'd share because I find this solution faster and better looking.

public static class Statics
    public static Dictionary<string, string> QueryParse(string url)
    {
        Dictionary<string, string> qDict = new Dictionary<string, string>();
        foreach (string qPair in url.Substring(url.IndexOf('?') + 1).Split('&'))
        {
            string[] qVal = qPair.Split('=');
            qDict.Add(qVal[0], Uri.UnescapeDataString(qVal[1]));
        }
        return qDict;
    }

    public static string QueryGet(string url, string param)
    {
        var qDict = QueryParse(url);
        return qDict[param];
    }
}

Usage:

Statics.QueryGet(url, "id")

node.js - request - How to "emitter.setMaxListeners()"?

It also happened to me

I use this code and it worked

require('events').EventEmitter.defaultMaxListeners = infinity;

Try it out. It may help

Thanks

Map with Key as String and Value as List in Groovy

def map = [:]
map["stringKey"] = [1, 2, 3, 4]
map["anotherKey"] = [55, 66, 77]

assert map["anotherKey"] == [55, 66, 77] 

Java String.split() Regex

    String str = "a + b - c * d / e < f > g >= h <= i == j";
    String reg = "\\s*[a-zA-Z]+";

    String[] res = str.split(reg);
    for (String out : res) {
        if (!"".equals(out)) {
            System.out.print(out);
        }
    }

Output : + - * / < > >= <= ==

How do I convert a float number to a whole number in JavaScript?

var intvalue = Math.floor( floatvalue );
var intvalue = Math.ceil( floatvalue ); 
var intvalue = Math.round( floatvalue );

// `Math.trunc` was added in ECMAScript 6
var intvalue = Math.trunc( floatvalue );

Math object reference


Examples

Positive
// value=x        //  x=5          5<x<5.5      5.5<=x<6  

Math.floor(value) //  5            5            5
Math.ceil(value)  //  5            6            6
Math.round(value) //  5            5            6
Math.trunc(value) //  5            5            5
parseInt(value)   //  5            5            5
~~value           //  5            5            5
value | 0         //  5            5            5
value >> 0        //  5            5            5
value >>> 0       //  5            5            5
value - value % 1 //  5            5            5
Negative
// value=x        // x=-5         -5>x>=-5.5   -5.5>x>-6

Math.floor(value) // -5           -6           -6
Math.ceil(value)  // -5           -5           -5
Math.round(value) // -5           -5           -6
Math.trunc(value) // -5           -5           -5
parseInt(value)   // -5           -5           -5
value | 0         // -5           -5           -5
~~value           // -5           -5           -5
value >> 0        // -5           -5           -5
value >>> 0       // 4294967291   4294967291   4294967291
value - value % 1 // -5           -5           -5
Positive - Larger numbers
// x = Number.MAX_SAFE_INTEGER/10 // =900719925474099.1

// value=x            x=900719925474099    x=900719925474099.4  x=900719925474099.5
           
Math.floor(value) //  900719925474099      900719925474099      900719925474099
Math.ceil(value)  //  900719925474099      900719925474100      900719925474100
Math.round(value) //  900719925474099      900719925474099      900719925474100
Math.trunc(value) //  900719925474099      900719925474099      900719925474099
parseInt(value)   //  900719925474099      900719925474099      900719925474099
value | 0         //  858993459            858993459            858993459
~~value           //  858993459            858993459            858993459
value >> 0        //  858993459            858993459            858993459
value >>> 0       //  858993459            858993459            858993459
value - value % 1 //  900719925474099      900719925474099      900719925474099
Negative - Larger numbers
// x = Number.MAX_SAFE_INTEGER/10 * -1 // -900719925474099.1

// value = x      // x=-900719925474099   x=-900719925474099.5 x=-900719925474099.6

Math.floor(value) // -900719925474099     -900719925474100     -900719925474100
Math.ceil(value)  // -900719925474099     -900719925474099     -900719925474099
Math.round(value) // -900719925474099     -900719925474099     -900719925474100
Math.trunc(value) // -900719925474099     -900719925474099     -900719925474099
parseInt(value)   // -900719925474099     -900719925474099     -900719925474099
value | 0         // -858993459           -858993459           -858993459
~~value           // -858993459           -858993459           -858993459
value >> 0        // -858993459           -858993459           -858993459
value >>> 0       //  3435973837           3435973837           3435973837
value - value % 1 // -900719925474099     -900719925474099     -900719925474099

MySQL compare now() (only date, not time) with a datetime field

Use DATE(NOW()) to compare dates

DATE(NOW()) will give you the date part of current date and DATE(duedate) will give you the date part of the due date. then you can easily compare the dates

So you can compare it like

DATE(NOW()) = DATE(duedate)

OR

DATE(duedate) = CURDATE() 

See here

Override element.style using CSS

As per my knowledge Inline sytle comes first so css class should not work.

Use Jquery as

$(document).ready(function(){

   $("#demoFour li").css("display","inline");
  });

You can also try 

#demoFour li { display:inline !important;}

css with background image without repeating the image

Instead of

background-repeat-x: no-repeat;
background-repeat-y: no-repeat;

which is not correct, use

background-repeat: no-repeat;

SQL Server: Query fast, but slow from procedure

Have you tried rebuilding the statistics and/or the indexes on the Report_Opener table. All the recomplies of the SP won't be worth anything if the stats still show data from when the database was first inauguarated.

The initial query itself works quickly because the optimiser can see that the parameter will never be null. In the case of the SP the optimiser cannot be sure that the parameter will never be null.

How to implement "Access-Control-Allow-Origin" header in asp.net

Configuring the CORS response headers on the server wasn't really an option. You should configure a proxy in client side.

Sample to Angular - So, I created a proxy.conf.json file to act as a proxy server. Below is my proxy.conf.json file:

{
  "/api": {
    "target": "http://localhost:49389",
    "secure": true,
    "pathRewrite": {
      "^/api": "/api"
    },
    "changeOrigin": true
  }
}

Put the file in the same directory the package.json then I modified the start command in the package.json file like below

"start": "ng serve --proxy-config proxy.conf.json"

now, the http call from the app component is as follows:

return this.http.get('/api/customers').map((res: Response) => res.json());

Lastly to run use npm start or ng serve --proxy-config proxy.conf.json

How to safely upgrade an Amazon EC2 instance from t1.micro to large?

Create AMI -> Boot AMI on large instance.

More info http://docs.amazonwebservices.com/AmazonEC2/gsg/2006-06-26/creating-an-image.html

You can do this all from the admin console too at aws.amazon.com

Mobile overflow:scroll and overflow-scrolling: touch // prevent viewport "bounce"

This answer seems quite outdated and not adapt for nowadays single page applications. In my case I found the solution thank to this aricle where a simple but effective solution is proposed:

_x000D_
_x000D_
html,
body {
  position: fixed;
  overflow: hidden;
}
_x000D_
_x000D_
_x000D_

This solution it's not applicable if your body is your scroll container.

Assigning a variable NaN in python without numpy

Yes -- use math.nan.

>>> from math import nan
>>> print(nan)
nan
>>> print(nan + 2)
nan
>>> nan == nan
False
>>> import math
>>> math.isnan(nan)
True

Before Python 3.5, one could use float("nan") (case insensitive).

Note that checking to see if two things that are NaN are equal to one another will always return false. This is in part because two things that are "not a number" cannot (strictly speaking) be said to be equal to one another -- see What is the rationale for all comparisons returning false for IEEE754 NaN values? for more details and information.

Instead, use math.isnan(...) if you need to determine if a value is NaN or not.

Furthermore, the exact semantics of the == operation on NaN value may cause subtle issues when trying to store NaN inside container types such as list or dict (or when using custom container types). See Checking for NaN presence in a container for more details.


You can also construct NaN numbers using Python's decimal module:

>>> from decimal import Decimal
>>> b = Decimal('nan')
>>> print(b)
NaN
>>> print(repr(b))
Decimal('NaN')
>>>
>>> Decimal(float('nan'))
Decimal('NaN')
>>> 
>>> import math
>>> math.isnan(b)
True

math.isnan(...) will also work with Decimal objects.


However, you cannot construct NaN numbers in Python's fractions module:

>>> from fractions import Fraction
>>> Fraction('nan')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python35\lib\fractions.py", line 146, in __new__
    numerator)
ValueError: Invalid literal for Fraction: 'nan'
>>>
>>> Fraction(float('nan'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python35\lib\fractions.py", line 130, in __new__
    value = Fraction.from_float(numerator)
  File "C:\Python35\lib\fractions.py", line 214, in from_float
    raise ValueError("Cannot convert %r to %s." % (f, cls.__name__))
ValueError: Cannot convert nan to Fraction.

Incidentally, you can also do float('Inf'), Decimal('Inf'), or math.inf (3.5+) to assign infinite numbers. (And also see math.isinf(...))

However doing Fraction('Inf') or Fraction(float('inf')) isn't permitted and will throw an exception, just like NaN.

If you want a quick and easy way to check if a number is neither NaN nor infinite, you can use math.isfinite(...) as of Python 3.2+.


If you want to do similar checks with complex numbers, the cmath module contains a similar set of functions and constants as the math module:

How to check if a process is in hang state (Linux)

Unfortunately there is no hung state for a process. Now hung can be deadlock. This is block state. The threads in the process are blocked. The other things could be live lock where the process is running but doing the same thing again and again. This process is in running state. So as you can see there is no definite hung state. As suggested you can use the top command to see if the process is using 100% CPU or lot of memory.

What does "make oldconfig" do exactly in the Linux kernel makefile?

It reads the existing .config file that was used for an old kernel and prompts the user for options in the current kernel source that are not found in the file. This is useful when taking an existing configuration and moving it to a new kernel.

Jquery function return value

The return statement you have is stuck in the inner function, so it won't return from the outer function. You just need a little more code:

function getMachine(color, qty) {
    var returnValue = null;
    $("#getMachine li").each(function() {
        var thisArray = $(this).text().split("~");
        if(thisArray[0] == color&& qty>= parseInt(thisArray[1]) && qty<= parseInt(thisArray[2])) {
            returnValue = thisArray[3];
            return false; // this breaks out of the each
        }
    });
    return returnValue;
}

var retval = getMachine(color, qty);

How can I fix WebStorm warning "Unresolved function or method" for "require" (Firefox Add-on SDK)

Ok, Here I have seen a lot of answers already given, I want to add some more that are fixed unresolved function/method/variable warning.

That is resolved "unresolved function or method for 'require' and some other warning"

Go -> Preferences-> Languages & Frameworks -> Node.js and NPM, then checkmark the "Coding assistance for Node.js"

If you still see this type of warning, unresolved variable or something like that, you can manually disable these warnings by followings.

Go -> Preferences-> Editor-> Inspections-> JavaScript-> General.  

and you will find a list and just unchecked what warning you want to disable and then apply.

"date(): It is not safe to rely on the system's timezone settings..."

A simple method for two time zone.

<?php 
$date = new DateTime("2012-07-05 16:43:21", new DateTimeZone('Europe/Paris')); 

date_default_timezone_set('America/New_York'); 

echo date("Y-m-d h:iA", $date->format('U')); 

// 2012-07-05 10:43AM 
?>

Why does C# XmlDocument.LoadXml(string) fail when an XML header is included?

Background

Although your question does have the encoding set as UTF-16, you don't have the string properly escaped so I wasn't sure if you did, in fact, accurately transpose the string into your question.

I ran into the same exception:

System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1.

However, my code looked like this:

string xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<event>This is a Test</event>";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);

The Problem

The problem is that strings are stored internally as UTF-16 in .NET however the encoding specified in the XML document header may be different. E.g.:

<?xml version="1.0" encoding="utf-8"?>

From the MSDN documentation for String here:

Each Unicode character in a string is defined by a Unicode scalar value, also called a Unicode code point or the ordinal (numeric) value of the Unicode character. Each code point is encoded using UTF-16 encoding, and the numeric value of each element of the encoding is represented by a Char object.

This means that when you pass XmlDocument.LoadXml() your string with an XML header, it must say the encoding is UTF-16. Otherwise, the actual underlying encoding won't match the encoding reported in the header and will result in an XmlException being thrown.

The Solution

The solution for this problem is to make sure the encoding used in whatever you pass the Load or LoadXml method matches what you say it is in the XML header. In my example above, either change your XML header to state UTF-16 or to encode the input in UTF-8 and use one of the XmlDocument.Load methods.

Below is sample code demonstrating how to use a MemoryStream to build an XmlDocument using a string which defines a UTF-8 encode XML document (but of course, is stored a UTF-16 .NET string).

string xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<event>This is a Test</event>";

// Encode the XML string in a UTF-8 byte array
byte[] encodedString = Encoding.UTF8.GetBytes(xml);

// Put the byte array into a stream and rewind it to the beginning
MemoryStream ms = new MemoryStream(encodedString);
ms.Flush();
ms.Position = 0;

// Build the XmlDocument from the MemorySteam of UTF-8 encoded bytes
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(ms);

Write to CSV file and export it?

Here's a very simple free open-source CsvExport class for C#. There's an ASP.NET MVC example at the bottom.

https://github.com/jitbit/CsvExport

It takes care about line-breaks, commas, escaping quotes, MS Excel compatibilty... Just add one short .cs file to your project and you're good to go.

(disclaimer: I'm one of the contributors)

Change the selected value of a drop-down list with jQuery

I use an extend function to get client ids, like so:

$.extend({
    clientID: function(id) {
        return $("[id$='" + id + "']");
    }
});

Then you can call ASP.NET controls in jQuery like this:

$.clientID("_statusDDL")

How to disable the ability to select in a DataGridView?

you have to create a custom DataGridView

`

namespace System.Windows.Forms
{
    class MyDataGridView : DataGridView
    {
        public bool PreventUserClick = false;

        public MyDataGridView()
        {

        }
        protected override void OnMouseDown(MouseEventArgs e)
        {
            if (PreventUserClick) return;

            base.OnMouseDown(e);
        }
    }
}

` note that you have to first compile the program once with the added class, before you can use the new control.

then go to The .Designer.cs and change the old DataGridView to the new one without having to mess up you previous code.

private System.Windows.Forms.DataGridView dgv; // found close to the bottom

private void InitializeComponent() {
    ...
    this.dgv = new System.Windows.Forms.DataGridView();
    ...
}

to (respective)

private System.Windows.Forms.MyDataGridView dgv;

this.dgv = new System.Windows.Forms.MyDataGridView();

Javascript - How to detect if document has loaded (IE 7/Firefox 3)

Try this:

var body = document.getElementsByTagName('BODY')[0];
// CONDITION DOES NOT WORK
if ((body && body.readyState == 'loaded') || (body &&  body.readyState == 'complete') ) {
    DoStuffFunction();
} else {
    // CODE BELOW WORKS
    if (window.addEventListener) {
        window.addEventListener('load', DoStuffFunction, false);
    } else {
        window.attachEvent('onload',DoStuffFunction);
    }
}

Getting NetworkCredential for current user (C#)

If the web service being invoked uses windows integrated security, creating a NetworkCredential from the current WindowsIdentity should be sufficient to allow the web service to use the current users windows login. However, if the web service uses a different security model, there isn't any way to extract a users password from the current identity ... that in and of itself would be insecure, allowing you, the developer, to steal your users passwords. You will likely need to provide some way for your user to provide their password, and keep it in some secure cache if you don't want them to have to repeatedly provide it.

Edit: To get the credentials for the current identity, use the following:

Uri uri = new Uri("http://tempuri.org/");
ICredentials credentials = CredentialCache.DefaultCredentials;
NetworkCredential credential = credentials.GetCredential(uri, "Basic");

How to check if input is numeric in C++

I guess ctype.h is the header file that you need to look at. it has numerous functions for handling digits as well as characters. isdigit or iswdigit is something that will help you in this case.

Here is a reference: http://docs.embarcadero.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN/html/devwin32/isdigit_xml.html

sizing div based on window width

A good trick is to use inner box-shadow, and let it do all the fading for you rather than applying it to the image.

How do I keep the screen on in my App?

There are multiple ways you can do it:

Solution 1:

class MainActivity extends AppCompactActivity {
    @Override
    protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);    
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }
}

Solution 2:

In activity_main.xml file, simply add:

<android:KeepScreenOn="true"/>

My advice: please don't use WakeLock. If you use it, you have to define extra permission, and mostly this thing is useful in CPU's development environment.

Also, make sure to turn off the screen while closing the activity. You can do it in this way:

public void onDestry() {
    getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}

How do I find files with a path length greater than 260 characters in Windows?

I created the Path Length Checker tool for this purpose, which is a nice, free GUI app that you can use to see the path lengths of all files and directories in a given directory.

I've also written and blogged about a simple PowerShell script for getting file and directory lengths. It will output the length and path to a file, and optionally write it to the console as well. It doesn't limit to displaying files that are only over a certain length (an easy modification to make), but displays them descending by length, so it's still super easy to see which paths are over your threshold. Here it is:

$pathToScan = "C:\Some Folder"  # The path to scan and the the lengths for (sub-directories will be scanned as well).
$outputFilePath = "C:\temp\PathLengths.txt" # This must be a file in a directory that exists and does not require admin rights to write to.
$writeToConsoleAsWell = $true   # Writing to the console will be much slower.

# Open a new file stream (nice and fast) and write all the paths and their lengths to it.
$outputFileDirectory = Split-Path $outputFilePath -Parent
if (!(Test-Path $outputFileDirectory)) { New-Item $outputFileDirectory -ItemType Directory }
$stream = New-Object System.IO.StreamWriter($outputFilePath, $false)
Get-ChildItem -Path $pathToScan -Recurse -Force | Select-Object -Property FullName, @{Name="FullNameLength";Expression={($_.FullName.Length)}} | Sort-Object -Property FullNameLength -Descending | ForEach-Object {
    $filePath = $_.FullName
    $length = $_.FullNameLength
    $string = "$length : $filePath"

    # Write to the Console.
    if ($writeToConsoleAsWell) { Write-Host $string }

    #Write to the file.
    $stream.WriteLine($string)
}
$stream.Close()

horizontal line and right way to code it in html, css

In HTML5, the <hr> tag defines a thematic break. In HTML 4.01, the <hr> tag represents a horizontal rule.

http://www.w3schools.com/tags/tag_hr.asp

So after definition, I would prefer <hr>

Why won't my PHP app send a 404 error?

For the record, this is the all-case handler:

<?php
header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
header("Status: 404 Not Found");

$_SERVER['REDIRECT_STATUS'] = 404;
?> <!-- 404 contents below this line -->

Validate a username and password against Active Directory?

very simple solution using DirectoryServices:

using System.DirectoryServices;

//srvr = ldap server, e.g. LDAP://domain.com
//usr = user name
//pwd = user password
public bool IsAuthenticated(string srvr, string usr, string pwd)
{
    bool authenticated = false;

    try
    {
        DirectoryEntry entry = new DirectoryEntry(srvr, usr, pwd);
        object nativeObject = entry.NativeObject;
        authenticated = true;
    }
    catch (DirectoryServicesCOMException cex)
    {
        //not authenticated; reason why is in cex
    }
    catch (Exception ex)
    {
        //not authenticated due to some other exception [this is optional]
    }

    return authenticated;
}

the NativeObject access is required to detect a bad user/password

How to exclude *AutoConfiguration classes in Spring Boot JUnit tests?

If the issue is that your SpringBootApplication/Configuration you are bringing in is component scanning the package your test configurations are in, you can actually remove the @Configuration annotation from the test configurations and you can still use them in the @SpringBootTest annotations. For example, if you have a class Application that is your main configuration and a class TestConfiguration that is a configuration for certain, but not all tests, you can set up your classes as follows:

@Import(Application.class) //or the specific configurations you want
//(Optional) Other Annotations that will not trigger an autowire
public class TestConfiguration {
    //your custom test configuration
}

And then you can configure your tests in one of two ways:

  1. With the regular configuration:

    @SpringBootTest(classes = {Application.class}) //won't component scan your configuration because it doesn't have an autowire-able annotation
    //Other annotations here
    public class TestThatUsesNormalApplication {
        //my test code
    }
    
  2. With the test custom test configuration:

    @SpringBootTest(classes = {TestConfiguration.class}) //this still works!
    //Other annotations here
    public class TestThatUsesCustomTestConfiguration {
        //my test code
    }
    

Fatal error: Namespace declaration statement has to be the very first statement in the script in

I have also faced the problem. In the php file, I have written following code where there was some space before php start tag

<?php
namespace App\Controller;

when I remove that space, it solved.

setup.py examples?

You may find the HitchHiker's Guide to Packaging helpful, even though it is incomplete. I'd start with the Quick Start tutorial. Try also just browsing through Python packages on the Python Package Index. Just download the tarball, unpack it, and have a look at the setup.py file. Or even better, only bother looking through packages that list a public source code repository such as one hosted on GitHub or BitBucket. You're bound to run into one on the front page.

My final suggestion is to just go for it and try making one; don't be afraid to fail. I really didn't understand it until I started making them myself. It's trivial to create a new package on PyPI and just as easy to remove it. So, create a dummy package and play around.

PHP Parse error: syntax error, unexpected T_PUBLIC

The public keyword is used only when declaring a class method.

Since you're declaring a simple function and not a class you need to remove public from your code.

How can I create a table with borders in Android?

enter image description here

Here i have designed the list by the following design image. My listitem filename is Propertylistitem.xml and cellborder.xml is used drawable shape for the cellborder output, are show in this image. necessary code i added here.

FileName:propertylistitem.xml

<TableLayout... >
            <TableRow... >
                 <TextView ...
                    android:background="@drawable/cellborder"
                    android:text="Amount"/>
            </TableRow>

            <TableRow... >
                <TextView...
                    android:background="@drawable/cellborder"
                    android:text="5000"/>
            </TableRow>
        </TableLayout>

filename:cellborder.xml Here i just want only border in my design, so i put comment the solid color tag.

<?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
    <!--     <solid android:color="#dc6888"/>     -->
        <stroke android:width="0.1dp" android:color="#ffffff"
            />
        <padding android:left="0dp" android:top="0dp"
                android:right="0dp" android:bottom="0dp" />
    </shape>

SQL Server Management Studio – tips for improving the TSQL coding process

My favorite quick tip is that when you expand a table name in the object explorer, just dragging the word colums to the query screen will put a list of all the columns in the table into the query. Much easier to just delete the ones you don't want than to type the ones you do want and it is so easy, it prevents people from using the truly awful select * syntax. And it prevents typos. Of course you can individually drag columns as well.

Does WhatsApp offer an open API?

WhatsApp does not have a API available for public use. As you put it, it's a closed system.

However, they provide several other ways in which your iPhone application can interact with WhatsApp: through custom URL schemes, share extension and through the Document Interaction API.

See this WhatsApp FAQ article.

Why is "throws Exception" necessary when calling a function?

Java requires that you handle or declare all exceptions. If you are not handling an Exception using a try/catch block then it must be declared in the method's signature.

For example:

class throwseg1 {
    void show() throws Exception {
        throw new Exception();
    }
}

Should be written as:

class throwseg1 {
    void show() {
        try {
            throw new Exception();
        } catch(Exception e) {
            // code to handle the exception
        }
    }
}

This way you can get rid of the "throws Exception" declaration in the method declaration.

How do I check if a number is positive or negative in C#?

Of course no-one's actually given the correct answer,

num != 0   // num is positive *or* negative!

Diff files present in two different directories

You can use the diff command for that:

diff -bur folder1/ folder2/

This will output a recursive diff that ignore spaces, with a unified context:

  • b flag means ignoring whitespace
  • u flag means a unified context (3 lines before and after)
  • r flag means recursive

How can I issue a single command from the command line through sql plus?

Have you tried something like this?

sqlplus username/password@database < "EXECUTE some_proc /"

Seems like in UNIX you can do:

sqlplus username/password@database <<EOF
EXECUTE some_proc;
EXIT;
EOF

But I'm not sure what the windows equivalent of that would be.

how to use ng-option to set default value of select element

<select name='partyid' id="partyid" class='span3'>
<option value=''>Select Party</option>
<option ng-repeat="item in partyName" value="{{item._id}}" ng-selected="obj.partyname == item.partyname">{{item.partyname}}
</option>
</select>

How to use android emulator for testing bluetooth application?

Download Androidx86 from this This is an iso file, so you'd
need something like VMWare or VirtualBox to run it When creating the virtual machine, you need to set the type of guest OS as Linux instead of Other.

After creating the virtual machine set the network adapter to 'Bridged'. · Start the VM and select 'Live CD VESA' at boot.

Now you need to find out the IP of this VM. Go to terminal in VM (use Alt+F1 & Alt+F7 to toggle) and use the netcfg command to find this.

Now you need open a command prompt and go to your android install folder (on host). This is usually C:\Program Files\Android\android-sdk\platform-tools>.

Type adb connect IP_ADDRESS. There done! Now you need to add Bluetooth. Plug in your USB Bluetooth dongle/Bluetooth device.

In VirtualBox screen, go to Devices>USB devices. Select your dongle.

Done! now your Android VM has Bluetooth. Try powering on Bluetooth and discovering/paring with other devices.

Now all that remains is to go to Eclipse and run your program. The Android AVD manager should show the VM as a device on the list.

Alternatively, Under settings of the virtual machine, Goto serialports -> Port 1 check Enable serial port select a port number then select port mode as disconnected click ok. now, start virtual machine. Under Devices -> USB Devices -> you can find your laptop bluetooth listed. You can simply check the option and start testing the android bluetooth application .

Source

npm not working - "read ECONNRESET"

This can be caused by installing anything with npm using sudo -- this causes the files in the cache to be owned by root, resulting in this problem. You can fix it by running:

sudo rm -rf ~/.npm

to remove the cache. Then try whatever you were doing again, making sure you never use sudo along with npm (or the problem may come back).

Lots more information: npm throws error without sudo

Assign a login to a user created without login (SQL Server)

Create a login for the user

Drop and re-create the user, WITH the login you created.

There are other topics discussing how to replicate the permissions of your user. I recommend that you take the opportunity to define those permissions in a Role and call sp_addrolemember to add the user to the Role.

Creating default object from empty value in PHP?

Your new environment may have E_STRICT warnings enabled in error_reporting for PHP versions <= 5.3.x, or simply have error_reporting set to at least E_WARNING with PHP versions >= 5.4. That error is triggered when $res is NULL or not yet initialized:

$res = NULL;
$res->success = false; // Warning: Creating default object from empty value

PHP will report a different error message if $res is already initialized to some value but is not an object:

$res = 33;
$res->success = false; // Warning: Attempt to assign property of non-object

In order to comply with E_STRICT standards prior to PHP 5.4, or the normal E_WARNING error level in PHP >= 5.4, assuming you are trying to create a generic object and assign the property success, you need to declare $res as an object of stdClass in the global namespace:

$res = new \stdClass();
$res->success = false;

Getting an element from a Set

If you have an equal object, why do you need the one from the set? If it is "equal" only by a key, an Map would be a better choice.

Anyway, the following will do it:

Foo getEqual(Foo sample, Set<Foo> all) {
  for (Foo one : all) {
    if (one.equals(sample)) {
      return one;
    }
  } 
  return null;
}

With Java 8 this can become a one liner:

return all.stream().filter(sample::equals).findAny().orElse(null);

Call JavaScript function from C#

You can call javascript functions from c# using Jering.Javascript.NodeJS, an open-source library by my organization:

string javascriptModule = @"
module.exports = (callback, x, y) => {  // Module must export a function that takes a callback as its first parameter
    var result = x + y; // Your javascript logic
    callback(null /* If an error occurred, provide an error object or message */, result); // Call the callback when you're done.
}";

// Invoke javascript
int result = await StaticNodeJSService.InvokeFromStringAsync<int>(javascriptModule, args: new object[] { 3, 5 });

// result == 8
Assert.Equal(8, result);

The library supports invoking directly from .js files as well. Say you have file C:/My/Directory/exampleModule.js containing:

module.exports = (callback, message) => callback(null, message);

You can invoke the exported function:

string result = await StaticNodeJSService.InvokeFromFileAsync<string>("C:/My/Directory/exampleModule.js", args: new[] { "test" });

// result == "test"
Assert.Equal("test", result);

What is a "cache-friendly" code?

Processors today work with many levels of cascading memory areas. So the CPU will have a bunch of memory that is on the CPU chip itself. It has very fast access to this memory. There are different levels of cache each one slower access ( and larger ) than the next, until you get to system memory which is not on the CPU and is relatively much slower to access.

Logically, to the CPU's instruction set you just refer to memory addresses in a giant virtual address space. When you access a single memory address the CPU will go fetch it. in the old days it would fetch just that single address. But today the CPU will fetch a bunch of memory around the bit you asked for, and copy it into the cache. It assumes that if you asked for a particular address that is is highly likely that you are going to ask for an address nearby very soon. For example if you were copying a buffer you would read and write from consecutive addresses - one right after the other.

So today when you fetch an address it checks the first level of cache to see if it already read that address into cache, if it doesn't find it, then this is a cache miss and it has to go out to the next level of cache to find it, until it eventually has to go out into main memory.

Cache friendly code tries to keep accesses close together in memory so that you minimize cache misses.

So an example would be imagine you wanted to copy a giant 2 dimensional table. It is organized with reach row in consecutive in memory, and one row follow the next right after.

If you copied the elements one row at a time from left to right - that would be cache friendly. If you decided to copy the table one column at a time, you would copy the exact same amount of memory - but it would be cache unfriendly.

What is Join() in jQuery?

I use join to separate the word in array with "and, or , / , &"

EXAMPLE

HTML

<p>London Mexico Canada</p>
<div></div>

JS

 newText = $("p").text().split(" ").join(" or ");
 $('div').text(newText);

Results

London or Mexico or Canada

copy-item With Alternate Credentials

You should be able to pass whatever credentials you want to the -Credential parameter. So something like:

$cred = Get-Credential

[Enter the credentials]

Copy-Item -Path $from -Destination $to -Credential $cred

Show a leading zero if a number is less than 10

Try this

function pad (str, max) {
  return str.length < max ? pad("0" + str, max) : str;
}

alert(pad("5", 2));

Example

http://jsfiddle.net/

Or

var number = 5;
var i;
if (number < 10) {
    alert("0"+number);
}

Example

http://jsfiddle.net/

Correct way to push into state array

This Code work for me :

fetch('http://localhost:8080')
  .then(response => response.json())
  .then(json => {
  this.setState({mystate: this.state.mystate.push.apply(this.state.mystate, json)})
})

Removing duplicate rows from table in Oracle

The Fastest way for really big tables

  1. Create exception table with structure below: exceptions_table

    ROW_ID ROWID
    OWNER VARCHAR2(30)
    TABLE_NAME VARCHAR2(30)
    CONSTRAINT VARCHAR2(30)
    
  2. Try create a unique constraint or primary key which will be violated by the duplicates. You will get an error message because you have duplicates. The exceptions table will contain the rowids for the duplicate rows.

    alter table add constraint
    unique --or primary key
    (dupfield1,dupfield2) exceptions into exceptions_table;
    
  3. Join your table with exceptions_table by rowid and delete dups

    delete original_dups where rowid in (select ROW_ID from exceptions_table);
    
  4. If the amount of rows to delete is big, then create a new table (with all grants and indexes) anti-joining with exceptions_table by rowid and rename the original table into original_dups table and rename new_table_with_no_dups into original table

    create table new_table_with_no_dups AS (
        select field1, field2 ........ 
        from original_dups t1
        where not exists ( select null from exceptions_table T2 where t1.rowid = t2.row_id )
    )
    

How can I tell Moq to return a Task?

You only need to add .Returns(Task.FromResult(0)); after the Callback.

Example:

mock.Setup(arg => arg.DoSomethingAsync())
    .Callback(() => { <my code here> })
    .Returns(Task.FromResult(0));

Using find to locate files that match one of multiple patterns

This will find all .c or .cpp files on linux

$ find . -name "*.c" -o -name "*.cpp"

You don't need the escaped parenthesis unless you are doing some additional mods. Here from the man page they are saying if the pattern matches, print it. Perhaps they are trying to control printing. In this case the -print acts as a conditional and becomes an "AND'd" conditional. It will prevent any .c files from being printed.

$ find .  -name "*.c" -o -name "*.cpp"  -print

But if you do like the original answer you can control the printing. This will find all .c files as well.

$ find . \( -name "*.c" -o -name "*.cpp" \) -print

One last example for all c/c++ source files

$ find . \( -name "*.c" -o -name "*.cpp"  -o -name "*.h" -o -name "*.hpp" \) -print

How do I use arrays in C++?

Programmers often confuse multidimensional arrays with arrays of pointers.

Multidimensional arrays

Most programmers are familiar with named multidimensional arrays, but many are unaware of the fact that multidimensional array can also be created anonymously. Multidimensional arrays are often referred to as "arrays of arrays" or "true multidimensional arrays".

Named multidimensional arrays

When using named multidimensional arrays, all dimensions must be known at compile time:

int H = read_int();
int W = read_int();

int connect_four[6][7];   // okay

int connect_four[H][7];   // ISO C++ forbids variable length array
int connect_four[6][W];   // ISO C++ forbids variable length array
int connect_four[H][W];   // ISO C++ forbids variable length array

This is how a named multidimensional array looks like in memory:

              +---+---+---+---+---+---+---+
connect_four: |   |   |   |   |   |   |   |
              +---+---+---+---+---+---+---+
              |   |   |   |   |   |   |   |
              +---+---+---+---+---+---+---+
              |   |   |   |   |   |   |   |
              +---+---+---+---+---+---+---+
              |   |   |   |   |   |   |   |
              +---+---+---+---+---+---+---+
              |   |   |   |   |   |   |   |
              +---+---+---+---+---+---+---+
              |   |   |   |   |   |   |   |
              +---+---+---+---+---+---+---+

Note that 2D grids such as the above are merely helpful visualizations. From the point of view of C++, memory is a "flat" sequence of bytes. The elements of a multidimensional array are stored in row-major order. That is, connect_four[0][6] and connect_four[1][0] are neighbors in memory. In fact, connect_four[0][7] and connect_four[1][0] denote the same element! This means that you can take multi-dimensional arrays and treat them as large, one-dimensional arrays:

int* p = &connect_four[0][0];
int* q = p + 42;
some_int_sequence_algorithm(p, q);

Anonymous multidimensional arrays

With anonymous multidimensional arrays, all dimensions except the first must be known at compile time:

int (*p)[7] = new int[6][7];   // okay
int (*p)[7] = new int[H][7];   // okay

int (*p)[W] = new int[6][W];   // ISO C++ forbids variable length array
int (*p)[W] = new int[H][W];   // ISO C++ forbids variable length array

This is how an anonymous multidimensional array looks like in memory:

              +---+---+---+---+---+---+---+
        +---> |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
        |     |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
        |     |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
        |     |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
        |     |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
        |     |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
        |
      +-|-+
   p: | | |
      +---+

Note that the array itself is still allocated as a single block in memory.

Arrays of pointers

You can overcome the restriction of fixed width by introducing another level of indirection.

Named arrays of pointers

Here is a named array of five pointers which are initialized with anonymous arrays of different lengths:

int* triangle[5];
for (int i = 0; i < 5; ++i)
{
    triangle[i] = new int[5 - i];
}

// ...

for (int i = 0; i < 5; ++i)
{
    delete[] triangle[i];
}

And here is how it looks like in memory:

          +---+---+---+---+---+
          |   |   |   |   |   |
          +---+---+---+---+---+
            ^
            | +---+---+---+---+
            | |   |   |   |   |
            | +---+---+---+---+
            |   ^
            |   | +---+---+---+
            |   | |   |   |   |
            |   | +---+---+---+
            |   |   ^
            |   |   | +---+---+
            |   |   | |   |   |
            |   |   | +---+---+
            |   |   |   ^
            |   |   |   | +---+
            |   |   |   | |   |
            |   |   |   | +---+
            |   |   |   |   ^
            |   |   |   |   |
            |   |   |   |   |
          +-|-+-|-+-|-+-|-+-|-+
triangle: | | | | | | | | | | |
          +---+---+---+---+---+

Since each line is allocated individually now, viewing 2D arrays as 1D arrays does not work anymore.

Anonymous arrays of pointers

Here is an anonymous array of 5 (or any other number of) pointers which are initialized with anonymous arrays of different lengths:

int n = calculate_five();   // or any other number
int** p = new int*[n];
for (int i = 0; i < n; ++i)
{
    p[i] = new int[n - i];
}

// ...

for (int i = 0; i < n; ++i)
{
    delete[] p[i];
}
delete[] p;   // note the extra delete[] !

And here is how it looks like in memory:

          +---+---+---+---+---+
          |   |   |   |   |   |
          +---+---+---+---+---+
            ^
            | +---+---+---+---+
            | |   |   |   |   |
            | +---+---+---+---+
            |   ^
            |   | +---+---+---+
            |   | |   |   |   |
            |   | +---+---+---+
            |   |   ^
            |   |   | +---+---+
            |   |   | |   |   |
            |   |   | +---+---+
            |   |   |   ^
            |   |   |   | +---+
            |   |   |   | |   |
            |   |   |   | +---+
            |   |   |   |   ^
            |   |   |   |   |
            |   |   |   |   |
          +-|-+-|-+-|-+-|-+-|-+
          | | | | | | | | | | |
          +---+---+---+---+---+
            ^
            |
            |
          +-|-+
       p: | | |
          +---+

Conversions

Array-to-pointer decay naturally extends to arrays of arrays and arrays of pointers:

int array_of_arrays[6][7];
int (*pointer_to_array)[7] = array_of_arrays;

int* array_of_pointers[6];
int** pointer_to_pointer = array_of_pointers;

However, there is no implicit conversion from T[h][w] to T**. If such an implicit conversion did exist, the result would be a pointer to the first element of an array of h pointers to T (each pointing to the first element of a line in the original 2D array), but that pointer array does not exist anywhere in memory yet. If you want such a conversion, you must create and fill the required pointer array manually:

int connect_four[6][7];

int** p = new int*[6];
for (int i = 0; i < 6; ++i)
{
    p[i] = connect_four[i];
}

// ...

delete[] p;

Note that this generates a view of the original multidimensional array. If you need a copy instead, you must create extra arrays and copy the data yourself:

int connect_four[6][7];

int** p = new int*[6];
for (int i = 0; i < 6; ++i)
{
    p[i] = new int[7];
    std::copy(connect_four[i], connect_four[i + 1], p[i]);
}

// ...

for (int i = 0; i < 6; ++i)
{
    delete[] p[i];
}
delete[] p;

Where can I find a list of escape characters required for my JSON ajax return type?

The JSON reference states:

 any-Unicode-character-
     except-"-or-\\-or-
     control-character

Then lists the standard escape codes:

  \" Standard JSON quote
  \\ Backslash (Escape char)
  \/ Forward slash
  \b Backspace (ascii code 08)
  \f Form feed (ascii code 0C)
  \n Newline
  \r Carriage return
  \t Horizontal Tab
  \u four-hex-digits

From this I assumed that I needed to escape all the listed ones and all the other ones are optional. You can choose to encode all characters into \uXXXX if you so wished, or you could only do any non-printable 7-bit ASCII characters or characters with Unicode value not in \u0020 <= x <= \u007E range (32 - 126). Preferably do the standard characters first for shorter escape codes and thus better readability and performance.

Additionally you can read point 2.5 (Strings) from RFC 4627.

You may (or may not) want to (further) escape other characters depending on where you embed that JSON string, but that is outside the scope of this question.

Could not find default endpoint element

There seem to be several ways to create/fix this issue. For me, the CRM product I am using was written in native code and is able to call my .NET dll, but I run into the configuration information needing to be at/above the main application. For me, the CRM application isn't .NET, so I ended up having to put it in my machine.config file (not where I want it). In addition, since my company uses Websense I had a hard time even adding the Service Reference due to a 407 Proxy Authentication Required issue, that to required a modification to the machine.cong.

Proxy solution:

To get the WCF Service Reference to work I had to copy the information from the app.config of my DLL to the main application config (but for me that was machine.config). And I also had to copy the endpoint information to that same file. Once I did that it starting working for me.

Is there an "exists" function for jQuery?

Just check the length of the selector, if it more than 0 then it's return true otherwise false.

For ID:

 if( $('#selector').length )         // use this if you are using id to check
{
     // it exists
}

For Class:

 if( $('.selector').length )         // use this if you are using class to check
{
     // it exists
}

For Dropdown:

if( $('#selector option').size() ) {   // use this if you are using dropdown size to check

   // it exists
}

Change Screen Orientation programmatically using a Button

Yes it is implementable!

ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

ActivityInfo.SCREEN_ORIENTATION_PORTRAIT

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

ActivityInfo

http://developer.android.com/reference/android/content/pm/ActivityInfo.html

Refer the link:

Button buttonSetPortrait = (Button)findViewById(R.id.setPortrait);
Button buttonSetLandscape = (Button)findViewById(R.id.setLandscape);

buttonSetPortrait.setOnClickListener(new Button.OnClickListener(){

   @Override
   public void onClick(View arg0) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
   }

});

buttonSetLandscape.setOnClickListener(new Button.OnClickListener(){

   @Override
   public void onClick(View arg0) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
   }

});

http://android-er.blogspot.in/2011/08/set-screen-orientation-programmatically.html

Get the full URL in PHP

Examples for: https://(www.)example.com/subFolder/myfile.php?var=blabla#555

// ======= PATHINFO ====== //
$x = pathinfo($url);
$x['dirname']       https://example.com/subFolder
$x['basename']                                    myfile.php?var=blabla#555 // Unsecure! 
$x['extension']                                          php?var=blabla#555 // Unsecure! 
$x['filename']                                    myfile

// ======= PARSE_URL ====== //
$x = parse_url($url);
$x['scheme']        https
$x['host']                  example.com
$x['path']                             /subFolder/myfile.php
$x['query']                                                  var=blabla
$x['fragment']                                                          555

//=================================================== //
//========== self-defined SERVER variables ========== //
//=================================================== //
$_SERVER["DOCUMENT_ROOT"]   /home/user/public_html
$_SERVER["SERVER_ADDR"]     143.34.112.23
$_SERVER["SERVER_PORT"]     80(or 443 etc..)
$_SERVER["REQUEST_SCHEME"]  https                                         //similar: $_SERVER["SERVER_PROTOCOL"] 
$_SERVER['HTTP_HOST']               example.com (or with WWW)             //similar: $_SERVER["SERVER_NAME"]
$_SERVER["REQUEST_URI"]                           /subFolder/myfile.php?var=blabla
$_SERVER["QUERY_STRING"]                                                var=blabla
__FILE__                    /home/user/public_html/subFolder/myfile.php
__DIR__                     /home/user/public_html/subFolder              //same: dirname(__FILE__)
$_SERVER["REQUEST_URI"]                           /subFolder/myfile.php?var=blabla
parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH)  /subFolder/myfile.php 
$_SERVER["PHP_SELF"]                              /subFolder/myfile.php

// ==================================================================//
//if "myfile.php" is included in "PARENTFILE.php" , and you visit  "PARENTFILE.PHP?abc":
$_SERVER["SCRIPT_FILENAME"] /home/user/public_html/parentfile.php
$_SERVER["PHP_SELF"]                              /parentfile.php
$_SERVER["REQUEST_URI"]                           /parentfile.php?var=blabla
__FILE__                    /home/user/public_html/subFolder/myfile.php

// =================================================== //
// ================= handy variables ================= //
// =================================================== //
//If site uses HTTPS:
$HTTP_or_HTTPS = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS']!=='off') || $_SERVER['SERVER_PORT']==443) ? 'https://':'http://' );            //in some cases, you need to add this condition too: if ('https'==$_SERVER['HTTP_X_FORWARDED_PROTO'])  ...

//To trim values to filename, i.e. 
basename($url)              myfile.php

//excellent solution to find origin
$debug_files = debug_backtrace();       
$caller_file = count($debug_files) ? $debug_files[count($debug_files) - 1]['file'] : __FILE__;

Notice ! ! !

  • hashtag # parts were manually used in the above example just for illustration purposes, however, server-side languages (including php) can't natively detect them (Only Javascript can do that, as hashtag is only browser/client side functionality ).
  • DIRECTORY_SEPARATOR returns \ for Windows-type hosting, instead of /.


For WordPress

//(let's say, if wordpress is installed in subdirectory:  http://example.com/wpdir/)
home_url()                       http://example.com/wpdir/        //if is_ssl() is true, then it will be "https"
get_stylesheet_directory_uri()   http://example.com/wpdir/wp-content/themes/THEME_NAME  [same: get_bloginfo('template_url') ]
get_stylesheet_directory()       /home/user/public_html/wpdir/wp-content/themes/THEME_NAME
plugin_dir_url(__FILE__)         http://example.com/wpdir/wp-content/themes/PLUGIN_NAME
plugin_dir_path(__FILE__)        /home/user/public_html/wpdir/wp-content/plugins/PLUGIN_NAME/  

How do I set bold and italic on UILabel of iPhone/iPad?

With iOS 7 system default font, you'll be using helvetica neue bold if you are looking to keep system default font.

    [titleText setFont:[UIFont fontWithName:@"HelveticaNeue-Bold" size:16.0]];

Or you can simply call it:

    [titleText setFont:[UIFont boldSystemFontOfSize:16.0]];

How do I round to the nearest 0.5?

There are several options. If performance is a concern, test them to see which works fastest in a large loop.

double Adjust(double input)
{
    double whole = Math.Truncate(input);
    double remainder = input - whole;
    if (remainder < 0.3)
    {
        remainder = 0;
    }
    else if (remainder < 0.8)
    {
        remainder = 0.5;
    }
    else
    {
        remainder = 1;
    }
    return whole + remainder;
}

get string from right hand side

Simplest solution:

substr('299123456',-6,6)

How do I record audio on iPhone with AVAudioRecorder?

I have uploaded a sample project. You can take a look.

VoiceRecorder

How can I tell which button was clicked in a PHP form submit?

With an HTML form like:

<input type="submit" name="btnSubmit" value="Save Changes" />
<input type="submit" name="btnDelete" value="Delete" />

The PHP code to use would look like:

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Something posted

    if (isset($_POST['btnDelete'])) {
        // btnDelete
    } else {
        // Assume btnSubmit
    }
}

You should always assume or default to the first submit button to appear in the form HTML source code. In practice, the various browsers reliably send the name/value of a submit button with the post data when:

  1. The user literally clicks the submit button with the mouse or pointing device
  2. Or there is focus on the submit button (they tabbed to it), and then the Enter key is pressed.

Other ways to submit a form exist, and some browsers/versions decide not to send the name/value of any submit buttons in some of these situations. For example, many users submit forms by pressing the Enter key when the cursor/focus is on a text field. Forms can also be submitted via JavaScript, as well as some more obscure methods.

It's important to pay attention to this detail, otherwise you can really frustrate your users when they submit a form, yet "nothing happens" and their data is lost, because your code failed to detect a form submission, because you did not anticipate the fact that the name/value of a submit button may not be sent with the post data.

Also, the above advice should be used for forms with a single submit button too because you should always assume a default submit button.

I'm aware that the Internet is filled with tons of form-handler tutorials, and almost of all them do nothing more than check for the name and value of a submit button. But, they're just plain wrong!

Find provisioning profile in Xcode 5

I found a way to find out how your provisioning profile is named. Select the profile that you want in the code sign section in the build settings, then open the selection view again and click on "other" at the bottom. Then occur a view with the naming of the current selected provisioning profile.

You can now find the profile file on the path:

~/Library/MobileDevice/Provisioning Profiles

Update:

For Terminal:

cd ~/Library/MobileDevice/Provisioning\ Profiles

How to debug apk signed for release?

Add the following to your app build.gradle and select the specified release build variant and run

signingConfigs {
        config {
            keyAlias 'keyalias'
            keyPassword 'keypwd'
            storeFile file('<<KEYSTORE-PATH>>.keystore')
            storePassword 'pwd'
        }
    }
    buildTypes {
      release {
          debuggable true
          signingConfig signingConfigs.config
          proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }

How to make a form close when pressing the escape key?

You can set a property on the form to do this for you if you have a button on the form that closes the form already.

Set the CancelButton property of the form to that button.

Gets or sets the button control that is clicked when the user presses the Esc key.

If you don't have a cancel button then you'll need to add a KeyDown handler and check for the Esc key in that:

private void Form_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Escape)
    {
        this.Close();
    }
}

You will also have to set the KeyPreview property to true.

Gets or sets a value indicating whether the form will receive key events before the event is passed to the control that has focus.

However, as Gargo points out in his answer this will mean that pressing Esc to abort an edit on a control in the dialog will also have the effect of closing the dialog. To avoid that override the ProcessDialogKey method as follows:

protected override bool ProcessDialogKey(Keys keyData)
{
    if (Form.ModifierKeys == Keys.None && keyData == Keys.Escape)
    {
        this.Close();
        return true;
    }
    return base.ProcessDialogKey(keyData);
}

What is the difference between map and flatMap and a good use case for each?

map and flatMap are similar, in the sense they take a line from the input RDD and apply a function on it. The way they differ is that the function in map returns only one element, while function in flatMap can return a list of elements (0 or more) as an iterator.

Also, the output of the flatMap is flattened. Although the function in flatMap returns a list of elements, the flatMap returns an RDD which has all the elements from the list in a flat way (not a list).

Is there a way to comment out markup in an .ASPX page?

I believe you're looking for:

<%-- your markup here --%>

That is a serverside comment and will not be delivered to the client ... but it's not optional. If you need this to be programmable, then you'll want this answer :-)

JPA With Hibernate Error: [PersistenceUnit: JPA] Unable to build EntityManagerFactory

Suppress the @JoinColumn(name="categoria") on the ID field of the Categoria class and I think it will work.

How do I set a textbox's text to bold at run time?

 txtText.Font = new Font("Segoe UI", 8,FontStyle.Bold);
 //Font(Font Name,Font Size,Font.Style)

Entity Framework VS LINQ to SQL VS ADO.NET with stored procedures?

First off, if you're starting a new project, go with Entity Framework ("EF") - it now generates much better SQL (more like Linq to SQL does) and is easier to maintain and more powerful than Linq to SQL ("L2S"). As of the release of .NET 4.0, I consider Linq to SQL to be an obsolete technology. MS has been very open about not continuing L2S development further.

1) Performance

This is tricky to answer. For most single-entity operations (CRUD) you will find just about equivalent performance with all three technologies. You do have to know how EF and Linq to SQL work in order to use them to their fullest. For high-volume operations like polling queries, you may want to have EF/L2S "compile" your entity query such that the framework doesn't have to constantly regenerate the SQL, or you can run into scalability issues. (see edits)

For bulk updates where you're updating massive amounts of data, raw SQL or a stored procedure will always perform better than an ORM solution because you don't have to marshal the data over the wire to the ORM to perform updates.

2) Speed of Development

In most scenarios, EF will blow away naked SQL/stored procs when it comes to speed of development. The EF designer can update your model from your database as it changes (upon request), so you don't run into synchronization issues between your object code and your database code. The only time I would not consider using an ORM is when you're doing a reporting/dashboard type application where you aren't doing any updating, or when you're creating an application just to do raw data maintenance operations on a database.

3) Neat/Maintainable code

Hands down, EF beats SQL/sprocs. Because your relationships are modeled, joins in your code are relatively infrequent. The relationships of the entities are almost self-evident to the reader for most queries. Nothing is worse than having to go from tier to tier debugging or through multiple SQL/middle tier in order to understand what's actually happening to your data. EF brings your data model into your code in a very powerful way.

4) Flexibility

Stored procs and raw SQL are more "flexible". You can leverage sprocs and SQL to generate faster queries for the odd specific case, and you can leverage native DB functionality easier than you can with and ORM.

5) Overall

Don't get caught up in the false dichotomy of choosing an ORM vs using stored procedures. You can use both in the same application, and you probably should. Big bulk operations should go in stored procedures or SQL (which can actually be called by the EF), and EF should be used for your CRUD operations and most of your middle-tier's needs. Perhaps you'd choose to use SQL for writing your reports. I guess the moral of the story is the same as it's always been. Use the right tool for the job. But the skinny of it is, EF is very good nowadays (as of .NET 4.0). Spend some real time reading and understanding it in depth and you can create some amazing, high-performance apps with ease.

EDIT: EF 5 simplifies this part a bit with auto-compiled LINQ Queries, but for real high volume stuff, you'll definitely need to test and analyze what fits best for you in the real world.

How to backup MySQL database in PHP?

A solution to take the backup of your Database in "dbBackup" Folder / Directory

<?php
error_reporting(E_ALL);

/* Define database parameters here */
define("DB_USER", 'root');
define("DB_PASSWORD", 'root');
define("DB_NAME", 'YOUR_DATABASE_NAME');
define("DB_HOST", 'localhost');
define("OUTPUT_DIR", 'dbBackup'); // Folder Path / Directory Name
define("TABLES", '*');

/* Instantiate Backup_Database and perform backup */
$backupDatabase = new Backup_Database(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

$status = $backupDatabase->backupTables(TABLES, OUTPUT_DIR) ? 'OK' : 'KO';
echo "Backup result: " . $status;

/* The Backup_Database class */
class Backup_Database {

    private $conn;

    /* Constructor initializes database */
    function __construct( $host, $username, $passwd, $dbName, $charset = 'utf8' ) {
        $this->dbName = $dbName;
        $this->connectDatabase( $host, $username, $passwd, $charset );
    }


    protected function connectDatabase( $host, $username, $passwd, $charset ) {
        $this->conn = mysqli_connect( $host, $username, $passwd, $this->dbName);

        if (mysqli_connect_errno()) {
            echo "Failed to connect to MySQL: " . mysqli_connect_error();
            exit();
        }

        /* change character set to $charset Ex : "utf8" */
        if (!mysqli_set_charset($this->conn, $charset)) {
            printf("Error loading character set ".$charset.": %s\n", mysqli_error($this->conn));
            exit();
        }
    }


    /* Backup the whole database or just some tables Use '*' for whole database or 'table1 table2 table3...' @param string $tables  */
    public function backupTables($tables = '*', $outputDir = '.') {
        try {
            /* Tables to export  */
            if ($tables == '*') {
                $tables = array();
                $result = mysqli_query( $this->conn, 'SHOW TABLES' );

                while ( $row = mysqli_fetch_row($result) ) {
                    $tables[] = $row[0];
                }
            } else {
                $tables = is_array($tables) ? $tables : explode(',', $tables);
            }

            $sql = 'CREATE DATABASE IF NOT EXISTS ' . $this->dbName . ";\n\n";
            $sql .= 'USE ' . $this->dbName . ";\n\n";

            /* Iterate tables */
            foreach ($tables as $table) {
                echo "Backing up " . $table . " table...";

                $result = mysqli_query( $this->conn, 'SELECT * FROM ' . $table );

                // Return the number of fields in result set
                $numFields = mysqli_num_fields($result);

                $sql .= 'DROP TABLE IF EXISTS ' . $table . ';';
                $row2 = mysqli_fetch_row( mysqli_query( $this->conn, 'SHOW CREATE TABLE ' . $table ) );

                $sql.= "\n\n" . $row2[1] . ";\n\n";

                for ($i = 0; $i < $numFields; $i++) {

                    while ($row = mysqli_fetch_row($result)) {

                        $sql .= 'INSERT INTO ' . $table . ' VALUES(';

                        for ($j = 0; $j < $numFields; $j++) {
                            $row[$j] = addslashes($row[$j]);
                            // $row[$j] = ereg_replace("\n", "\\n", $row[$j]);
                            if (isset($row[$j])) {
                                $sql .= '"' . $row[$j] . '"';
                            } else {
                                $sql.= '""';
                            }
                            if ($j < ($numFields - 1)) {
                                $sql .= ',';
                            }
                        }

                        $sql.= ");\n";
                    }
                } // End :: for loop

                mysqli_free_result($result); // Free result set

                $sql.="\n\n\n";
                echo " OK <br/>" . "";
            }
        } catch (Exception $e) {
            var_dump($e->getMessage());
            return false;
        }

        return $this->saveFile($sql, $outputDir);
    }


    /* Save SQL to file @param string $sql */
    protected function saveFile(&$sql, $outputDir = '.') {
        if (!$sql)
            return false;

        try {
            $handle = fopen($outputDir . '/db-backup-' . $this->dbName . '-' . date("Ymd-His", time()) . '.sql', 'w+');
            fwrite($handle, $sql);
            fclose($handle);

            mysqli_close( $this->conn );
        } catch (Exception $e) {
            var_dump($e->getMessage());
            return false;
        }
        return true;
    }

} // End :: class Backup_Database

?>

Travel/Hotel API's?

I've used the TripAdvisor API before and its suited me well. It returns, per destination, a list of top-rated hotels, along with options to retrieve reviews, photos, nearby restaurants and a couple other useful things.

http://www.tripadvisor.com/help/what_type_of_tripadvisor_content_is_available

From the API page (available API content) :

* Hotel, attraction and restaurant ratings and reviews
* Top 10 lists of hotels, attractions and restaurants in a destination
* Traveler photos of a destination
* Travelers' Choice award badges for hotels and destinations

To expand upon @nstehr's answer, you could also use Yahoo Pipes to facilitate a more granular local search. Go to pipes.yahoo.com and do a search for existing hotel pipes and you'll get the idea..

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

I am not a coder, but you could save a few lines:

<div>
            <select onchange="if(selectedIndex!=0)document.getElementById('less_is_more').innerHTML=options[selectedIndex].value;">
                <option value="">hire me for real estate</option>
                <option value="me!!!">Who is a good Broker? </option>
                <option value="yes!!!">Can I buy a house with no down payment</option>
                <option value="send me a note!">Get my contact info?</option>
            </select>
        </div>

<div id="less_is_more"></div>

Here is demo.

Swipe to Delete and the "More" button (like in Mail app on iOS 7)

Swift 3 version code without using any library:

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        tableView.tableFooterView = UIView(frame: CGRect.zero) //Hiding blank cells.
        tableView.separatorInset = UIEdgeInsets.zero
        tableView.dataSource = self
        tableView.delegate = self
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return 4
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath)

        return cell
    }

    //Enable cell editing methods.
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {

        return true
    }

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

    }

    func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {

        let more = UITableViewRowAction(style: .normal, title: "More") { action, index in
            //self.isEditing = false
            print("more button tapped")
        }
        more.backgroundColor = UIColor.lightGray

        let favorite = UITableViewRowAction(style: .normal, title: "Favorite") { action, index in
            //self.isEditing = false
            print("favorite button tapped")
        }
        favorite.backgroundColor = UIColor.orange

        let share = UITableViewRowAction(style: .normal, title: "Share") { action, index in
            //self.isEditing = false
            print("share button tapped")
        }
        share.backgroundColor = UIColor.blue

        return [share, favorite, more]
    }

}

Oracle - What TNS Names file am I using?

Not direct answer to your question, but I've been quite frustrated myself trying find and update all of the tnsnames files, as I had several oracle installs: Client, BI tools, OWB, etc, each of which had its own oracle home. I ended up creating a utility called TNSNamesSync that will update all of the tnsnames in all of the oracle homes. It's under the MIT license, free to use here https://github.com/artybug/TNSNamesSync/releases

The docs are here: https://github.com/artchik/TNSNamesSync/blob/master/README.md

This is for Windows only, though.

Firefox Add-on RESTclient - How to input POST parameters?

Request header needs to be set as per below image.add request header

request body can be passed as json string in text area. enter image description here

Find Java classes implementing an interface

Obviously, Class.isAssignableFrom() tells you whether an individual class implements the given interface. So then the problem is getting the list of classes to test.

As far as I'm aware, there's no direct way from Java to ask the class loader for "the list of classes that you could potentially load". So you'll have to do this yourself by iterating through the visible jars, calling Class.forName() to load the class, then testing it.

However, it's a little easier if you just want to know classes implementing the given interface from those that have actually been loaded:

  • via the Java Instrumentation framework, you can call Instrumentation.getAllLoadedClasses()
  • via reflection, you can query the ClassLoader.classes field of a given ClassLoader.

If you use the instrumentation technique, then (as explained in the link) what happens is that your "agent" class is called essentially when the JVM starts up, and passed an Instrumentation object. At that point, you probably want to "save it for later" in a static field, and then have your main application code call it later on to get the list of loaded classes.

How to extract a single value from JSON response?

using json.loads will turn your data into a python dictionary.

Dictionaries values are accessed using ['key']

resp_str = {
  "name" : "ns1:timeSeriesResponseType",
  "declaredType" : "org.cuahsi.waterml.TimeSeriesResponseType",
  "scope" : "javax.xml.bind.JAXBElement$GlobalScope",
  "value" : {
    "queryInfo" : {
      "creationTime" : 1349724919000,
      "queryURL" : "http://waterservices.usgs.gov/nwis/iv/",
      "criteria" : {
        "locationParam" : "[ALL:103232434]",
        "variableParam" : "[00060, 00065]"
      },
      "note" : [ {
        "value" : "[ALL:103232434]",
        "title" : "filter:sites"
      }, {
        "value" : "[mode=LATEST, modifiedSince=null]",
        "title" : "filter:timeRange"
      }, {
        "value" : "sdas01",
        "title" : "server"
      } ]
    }
  },
  "nil" : false,
  "globalScope" : true,
  "typeSubstituted" : false
}

would translate into a python diction

resp_dict = json.loads(resp_str)

resp_dict['name'] # "ns1:timeSeriesResponseType"

resp_dict['value']['queryInfo']['creationTime'] # 1349724919000

How to change column datatype from character to numeric in PostgreSQL 8.4

Step 1: Add new column with integer or numeric as per your requirement

Step 2: Populate data from varchar column to numeric column

Step 3: drop varchar column

Step 4: change new numeric column name as per old varchar column

What is the best way to implement constants in Java?

To take it a step further, you can place globally used constants in an interface so they can be used system wide. E.g.

public interface MyGlobalConstants {
    public static final int TIMEOUT_IN_SECS = 25;
}

But don't then implement it. Just refer to them directly in code via the fully qualified classname.

jquery .html() vs .append()

if by .add you mean .append, then the result is the same if #myDiv is empty.

is the performance the same? dont know.

.html(x) ends up doing the same thing as .empty().append(x)

String to decimal conversion: dot separation instead of comma

You are viewing your decimal or double values in Visual Studio. That doesn't respect the culture settings you have on your code.

Change the Region and Language settings on your Control Panel if you want to see decimal and double values having the comma as the decimal separator.

Write a file in UTF-8 using FileWriter (Java)?

Ditch FileWriter and FileReader, which are useless exactly because they do not allow you to specify the encoding. Instead, use

new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)

and

new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8);

Writing a VLOOKUP function in vba

As Tim Williams suggested, using Application.VLookup will not throw an error if the lookup value is not found (unlike Application.WorksheetFunction.VLookup).

If you want the lookup to return a default value when it fails to find a match, and to avoid hard-coding the column number -- an equivalent of IFERROR(VLOOKUP(what, where, COLUMNS(where), FALSE), default) in formulas, you could use the following function:

Private Function VLookupVBA(what As Variant, lookupRng As Range, defaultValue As Variant) As Variant
    Dim rv As Variant: rv = Application.VLookup(what, lookupRng, lookupRng.Columns.Count, False)
    If IsError(rv) Then
        VLookupVBA = defaultValue
    Else
        VLookupVBA = rv
    End If
End Function

Public Sub UsageExample()
    MsgBox VLookupVBA("ValueToFind", ThisWorkbook.Sheets("ReferenceSheet").Range("A:D"), "Not found!")
End Sub

PHP: Count a stdClass object

The count function is meant to be used on

  1. Arrays
  2. Objects that are derived from classes that implement the countable interface

A stdClass is neither of these. The easier/quickest way to accomplish what you're after is

$count = count(get_object_vars($some_std_class_object));

This uses PHP's get_object_vars function, which will return the properties of an object as an array. You can then use this array with PHP's count function.

How do I calculate percentiles with python/numpy?

By the way, there is a pure-Python implementation of percentile function, in case one doesn't want to depend on scipy. The function is copied below:

## {{{ http://code.activestate.com/recipes/511478/ (r1)
import math
import functools

def percentile(N, percent, key=lambda x:x):
    """
    Find the percentile of a list of values.

    @parameter N - is a list of values. Note N MUST BE already sorted.
    @parameter percent - a float value from 0.0 to 1.0.
    @parameter key - optional key function to compute value from each element of N.

    @return - the percentile of the values
    """
    if not N:
        return None
    k = (len(N)-1) * percent
    f = math.floor(k)
    c = math.ceil(k)
    if f == c:
        return key(N[int(k)])
    d0 = key(N[int(f)]) * (c-k)
    d1 = key(N[int(c)]) * (k-f)
    return d0+d1

# median is 50th percentile.
median = functools.partial(percentile, percent=0.5)
## end of http://code.activestate.com/recipes/511478/ }}}

Oracle select most recent date record

you can't use aliases from select list inside the WHERE clause (because of the Order of Evaluation of a SELECT statement)

also you cannot use OVER clause inside WHERE clause - "You can specify analytic functions with this clause in the select list or ORDER BY clause." (citation from docs.oracle.com)

select *
from (select
  staff_id, site_id, pay_level, date, 
  max(date) over (partition by staff_id) max_date
  from owner.table
  where end_enrollment_date is null
)
where date = max_date

Exporting functions from a DLL with dllexport

I had exactly the same problem, my solution was to use module definition file (.def) instead of __declspec(dllexport) to define exports(http://msdn.microsoft.com/en-us/library/d91k01sh.aspx). I have no idea why this works, but it does

angular.min.js.map not found, what is it exactly?

Monkey is right, according to the link given by monkey

Basically it's a way to map a combined/minified file back to an unbuilt state. When you build for production, along with minifying and combining your JavaScript files, you generate a source map which holds information about your original files. When you query a certain line and column number in your generated JavaScript you can do a lookup in the source map which returns the original location.

I am not sure if it is angular's fault that no map files were generated. But you can turn off source map files by unchecking this option in chrome console setting

enter image description here

Delete an element from a dictionary

pop mutates the dictionary.

 >>> lol = {"hello": "gdbye"}
 >>> lol.pop("hello")
     'gdbye'
 >>> lol
     {}

If you want to keep the original you could just copy it.

Practical uses of different data structures

The excellent book "Algorithm Design Manual" by Skienna contains a huge repository of Algorithms and Data structure.

For tons of problems, data structures and algorithm are described, compared, and discusses the practical usage. The author also provides references to implementations and the original research papers.

The book is great to have it on your desk if you search the best data structure for your problem to solve. It is also very helpful for interview preparation.

Another great resource is the NIST Dictionary of Data structures and algorithms.

How to get ELMAH to work with ASP.NET MVC [HandleError] attribute?

You can take the code above and go one step further by introducing a custom controller factory that injects the HandleErrorWithElmah attribute into every controller.

For more infomation check out my blog series on logging in MVC. The first article covers getting Elmah set up and running for MVC.

There is a link to downloadable code at the end of the article. Hope that helps.

http://dotnetdarren.wordpress.com/

Unmount the directory which is mounted by sshfs in Mac

In my case (Mac OS Mojave), the key is to use the full path $umount -f /Volumnes/fullpath/folder

Failed to load resource: net::ERR_FILE_NOT_FOUND loading json.js

Same thing happened to me. Eventually my solution was to navigate to the repository using terminal (on mac) and create a new js file with a slightly different name. It linked immediately so i copied contents of original file to new one. You also might want to lose the first / after src= and use "".

Create a 3D matrix

I use Octave, but Matlab has the same syntax.

Create 3d matrix:

octave:3> m = ones(2,3,2)
m =

ans(:,:,1) =

   1   1   1
   1   1   1

ans(:,:,2) =

   1   1   1
   1   1   1

Now, say I have a 2D matrix that I want to expand in a new dimension:

octave:4> Two_D = ones(2,3)
Two_D =
   1   1   1
   1   1   1

I can expand it by creating a 3D matrix, setting the first 2D in it to my old (here I have size two of the third dimension):

octave:11> Three_D = zeros(2,3,2)
Three_D =

ans(:,:,1) =

   0   0   0
   0   0   0

ans(:,:,2) =

   0   0   0
   0   0   0



octave:12> Three_D(:,:,1) = Two_D
Three_D =

ans(:,:,1) =

   1   1   1
   1   1   1

ans(:,:,2) =

   0   0   0
   0   0   0

Installing MySQL in Docker fails with error message "Can't connect to local MySQL server through socket"

Months after this question, I've levelup my Docker skills. I should use Docker container name instead.

That use dokerized-nginx as bridge to expose ip+port of the container.

Within WEB configuration, I now use mysql://USERNAME:PASSWORD@docker_container_name/DB_NAME to access to Mysql socket through docker (also works with docker-compose, use compose-name instead of container one)

How to truncate string using SQL server

I think the answers here are great, but I would like to add a scenario.

Several times I've wanted to take a certain amount of characters off the front of a string, without worrying about it's length. There are several ways of doing this with RIGHT() and SUBSTRING(), but they all need to know the length of the string which can sometimes slow things down.

I've use the STUFF() function instead:

SET @Result = STUFF(@Result, 1, @LengthToRemove, '')

This replaces the length of unneeded string with an empty string.

Could not reserve enough space for object heap

If you're running 32bit JVM, change heap size to smaller would probabaly help. You can do this by passing args to java directly or through enviroment variables like following,

java -Xms128M -Xmx512M
JAVA_OPTS="-Xms128M -Xmx512M"

For 64bit JVM, bigger heap size like -Xms512M -Xmx1536M should work.

Run java -version or java -d32, java--d64 for Java7 to check which version you're running.

How to remove square brackets in string using regex?

You probably don't even need string substitution for that. If your original string is JSON, try:

js> a="['abc','xyz']"
['abc','xyz']
js> eval(a).join(",")
abc,xyz

Be careful with eval, of course.

What is phtml, and when should I use a .phtml extension rather than .php?

It is a file ext that some folks used for a while to denote that it was PHP generated HTML. As servers like Apache don't care what you use as a file ext as long as it is mapped to something, you could go ahead and call all your PHP files .jimyBobSmith and it would happily run them. PHTML just happened to be a trend that caught on for a while.

How to remove an appended element with Jquery and why bind or live is causing elements to repeat

The live function is registering a click event handler. It'll do so every time you click the object. So if you click it twice, you're assigning two click handlers to the object. You're also assigning a click handler here:

onclick="feedback('the message html')";

And then that click handler is assigning another click handler via live().

Really what I think you want to do is this:

function feedback(message)
{
    $('#feedback').remove();

    $('.answers').append('<div id="feedback">'+message+'</div>');
}

Ok, per your comment, try taking out the onclick part of the <a> element and instead, putting this in a document.ready() handler.

$('#answer').live('click',function(){
                     $('#feedback').remove();
                     $('.answers').append('<div id="feedback">'+message+'</div>');
                 });

The following untracked working tree files would be overwritten by merge, but I don't care

In my case when I had this problem. I had a local file that I had renamed on the remote.

When trying to git pull Git told me the new filename was not tracked -- which it was on the remote although it didn't yet exist on local.

Because there was no instance of it locally I couldn't do git pull until I did git rm on the old filename (which wasn't obvious at first because of my stupid idea of renaming it).

How to configure "Shorten command line" method for whole project in IntelliJ

Thanks to Rajesh Goel in Android Studio:

Run > Edit Configurations...

enter image description here

Select a test (better to select a parent test class) and set a Shorten command line: option to classpath file. Then OK (or Apply, OK).

enter image description here

Why do I need to override the equals and hashCode methods in Java?

Consider collection of balls in a bucket all in black color. Your Job is to color those balls as follows and use it for appropriate game,

For Tennis - Yellow, Red. For Cricket - White

Now bucket has balls in three colors Yellow, Red and White. And that now you did the coloring Only you know which color is for which game.

Coloring the balls - Hashing. Choosing the ball for game - Equals.

If you did the coloring and some one chooses the ball for either cricket or tennis they wont mind the color!!!

Get current scroll position of ScrollView in React Native

To get the x/y after scroll ended as the original questions was requesting, the easiest way is probably this:

<ScrollView
   horizontal={true}
   pagingEnabled={true}
   onMomentumScrollEnd={(event) => { 
      // scroll animation ended
      console.log(e.nativeEvent.contentOffset.x);
      console.log(e.nativeEvent.contentOffset.y);
   }}>
   ...content
</ScrollView>

How to sum data.frame column values?

When you have 'NA' values in the column, then

sum(as.numeric(JuneData1$Account.Balance), na.rm = TRUE)

Create a string with n characters

How about this?

char[] bytes = new char[length];
Arrays.fill(bytes, ' ');
String str = new String(bytes);

Downcasting in Java

Downcasting is very useful in the following code snippet I use this all the time. Thus proving that downcasting is useful.

private static String printAll(LinkedList c)
{
    Object arr[]=c.toArray();
    String list_string="";
    for(int i=0;i<c.size();i++)
    {
        String mn=(String)arr[i];
        list_string+=(mn);
    }
    return list_string;
}

I store String in the Linked List. When I retrieve the elements of Linked List, Objects are returned. To access the elements as Strings(or any other Class Objects), downcasting helps me.

Java allows us to compile downcast code trusting us that we are doing the wrong thing. Still if humans make a mistake, it is caught at runtime.

Unprotect workbook without password

No longer works for spreadsheets Protected with Excel 2013 or later -- they improved the pw hash. So now need to unzip .xlsx and hack the internals.

Format a BigDecimal as String with max 2 decimal digits, removing 0 on decimal part

The below code may help you.

protected String getLocalizedBigDecimalValue(BigDecimal input, Locale locale) {
    final NumberFormat numberFormat = NumberFormat.getNumberInstance(locale);
    numberFormat.setGroupingUsed(true);
    numberFormat.setMaximumFractionDigits(2);
    numberFormat.setMinimumFractionDigits(2);
    return numberFormat.format(input);
}

How to add a Hint in spinner in XML

The trick is this line

((TextView) view).setTextColor(ContextCompat.getColor(mContext, R.color.login_input_hint_color));

use it in the onItemSelected. Here is my code with more context

List<String> list = getLabels(); // First item will be the placeholder
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_spinner_item, list);
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(dataAdapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                // First item will be gray
                if (position == 0) {
                    ((TextView) view).setTextColor(ContextCompat.getColor(mContext, R.color.login_input_hint_color));
                } else {
                    ((TextView) view).setTextColor(ContextCompat.getColor(mContext, R.color.primary_text));
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

Format timedelta to string

import datetime
hours = datetime.timedelta(hours=16, minutes=30)
print((datetime.datetime(1,1,1) + hours).strftime('%H:%M'))

Printf width specifier to maintain precision of floating-point value

The short answer to print floating point numbers losslessly (such that they can be read back in to exactly the same number, except NaN and Infinity):

  • If your type is float: use printf("%.9g", number).
  • If your type is double: use printf("%.17g", number).

Do NOT use %f, since that only specifies how many significant digits after the decimal and will truncate small numbers. For reference, the magic numbers 9 and 17 can be found in float.h which defines FLT_DECIMAL_DIG and DBL_DECIMAL_DIG.

Google Maps API warning: NoApiKeys

I had the same problem and I found out that if you add the URL param ?v=3 you won't get the warning message anymore:

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3"></script>

Reproduction online

As pointed out in the comments by @Zia Ul Rehman Mughal

Turns out specifying this means you are referring to old frozen version 3.0 not the latest version. Frozen old versions are not updated with bug fixes or anything. But this is good to mention though. https://developers.google.com/maps/documentation/javascript/versions#the-frozen-version

Update 07-Jun-2016

This solution doesn't work anymore.

PHP Session data not being saved

I had session cookie path set to "//" instead of "/". Firebug is awesome. Hope it helps somebody.

Hide particular div onload and then show div after click

This is an easier way to do it. Hope this helps...

<script type="text/javascript">
$(document).ready(function () {
    $("#preview").toggle(function() {
        $("#div1").hide();
        $("#div2").show();
    }, function() {
        $("#div1").show();
        $("#div2").hide();
    });
});

<div id="div1">
This is preview Div1. This is preview Div1.
</div>

<div id="div2" style="display:none;">
This is preview Div2 to show after div 1 hides.
</div>

<div id="preview" style="color:#999999; font-size:14px">
PREVIEW
</div>
  • If you want the div to be hidden on load, make the style display:none
  • Use toggle rather than click function.


Links:

JQuery Tutorials

JQuery References

Get the position of a spinner in Android

if (position ==0) {
    if (rYes.isChecked()) {
        Toast.makeText(SportActivity.this, "yes ur answer is right", Toast.LENGTH_LONG).show();
    } else if (rNo.isChecked()) {
        Toast.makeText(SportActivity.this, "no.ur answer is wrong", Toast.LENGTH_LONG).show();
    }
}

This code is supposed to select both check boxes.
Is there a problem with it?

How to create an executable .exe file from a .m file

The "StandAlone" method to compile .m file (or files) requires a set of Matlab published library (.dll) files on a target (non-Matlab) platform to allow execution of the compiler generated .exe.

Check MATLAB main site for their compiler products and their limitations.

Submit a form in a popup, and then close the popup

I have executed the code in my machine its working for IE and FF also.

function closeSelf(){
    // do something

    if(condition satisfied){
       alert("conditions satisfied, submiting the form.");
       document.forms['certform'].submit();
       window.close();
    }else{
       alert("conditions not satisfied, returning to form");    
    }
}


<form action="/system/wpacert" method="post" enctype="multipart/form-data" name="certform">
       <div>Certificate 1: <input type="file" name="cert1"/></div>
       <div>Certificate 2: <input type="file" name="cert2"/></div>
       <div>Certificate 3: <input type="file" name="cert3"/></div>

       // change the submit button to normal button
       <div><input type="button" value="Upload"  onclick="closeSelf();"/></div>
</form>

Best way to check if MySQL results returned in PHP?

What is more logical then testing the TYPE of the result variable before processing? It is either of type 'boolean' or 'resource'. When you use a boolean for parameter with mysqli_num_rows, a warning will be generated because the function expects a resource.

$result = mysqli_query($dbs, $sql);

if(gettype($result)=='boolean'){ // test for boolean
    if($result){  // returned TRUE, e.g. in case of a DELETE sql  
        echo "SQL succeeded"; 
    } else { // returned FALSE
        echo "Error: " . mysqli_error($dbs);
    } 
} else { // must be a resource
    if(mysqli_num_rows($result)){

       // process the data    

    }
    mysqli_free_result($result);  
 }

Enter key in textarea

My scenario is when the user strikes the enter key while typing in textarea i have to include a line break.I achieved this using the below code......Hope it may helps somebody......

function CheckLength()
{
    var keyCode = event.keyCode
    if (keyCode == 13)
    {
        document.getElementById('ctl00_ContentPlaceHolder1_id_txt_Suggestions').value = document.getElementById('ctl00_ContentPlaceHolder1_id_txt_Suggestions').value + "\n<br>";
    }
}

Using a BOOL property

Apple simply recommends declaring an isX getter for stylistic purposes. It doesn't matter whether you customize the getter name or not, as long as you use the dot notation or message notation with the correct name. If you're going to use the dot notation it makes no difference, you still access it by the property name:

@property (nonatomic, assign) BOOL working;

[self setWorking:YES];         // Or self.working = YES;
BOOL working = [self working]; // Or = self.working;

Or

@property (nonatomic, assign, getter=isWorking) BOOL working;

[self setWorking:YES];           // Or self.working = YES;, same as above
BOOL working = [self isWorking]; // Or = self.working;, also same as above

Support for the experimental syntax 'classProperties' isn't currently enabled

After almost 3 hours of searching and spending time on the same error, I found that I'm using name import for React:

import { React } from 'react';

which is totally wrong. Just by switching it to:

import React from 'react';

all the error are gone. I hope this helps someone. This is my .babelrc:

{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-react"
  ],
  "plugins": [
      "@babel/plugin-proposal-class-properties"
  ]
}

the webpack.config.js

const path = require('path');
const devMode = process.env.Node_ENV !== 'production';
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
  entry: './src/App.js',
  devtool: 'source-map',
  output: {
    path: path.resolve(__dirname, 'public'),
    filename: 'App.js'
  },
  mode: 'development',
  devServer: {
    contentBase: path.resolve(__dirname, 'public'),
    port:9090,
    open: 'google chrome',
    historyApiFallback: true
  },
  module: {
    rules: [
      {
        test: /\.m?js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader'
        }
      },{
        test: /\.(sa|sc|c)ss$/,
        use: [
          devMode ? 'style-loader' : MiniCssExtractPlugin.loader,
          {
            loader: 'css-loader',
            options: {
              modules: true,
              localIdentName: '[local]--[hash:base64:5]',
              sourceMap: true
            }
          },{
            loader: 'sass-loader'
          }
        ]
      }
    ]
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: devMode ? '[name].css' : '[name].[hash].css',
      chunkFilename: devMode ? '[id].css' : '[id].[hash].css'
    })
  ]
}

the package.json

{
  "name": "expense-app",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "webpack",
    "serve": "webpack-dev-server"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/cli": "^7.1.2",
    "@babel/core": "^7.1.2",
    "@babel/plugin-proposal-class-properties": "^7.1.0",
    "@babel/preset-env": "^7.1.0",
    "@babel/preset-react": "^7.0.0",
    "babel-loader": "^8.0.4",
    "css-loader": "^1.0.0",
    "mini-css-extract-plugin": "^0.4.3",
    "node-sass": "^4.9.3",
    "react-router-dom": "^4.3.1",
    "sass-loader": "^7.1.0",
    "style-loader": "^0.23.1",
    "webpack": "^4.20.2",
    "webpack-cli": "^3.1.2",
    "webpack-dev-server": "^3.1.9"
  },
  "dependencies": {
    "normalize.css": "^8.0.0",
    "react": "^16.5.2",
    "react-dom": "^16.5.2"
  }
}

With block equivalent in C#?

You could use the argument accumulator pattern.

Big discussion about this here:

http://blogs.msdn.com/csharpfaq/archive/2004/03/11/87817.aspx

Defining arrays in Google Scripts

This may be of help to a few who are struggling like I was:

var data = myform.getRange("A:AA").getValues().pop();
var myvariable1 = data[4];
var myvariable2 = data[7];

Get model's fields in Django

As per the django documentation 2.2 you can use:

To get all fields: Model._meta.get_fields()

To get an individual field: Model._meta.get_field('field name')

ex. Session._meta.get_field('expire_date')

Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state

For me the issue was signing into my Google account on the debug Chrome window. This had been working fine for me until I signed in. Once I signed out of that instance of Chrome AND choose to delete all of my settings via the checkbox, the debugger worked fine again.

My non-debugging instance of Chrome was still signed into Google and unaffected. The main issue is that my lovely plugins are gone from the debug version, but at least I can step through client code again.

Self Join to get employee manager name

try this ..you should do LEFT JOIN to igore null values in the table

SELECT a.emp_Id EmployeeId, a.emp_name EmployeeName,  
       a.emp_mgr_id ManagerId, b.emp_name AS ManagerName 
FROM   tblEmployeeDetails a 
       LEFT JOIN tblEmployeeDetails b
       ON b.emp_mgr_id = b.emp_id

Hibernate table not mapped error in HQL query

Thanks everybody. Lots of good ideas. This is my first application in Spring and Hibernate.. so a little more patience when dealing with "novices" like me..

Please read Tom Anderson and Roman C.'s answers. They explained very well the problem. And all of you helped me.I replaced

SELECT COUNT(*) FROM Books

with

select count(book.id) from Book book

And of course, I have this Spring config:

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="packagesToScan" value="extjs.model"/>

Thank you all again!

Download file through an ajax call php

AJAX isn't for downloading files. Pop up a new window with the download link as its address, or do document.location = ....

Open a local HTML file using window.open in Chrome

window.location.href = 'file://///fileserver/upload/Old_Upload/05_06_2019/THRESHOLD/BBH/Look/chrs/Delia';

Nothing Worked for me.

Correct way to try/except using Python requests module?

Have a look at the Requests exception docs. In short:

In the event of a network problem (e.g. DNS failure, refused connection, etc), Requests will raise a ConnectionError exception.

In the event of the rare invalid HTTP response, Requests will raise an HTTPError exception.

If a request times out, a Timeout exception is raised.

If a request exceeds the configured number of maximum redirections, a TooManyRedirects exception is raised.

All exceptions that Requests explicitly raises inherit from requests.exceptions.RequestException.

To answer your question, what you show will not cover all of your bases. You'll only catch connection-related errors, not ones that time out.

What to do when you catch the exception is really up to the design of your script/program. Is it acceptable to exit? Can you go on and try again? If the error is catastrophic and you can't go on, then yes, you may abort your program by raising SystemExit (a nice way to both print an error and call sys.exit).

You can either catch the base-class exception, which will handle all cases:

try:
    r = requests.get(url, params={'s': thing})
except requests.exceptions.RequestException as e:  # This is the correct syntax
    raise SystemExit(e)

Or you can catch them separately and do different things.

try:
    r = requests.get(url, params={'s': thing})
except requests.exceptions.Timeout:
    # Maybe set up for a retry, or continue in a retry loop
except requests.exceptions.TooManyRedirects:
    # Tell the user their URL was bad and try a different one
except requests.exceptions.RequestException as e:
    # catastrophic error. bail.
    raise SystemExit(e)

As Christian pointed out:

If you want http errors (e.g. 401 Unauthorized) to raise exceptions, you can call Response.raise_for_status. That will raise an HTTPError, if the response was an http error.

An example:

try:
    r = requests.get('http://www.google.com/nothere')
    r.raise_for_status()
except requests.exceptions.HTTPError as err:
    raise SystemExit(err)

Will print:

404 Client Error: Not Found for url: http://www.google.com/nothere

Changing the maximum length of a varchar column?

You need

ALTER TABLE YourTable ALTER COLUMN YourColumn <<new_datatype>> [NULL | NOT NULL]

But remember to specify NOT NULL explicitly if desired.

ALTER TABLE YourTable ALTER COLUMN YourColumn VARCHAR (500) NOT NULL;

If you leave it unspecified as below...

ALTER TABLE YourTable ALTER COLUMN YourColumn VARCHAR (500);

Then the column will default to allowing nulls even if it was originally defined as NOT NULL. i.e. omitting the specification in an ALTER TABLE ... ALTER COLUMN is always treated as.

ALTER TABLE YourTable ALTER COLUMN YourColumn VARCHAR (500) NULL;

This behaviour is different from that used for new columns created with ALTER TABLE (or at CREATE TABLE time). There the default nullability depends on the ANSI_NULL_DFLT settings.

Call asynchronous method in constructor?

My preferred approach:

// caution: fire and forget
Task.Run(async () => await someAsyncFunc());

How to load external scripts dynamically in Angular?

If you're using system.js, you can use System.import() at runtime:

export class MyAppComponent {
  constructor(){
    System.import('path/to/your/module').then(refToLoadedModule => {
      refToLoadedModule.someFunction();
    }
  );
}

If you're using webpack, you can take full advantage of its robust code splitting support with require.ensure :

export class MyAppComponent {
  constructor() {
     require.ensure(['path/to/your/module'], require => {
        let yourModule = require('path/to/your/module');
        yourModule.someFunction();
     }); 
  }
}

Newline in string attribute

<TextBlock>
    Stuff on line1 <LineBreak/>
    Stuff on line2
</TextBlock>

not that it's important to know but what you specify between the TextBlock tags is called inline content and goes into the TextBlock.Inlines property which is a InlineCollection and contains items of type Inline. Subclasses of Inline are Run and LineBreak, among others. see TextBlock.Inlines

How to manually force a commit in a @Transactional method?

I know that due to this ugly anonymous inner class usage of TransactionTemplate doesn't look nice, but when for some reason we want to have a test method transactional IMHO it is the most flexible option.

In some cases (it depends on the application type) the best way to use transactions in Spring tests is a turned-off @Transactional on the test methods. Why? Because @Transactional may leads to many false-positive tests. You may look at this sample article to find out details. In such cases TransactionTemplate can be perfect for controlling transaction boundries when we want that control.

The 'Access-Control-Allow-Origin' header contains multiple values

This can also happen of course if you've actually set your Access-Control-Allow-Origin header to have multiple values - For example, a comma separated list of values, which is kind of supported in the RFC but isn't actually supported by most major browsers. Note that the RFC talks about how to allow more than one domain without using '*' as well.

For example, you can get that error in Chrome by using a header like so:

Access-Control-Allow-Origin: http://test.mysite.com, http://test2.mysite.com

This was in Chrome Version 64.0.3282.186 (Official Build) (64-bit)

Note that if you're considering this because of a CDN, and you use Akamai, you may want to note that Akamai wont cache on the server if you use Vary:Origin, the way many suggest to solve this problem.

You'll probably have to change how your cache key is built, using a "Cache ID Modification" response behavior. More details on this issue in this related StackOverflow question

Emulate a 403 error page

I understand you have a scenario with ErrorDocument already defined within your apache conf or .htaccess and want to make those pages appear when manually sending a 4xx status code via php.

Unfortunately this is not possible with common methods because php sends header directly to user's browser (not to Apache web server) whereas ErrorDocument is a display handler for http status generated from Apache.

fatal: ambiguous argument 'origin': unknown revision or path not in the working tree

Sometimes things might be simpler. I came here with the exact issue and tried all the suggestions. But later found that the problem was just the local file path was different and I was on a different folder. :-)

eg -

~/myproject/mygitrepo/app/$ git diff app/TestFile.txt

should have been

~/myproject/mygitrepo/app/$ git diff TestFile.txt

Python setup.py develop vs install

Another thing that people may find useful when using the develop method is the --user option to install without sudo. Ex:

python setup.py develop --user

instead of

sudo python setup.py develop

R: Select values from data table in range

Lots of options here, but one of the easiest to follow is subset. Consider:

> set.seed(43)
> df <- data.frame(name = sample(letters, 100, TRUE), date = sample(1:500, 100, TRUE))
> 
> subset(df, date > 5 & date < 15)
   name date
11    k   10
67    y   12
86    e    8

You can also insert logic directly into the index for your data.frame. The comma separates the rows from columns. We just have to remember that R indexes rows first, then columns. So here we are saying rows with date > 5 & < 15 and then all columns:

df[df$date > 5 & df$date < 15 ,]

I'd also recommend checking out the help pages for subset, ?subset and the logical operators ?"&"

Use jQuery to scroll to the bottom of a div with lots of text

Scrolling with animation:

Your DIV:

<div class='messageScrollArea' style='height: 100px;overflow: auto;'>
      Hello World! Hello World! Hello World! Hello World! Hello World! Hello
      Hello World! Hello World! Hello World! Hello World! Hello World! Hello
      Hello World! Hello World! Hello World! Hello World! Hello World! Hello
</div>

jQuery part:

jQuery(document).ready(function(){       
    var $t = $('.messageScrollArea');
    $t.animate({"scrollTop": $('.messageScrollArea')[0].scrollHeight}, "slow");
});

?http://jsfiddle.net/3Wx3U/

Jackson serialization: ignore empty values (or null)

Also you can try to use

@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)

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

What's default HTML/CSS link color?

According to the official default HTML stylesheet, there is no defined default link color. However, you can find out the default your browser uses by either taking a screenshot and using the pipette tool in any decent graphic editor or using the developer tools of your browser (select an a element, look for computed values>color).

is there a css hack for safari only NOT chrome?

Note: If iOS-only is sufficient (if you're willing to sacrifice Safari desktop), then this works:

    @supports (-webkit-overflow-scrolling: touch) {
    /* CSS specific to iOS devices */ 
    }

npm ERR! Error: EPERM: operation not permitted, rename

These steps solved for me

Go to the package.json file in the file explorer Right click & select Properties. Deselect Read-only. Click Apply

NOTE: (In case if it is already deselected , check and uncheck the read-only once and click Apply)

Accessing Websites through a Different Port?

If website server is listening to a different port, then yes, simply use http://address:port/

If server is not listening to a different port, then obviously you cannot.

Encoding URL query parameters in Java

EDIT: URIUtil is no longer available in more recent versions, better answer at Java - encode URL or by Mr. Sindi in this thread.


URIUtil of Apache httpclient is really useful, although there are some alternatives

URIUtil.encodeQuery(url);

For example, it encodes space as "+" instead of "%20"

Both are perfectly valid in the right context. Although if you really preferred you could issue a string replace.

How do I parse a HTML page with Node.js

You can use the npm modules jsdom and htmlparser to create and parse a DOM in Node.JS.

Other options include:

  • BeautifulSoup for python
  • you can convert you html to xhtml and use XSLT
  • HTMLAgilityPack for .NET
  • CsQuery for .NET (my new favorite)
  • The spidermonkey and rhino JS engines have native E4X support. This may be useful, only if you convert your html to xhtml.

Out of all these options, I prefer using the Node.js option, because it uses the standard W3C DOM accessor methods and I can reuse code on both the client and server. I wish BeautifulSoup's methods were more similar to the W3C dom, and I think converting your HTML to XHTML to write XSLT is just plain sadistic.

How is the 'use strict' statement interpreted in Node.js?

"use strict";

Basically it enables the strict mode.

Strict Mode is a feature that allows you to place a program, or a function, in a "strict" operating context. In strict operating context, the method form binds this to the objects as before. The function form binds this to undefined, not the global set objects.

As per your comments you are telling some differences will be there. But it's your assumption. The Node.js code is nothing but your JavaScript code. All Node.js code are interpreted by the V8 JavaScript engine. The V8 JavaScript Engine is an open source JavaScript engine developed by Google for Chrome web browser.

So, there will be no major difference how "use strict"; is interpreted by the Chrome browser and Node.js.

Please read what is strict mode in JavaScript.

For more information:

  1. Strict mode
  2. ECMAScript 5 Strict mode support in browsers
  3. Strict mode is coming to town
  4. Compatibility table for strict mode
  5. Stack Overflow questions: what does 'use strict' do in JavaScript & what is the reasoning behind it


ECMAScript 6:

ECMAScript 6 Code & strict mode. Following is brief from the specification:

10.2.1 Strict Mode Code

An ECMAScript Script syntactic unit may be processed using either unrestricted or strict mode syntax and semantics. Code is interpreted as strict mode code in the following situations:

  • Global code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive (see 14.1.1).
  • Module code is always strict mode code.
  • All parts of a ClassDeclaration or a ClassExpression are strict mode code.
  • Eval code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive or if the call to eval is a direct eval (see 12.3.4.1) that is contained in strict mode code.
  • Function code is strict mode code if the associated FunctionDeclaration, FunctionExpression, GeneratorDeclaration, GeneratorExpression, MethodDefinition, or ArrowFunction is contained in strict mode code or if the code that produces the value of the function’s [[ECMAScriptCode]] internal slot begins with a Directive Prologue that contains a Use Strict Directive.
  • Function code that is supplied as the arguments to the built-in Function and Generator constructors is strict mode code if the last argument is a String that when processed is a FunctionBody that begins with a Directive Prologue that contains a Use Strict Directive.

Additionally if you are lost on what features are supported by your current version of Node.js, this node.green can help you (leverages from the same data as kangax).

How to enable remote access of mysql in centos?

In case of Allow IP to mysql server linux machine. you can do following command--

 nano /etc/httpd/conf.d/phpMyAdmin.conf  and add Desired IP.

<Directory /usr/share/phpMyAdmin/>
   AddDefaultCharset UTF-8
   Order allow,deny
   allow from all
   <IfModule mod_authz_core.c>
     # Apache 2.4
     <RequireAny>

    Require ip 192.168.9.1(Desired IP)

</RequireAny>
   </IfModule>
 <IfModule !mod_authz_core.c>
     # Apache 2.2
     Order Deny,Allow
     #Allow from All

     Allow from 192.168.9.1(Desired IP)

</IfModule>

And after Update, please restart using following command--

sudo systemctl restart httpd.service

How can I get a collection of keys in a JavaScript dictionary?

Use Object.keys() or shim it in older browsers...

const keys = Object.keys(driversCounter);

If you wanted values, there is Object.values() and if you want key and value, you can use Object.entries(), often paired with Array.prototype.forEach() like this...

Object.entries(driversCounter).forEach(([key, value]) => {
   console.log(key, value);
});

Alternatively, considering your use case, maybe this will do it...

var selectBox, option, prop;

selectBox = document.getElementById("drivers");

for (prop in driversCounter) {
   option = document.createElement("option");
   option.textContent = prop;
   option.value = driversCounter[prop];
   selectBox.add(option);
}

How to fix 'Notice: Undefined index:' in PHP form action

if(isset($_POST['form_field_name'])) {
    $variable_name = $_POST['form_field_name'];
}

When to use static keyword before global variables?

global static variables are initialized at compile-time unlike automatic

How to get index using LINQ?

myCars.TakeWhile(car => !myCondition(car)).Count();

It works! Think about it. The index of the first matching item equals the number of (not matching) item before it.

Story time

I too dislike the horrible standard solution you already suggested in your question. Like the accepted answer I went for a plain old loop although with a slight modification:

public static int FindIndex<T>(this IEnumerable<T> items, Predicate<T> predicate) {
    int index = 0;
    foreach (var item in items) {
        if (predicate(item)) break;
        index++;
    }
    return index;
}

Note that it will return the number of items instead of -1 when there is no match. But let's ignore this minor annoyance for now. In fact the horrible standard solution crashes in that case and I consider returning an index that is out-of-bounds superior.

What happens now is ReSharper telling me Loop can be converted into LINQ-expression. While most of the time the feature worsens readability, this time the result was awe-inspiring. So Kudos to the JetBrains.

Analysis

Pros

  • Concise
  • Combinable with other LINQ
  • Avoids newing anonymous objects
  • Only evaluates the enumerable until the predicate matches for the first time

Therefore I consider it optimal in time and space while remaining readable.

Cons

  • Not quite obvious at first
  • Does not return -1 when there is no match

Of course you can always hide it behind an extension method. And what to do best when there is no match heavily depends on the context.

curl error 18 - transfer closed with outstanding read data remaining

I had the same problem, but managed to fix it by suppressing the 'Expect: 100-continue' header that cURL usually sends (the following is PHP code, but should work similarly with other cURL APIs):

curl_setopt($curl, CURLOPT_HTTPHEADER, array('Expect:'));

By the way, I am sending calls to the HTTP server that is included in the JDK 6 REST stuff, which has all kinds of problems. In this case, it first sends a 100 response, and then with some requests doesn't send the subsequent 200 response correctly.

How to ignore whitespace in a regular expression subject string?

While the accepted answer is technically correct, a more practical approach, if possible, is to just strip whitespace out of both the regular expression and the search string.

If you want to search for "my cats", instead of:

myString.match(/m\s*y\s*c\s*a\*st\s*s\s*/g)

Just do:

myString.replace(/\s*/g,"").match(/mycats/g)

Warning: You can't automate this on the regular expression by just replacing all spaces with empty strings because they may occur in a negation or otherwise make your regular expression invalid.

Do HttpClient and HttpClientHandler have to be disposed between requests?

If you want to dispose of HttpClient, you can if you set it up as a resource pool. And at the end of your application, you dispose your resource pool.

Code:

// Notice that IDisposable is not implemented here!
public interface HttpClientHandle
{
    HttpRequestHeaders DefaultRequestHeaders { get; }
    Uri BaseAddress { get; set; }
    // ...
    // All the other methods from peeking at HttpClient
}

public class HttpClientHander : HttpClient, HttpClientHandle, IDisposable
{
    public static ConditionalWeakTable<Uri, HttpClientHander> _httpClientsPool;
    public static HashSet<Uri> _uris;

    static HttpClientHander()
    {
        _httpClientsPool = new ConditionalWeakTable<Uri, HttpClientHander>();
        _uris = new HashSet<Uri>();
        SetupGlobalPoolFinalizer();
    }

    private DateTime _delayFinalization = DateTime.MinValue;
    private bool _isDisposed = false;

    public static HttpClientHandle GetHttpClientHandle(Uri baseUrl)
    {
        HttpClientHander httpClient = _httpClientsPool.GetOrCreateValue(baseUrl);
        _uris.Add(baseUrl);
        httpClient._delayFinalization = DateTime.MinValue;
        httpClient.BaseAddress = baseUrl;

        return httpClient;
    }

    void IDisposable.Dispose()
    {
        _isDisposed = true;
        GC.SuppressFinalize(this);

        base.Dispose();
    }

    ~HttpClientHander()
    {
        if (_delayFinalization == DateTime.MinValue)
            _delayFinalization = DateTime.UtcNow;
        if (DateTime.UtcNow.Subtract(_delayFinalization) < base.Timeout)
            GC.ReRegisterForFinalize(this);
    }

    private static void SetupGlobalPoolFinalizer()
    {
        AppDomain.CurrentDomain.ProcessExit +=
            (sender, eventArgs) => { FinalizeGlobalPool(); };
    }

    private static void FinalizeGlobalPool()
    {
        foreach (var key in _uris)
        {
            HttpClientHander value = null;
            if (_httpClientsPool.TryGetValue(key, out value))
                try { value.Dispose(); } catch { }
        }

        _uris.Clear();
        _httpClientsPool = null;
    }
}

var handler = HttpClientHander.GetHttpClientHandle(new Uri("base url")).

  • HttpClient, as an interface, can't call Dispose().
  • Dispose() will be called in a delayed fashion by the Garbage Collector. Or when the program cleans up the object through its destructor.
  • Uses Weak References + delayed cleanup logic so it remains in use so long as it is being reused frequently.
  • It only allocates a new HttpClient for each base URL passed to it. Reasons explained by Ohad Schneider answer below. Bad behavior when changing base url.
  • HttpClientHandle allows for Mocking in tests

Function to Calculate a CRC16 Checksum

Here follows a working code to calculate crc16 CCITT. I tested it and the results matched with those provided by http://www.lammertbies.nl/comm/info/crc-calculation.html.

unsigned short crc16(const unsigned char* data_p, unsigned char length){
    unsigned char x;
    unsigned short crc = 0xFFFF;

    while (length--){
        x = crc >> 8 ^ *data_p++;
        x ^= x>>4;
        crc = (crc << 8) ^ ((unsigned short)(x << 12)) ^ ((unsigned short)(x <<5)) ^ ((unsigned short)x);
    }
    return crc;
}

Iterating over arrays in Python 3

You can use

    nditer

Here I calculated no. of positive and negative coefficients in a logistic regression:

b=sentiment_model.coef_
pos_coef=0
neg_coef=0
for i in np.nditer(b):
    if i>0:
    pos_coef=pos_coef+1
    else:
    neg_coef=neg_coef+1
print("no. of positive coefficients is : {}".format(pos_coef))
print("no. of negative coefficients is : {}".format(neg_coef))

Output:

no. of positive coefficients is : 85035
no. of negative coefficients is : 36199

Stop executing further code in Java

Just do:

public void onClick() {
    if(condition == true) {
        return;
    }
    string.setText("This string should not change if condition = true");
}

It's redundant to write if(condition == true), just write if(condition) (This way, for example, you'll not write = by mistake).

Is it possible to install both 32bit and 64bit Java on Windows 7?

You can install multiple Java runtimes under Windows (including Windows 7) as long as each is in their own directory.

For example, if you are running Win 7 64-bit, or Win Server 2008 R2, you may install 32-bit JRE in "C:\Program Files (x86)\Java\jre6" and 64-bit JRE in "C:\Program Files\Java\jre6", and perhaps IBM Java 6 in "C:\Program Files (x86)\IBM\Java60\jre".

The Java Control Panel app theoretically has the ability to manage multiple runtimes: Java tab >> View... button

There are tabs for User and System settings. You can add additional runtimes with Add or Find, but once you have finished adding runtimes and hit OK, you have to hit Apply in the main Java tab frame, which is not as obvious as it could be - otherwise your changes will be lost.

If you have multiple versions installed, only the main version will auto-update. I have not found a solution to this apart from the weak workaround of manually updating whenever I see an auto-update, so I'd love to know if anyone has a fix for that.

Most Java IDEs allow you to select any Java runtime on your machine to build against, but if not using an IDE, you can easily manage this using environment variables in a cmd window. Your PATH and the JAVA_HOME variable determine which runtime is used by tools run from the shell. Set the JAVA_HOME to the jre directory you want and put the bin directory into your path (and remove references to other runtimes) - with IBM you may need to add multiple bin directories. This is pretty much all the set up that the default system Java does. You can also set CLASSPATH, ANT_HOME, MAVEN_HOME, etc. to unique values to match your runtime.

How to add key,value pair to dictionary?

Add a key, value pair to dictionary

aDict = {}
aDict[key] = value

What do you mean by dynamic addition.

Difference between add(), replace(), and addToBackStack()

One more important difference between add and replace is this:

replace removes the existing fragment and adds a new fragment. This means when you press back button the fragment that got replaced will be created with its onCreateView being invoked. Whereas add retains the existing fragments and adds a new fragment that means existing fragment will be active and they wont be in 'paused' state hence when a back button is pressed onCreateView is not called for the existing fragment(the fragment which was there before new fragment was added).

In terms of fragment's life cycle events onPause, onResume, onCreateView and other life cycle events will be invoked in case of replace but they wont be invoked in case of add.

Edit: One should be careful if she is using some kind of event bus library like Greenrobot's Eventbus and reusing the same fragment to stack the fragment on top of other via add. In this scenario, even though you follow the best practice and register the event bus in onResume and unregister in onPause, event bus would still be active in each instance of the added fragment as add fragment wont call either of these fragment life cycle methods. As a result event bus listener in each active instance of the fragment would process the same event which may not be what you want.

How do ACID and database transactions work?

ACID are desirable properties of any transaction processing engine.

A DBMS is (if it is any good) a particular kind of transaction processing engine that exposes, usually to a very large extent but not quite entirely, those properties.

But other engines exist that can also expose those properties. The kind of software that used to be called "TP monitors" being a case in point (nowadays' equivalent mostly being web servers).

Such TP monitors can access resources other than a DBMS (e.g. a printer), and still guarantee ACID toward their users. As an example of what ACID might mean when a printer is involved in a transaction:

  • Atomicity: an entire document gets printed or nothing at all
  • Consistency: at end-of-transaction, the paper feed is positioned at top-of-page
  • Isolation: no two documents get mixed up while printing
  • Durability: the printer can guarantee that it was not "printing" with empty cartridges.

SimpleDateFormat and locale based format string

Localization of date string:

Based on redsonic's post:

private String localizeDate(String inputdate, Locale locale) { 

    Date date = new Date();
    SimpleDateFormat dateFormatCN = new SimpleDateFormat("dd-MMM-yyyy", locale);       
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");


    try {
        date = dateFormat.parse(inputdate);
    } catch (ParseException e) {
        log.warn("Input date was not correct. Can not localize it.");
        return inputdate;
    }
    return dateFormatCN.format(date);
}

String localizedDate = localizeDate("05-Sep-2013", new Locale("zh","CN"));

will be like 05-??-2013

Get POST data in C#/ASP.NET

The following is OK in HTML4, but not in XHTML. Check your editor.

<input type=button value="Submit" />

Run task only if host does not belong to a group

You can set a control variable in vars files located in group_vars/ or directly in hosts file like this:

[vagrant:vars]
test_var=true

[location-1]
192.168.33.10 hostname=apollo

[location-2]
192.168.33.20 hostname=zeus

[vagrant:children]
location-1
location-2

And run tasks like this:

- name: "test"
  command: "echo {{test_var}}"
  when: test_var is defined and test_var

SQL Server PRINT SELECT (Print a select query result)?

If you wish (like me) to have results containing mulitple rows of various SELECT queries "labelled" and can't manage this within the constraints of the PRINT statement in concert with the Messages tab you could turn it around and simply add messages to the Results tab per the below:

SELECT 'Results from scenario 1'
SELECT
    *
FROM tblSample

enter image description here

Retrieving Data from SQL Using pyodbc

you could try using Pandas to retrieve information and get it as dataframe

import pyodbc as cnn
import pandas as pd

cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=SQLSRV01;DATABASE=DATABASE;UID=USER;PWD=PASSWORD')

# Copy to Clipboard for paste in Excel sheet
def copia (argumento):
    df=pd.DataFrame(argumento)
    df.to_clipboard(index=False,header=True)


tableResult = pd.read_sql("SELECT * FROM YOURTABLE", cnxn) 

# Copy to Clipboard
copia(tableResult)

# Or create a Excel file with the results
df=pd.DataFrame(tableResult)
df.to_excel("FileExample.xlsx",sheet_name='Results')

I hope this helps! Cheers!

SQL Server: Get data for only the past year

For some reason none of the results above worked for me.

This selects the last 365 days.

 SELECT ... From ... WHERE date BETWEEN CURDATE() - INTERVAL 1 YEAR AND CURDATE()

Counter exit code 139 when running, but gdb make it through

this error is also caused by null pointer reference. if you are using a pointer who is not initialized then it causes this error.

to check either a pointer is initialized or not you can try something like

Class *pointer = new Class();
if(pointer!=nullptr){
    pointer->myFunction();
}

console.log not working in Angular2 Component (Typescript)

Also try to update your browser because Angular need latest browser. check: https://angular.io/guide/browser-support

I fixed console.log issue after updating latest browser.

How to make FileFilter in java?

Another simple example:

public static void listFilesInDirectory(String pathString) {
  // A local class (a class defined inside a block, here a method).
  class MyFilter implements FileFilter {
    @Override
    public boolean accept(File file) {
      return !file.isHidden() && file.getName().endsWith(".txt");
    }
  }

  File directory = new File(pathString);
  File[] files = directory.listFiles(new MyFilter());

  for (File fileLoop : files) {
    System.out.println(fileLoop.getName());
  }
}

// Call it
listFilesInDirectory("C:\\Users\\John\\Documents\\zTemp");

// Output
Cool.txt
RedditKinsey.txt
...

write a shell script to ssh to a remote machine and execute commands

If you are able to write Perl code, then you should consider using Net::OpenSSH::Parallel.

You would be able to describe the actions that have to be run in every host in a declarative manner and the module will take care of all the scary details. Running commands through sudo is also supported.

Checking if a variable is defined?

defined?(your_var) will work. Depending on what you're doing you can also do something like your_var.nil?

adding x and y axis labels in ggplot2

[Note: edited to modernize ggplot syntax]

Your example is not reproducible since there is no ex1221new (there is an ex1221 in Sleuth2, so I guess that is what you meant). Also, you don't need (and shouldn't) pull columns out to send to ggplot. One advantage is that ggplot works with data.frames directly.

You can set the labels with xlab() and ylab(), or make it part of the scale_*.* call.

library("Sleuth2")
library("ggplot2")
ggplot(ex1221, aes(Discharge, Area)) +
  geom_point(aes(size=NO3)) + 
  scale_size_area() + 
  xlab("My x label") +
  ylab("My y label") +
  ggtitle("Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")

enter image description here

ggplot(ex1221, aes(Discharge, Area)) +
  geom_point(aes(size=NO3)) + 
  scale_size_area("Nitrogen") + 
  scale_x_continuous("My x label") +
  scale_y_continuous("My y label") +
  ggtitle("Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")

enter image description here

An alternate way to specify just labels (handy if you are not changing any other aspects of the scales) is using the labs function

ggplot(ex1221, aes(Discharge, Area)) +
  geom_point(aes(size=NO3)) + 
  scale_size_area() + 
  labs(size= "Nitrogen",
       x = "My x label",
       y = "My y label",
       title = "Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")

which gives an identical figure to the one above.

Duplicate symbols for architecture x86_64 under Xcode

This occurred on me when I accepted "recommended settings" pop-up on a project that I develop two years ago in Objective-C.

The problem was that when you accepted the "recommended settings" update, Xcode automatically changed or added some build settings, including GCC_NO_COMMON_BLOCKS = YES;.

This made the build failed with the duplicate symbol error in my updated project. So I changed No Common Block to NO in my build settings and the error was gone.

Detecting endianness programmatically in a C++ program

As pointed out by Coriiander, most (if not all) of those codes here will be optimized away at compilation time, so the generated binaries won't check "endianness" at run time.

It has been observed that a given executable shouldn't run in two different byte orders, but I have no idea if that is always the case, and it seems like a hack to me checking at compilation time. So I coded this function:

#include <stdint.h>

int* _BE = 0;

int is_big_endian() {
    if (_BE == 0) {
        uint16_t* teste = (uint16_t*)malloc(4);
        *teste = (*teste & 0x01FE) | 0x0100;
        uint8_t teste2 = ((uint8_t*) teste)[0];
        free(teste);
        _BE = (int*)malloc(sizeof(int));
        *_BE = (0x01 == teste2);
    }
    return *_BE;
}

MinGW wasn't able to optimize this code, even though it does optimize the other codes here away. I believe that is because I leave the "random" value that was alocated on the smaller byte memory as it was (at least 7 of its bits), so the compiler can't know what that random value is and it doesn't optimize the function away.

I've also coded the function so that the check is only performed once, and the return value is stored for next tests.

to_string is not a member of std, says g++ (mingw)

in codeblocks go to setting -> compiler setting -> compiler flag -> select std c++11 done. I had the same problem ... now it's working !

java IO Exception: Stream Closed

You're calling writer.close(); after you've done writing to it. Once a stream is closed, it can not be written to again. Usually, the way I go about implementing this is by moving the close out of the write to method.

public void writeToFile(){
    String file_text= pedStatusText + "     " + gatesStatus + "     " + DrawBridgeStatusText;
    try {
        writer.write(file_text);
        writer.flush();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

And add a method cleanUp to close the stream.

public void cleanUp() {
     writer.close();
}

This means that you have the responsibility to make sure that you're calling cleanUp when you're done writing to the file. Failure to do this will result in memory leaks and resource locking.

EDIT: You can create a new stream each time you want to write to the file, by moving writer into the writeToFile() method..

 public void writeToFile() {
    FileWriter writer = new FileWriter("status.txt", true);
    // ... Write to the file.

    writer.close();
 }

How to change the application launcher icon on Flutter?

You have to replace the Flutter icon files with images of your own. This site will help you turn your png into launcher icons of various sizes:

https://romannurik.github.io/AndroidAssetStudio/icons-launcher.html

Run parallel multiple commands at once in the same terminal

This bash script is for N parallel threads. Each argument is a command.

trap will kill all subprocesses when SIGINT is catched.
wait $PID_LIST is waiting each process to complete. When all processes have completed, the program exits.

#!/bin/bash

for cmd in "$@"; do {
  echo "Process \"$cmd\" started";
  $cmd & pid=$!
  PID_LIST+=" $pid";
} done

trap "kill $PID_LIST" SIGINT

echo "Parallel processes have started";

wait $PID_LIST

echo
echo "All processes have completed";

Save this script as parallel_commands and make it executable.
This is how to use this script:

parallel_commands "cmd arg0 arg1 arg2" "other_cmd arg0 arg2 arg3"

Example:

parallel_commands "sleep 1" "sleep 2" "sleep 3" "sleep 4"

Start 4 parallel sleep and waits until "sleep 4" finishes.