Programs & Examples On #Ruby cocoa

What's with the dollar sign ($"string")

It's the new feature in C# 6 called Interpolated Strings.

The easiest way to understand it is: an interpolated string expression creates a string by replacing the contained expressions with the ToString representations of the expressions' results.

For more details about this, please take a look at MSDN.

Now, think a little bit more about it. Why this feature is great?

For example, you have class Point:

public class Point
{
    public int X { get; set; }

    public int Y { get; set; }
}

Create 2 instances:

var p1 = new Point { X = 5, Y = 10 };
var p2 = new Point { X = 7, Y = 3 };

Now, you want to output it to the screen. The 2 ways that you usually use:

Console.WriteLine("The area of interest is bounded by (" + p1.X + "," + p1.Y + ") and (" + p2.X + "," + p2.Y + ")");

As you can see, concatenating string like this makes the code hard to read and error-prone. You may use string.Format() to make it nicer:

Console.WriteLine(string.Format("The area of interest is bounded by({0},{1}) and ({2},{3})", p1.X, p1.Y, p2.X, p2.Y));

This creates a new problem:

  1. You have to maintain the number of arguments and index yourself. If the number of arguments and index are not the same, it will generate a runtime error.

For those reasons, we should use new feature:

Console.WriteLine($"The area of interest is bounded by ({p1.X},{p1.Y}) and ({p2.X},{p2.Y})");

The compiler now maintains the placeholders for you so you don’t have to worry about indexing the right argument because you simply place it right there in the string.

For the full post, please read this blog.

Laravel view not found exception

In my case I was calling View::make('User/index'), where in fact my view was in user directory and it was called index.blade.php. Ergo after I changed it to View@make('user.index') all started working.

How does an SSL certificate chain bundle work?

You need to use the openssl pkcs12 -export -chain -in server.crt -CAfile ...

See https://www.openssl.org/docs/apps/pkcs12.html

Detect if range is empty

Dim cel As Range, hasNoData As Boolean

    hasNoData = True
    For Each cel In Selection
        hasNoData = hasNoData And IsEmpty(cel)
    Next

This will return True if no cells in Selection contains any data. For a specific range, just substitute RANGE(...) for Selection.

Checking for NULL pointer in C/C++

Most compilers I've used will at least warn on the if assignment without further syntax sugar, so I don't buy that argument. That said, I've used both professionally and have no preference for either. The == NULL is definitely clearer though in my opinion.

No newline after div?

div.noWrap {
    display: inline;
    }

How to create range in Swift?

Use like this

var start = str.startIndex // Start at the string's start index
var end = advance(str.startIndex, 5) // Take start index and advance 5 characters forward
var range: Range<String.Index> = Range<String.Index>(start: start,end: end)

let firstFiveDigit =  str.substringWithRange(range)

print(firstFiveDigit)

Output : Hello

Checking if a field contains a string

If your regex includes a variable, make sure to escape it.

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}

This can be used like this

new RegExp(escapeRegExp(searchString), 'i')

Or in a mongoDb query like this

{ '$regex': escapeRegExp(searchString) }

Posted same comment here

Cannot set some HTTP headers when using System.Net.WebRequest

I ran into this problem with a custom web client. I think people may be getting confused because of multiple ways to do this. When using WebRequest.Create() you can cast to an HttpWebRequest and use the property to add or modify a header. When using a WebHeaderCollection you may use the .Add("referer","my_url").

Ex 1

WebClient client = new WebClient();
client.Headers.Add("referer", "http://stackoverflow.com");
client.Headers.Add("user-agent", "Mozilla/5.0");

Ex 2

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Referer = "http://stackoverflow.com";
request.UserAgent = "Mozilla/5.0";
response = (HttpWebResponse)request.GetResponse();

Converting a date string to a DateTime object using Joda Time library

Your format is not the expected ISO format, you should try

DateTimeFormatter format = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss");
DateTime time = format.parseDateTime("04/02/2011 20:27:05");

Can I mask an input text in a bat file?

Up to XP and Server 2003, you can make use of another included tool (VBScript) - the following two scripts do the job you want.

First, getpwd.cmd:

@echo off
<nul: set /p passwd=Password: 
for /f "delims=" %%i in ('cscript /nologo getpwd.vbs') do set passwd=%%i
echo.

Then, getpwd.vbs:

Set oScriptPW = CreateObject("ScriptPW.Password")
strPassword = oScriptPW.GetPassword()
Wscript.StdOut.WriteLine strPassword

The getpwd.vbs simply uses the password object to input the password from the user and then print it to standard output (the next paragraph will explain why that doesn't show up in the terminal).

The getpwd.cmd command script is a bit trickier but it basically works as follows.

The effect of the "<nul: set /p passwd=Password: " command is to output the prompt with no trailing newline character - it's a sneaky way to emulate the "echo -n" command from the bash shell. It sets passwd to an empty string as an irrelevant side effect and doesn't wait for input since it's taking its input from the nul: device.

The "for /f "delims=" %%i in ('cscript /nologo getpwd.vbs') do set passwd=%%i" statement is the trickiest bit. It runs the VBScript with no Microsoft "advertising", so that the only line output is the password (from the VBscript "Wscript.StdOut.WriteLine strPassword".

Setting the delimiters to nothing is required to capture an entire input line with spaces, otherwise you just get the first word. The "for ... do set ..." bit sets passwd to be the actual password output from the VBScript.

Then we echo a blank line (to terminate the "Password: " line) and the password will be in the passwd environment variable after the code has run.


Now, as mentioned, scriptpw.dll is available only up to XP/2003. In order to rectify this, you can simply copy the scriptpw.dll file from the Windows\System32 folder of an XP/2003 system to the Winnt\System32 or Windows\System32 folder on your own system. Once the DLL has been copied, you will need to register it by running:

regsvr32 scriptpw.dll

To successfully register the DLL on Vista and later, you will need administrator privileges. I haven't examined the legality of such a move so cave lector.


If you're not overly keen on trying to track down and register older DLL files (for convenience or legal reasons), there is another way. Later versions of Windows (the ones that don't have the required DLL) should have Powershell available to you.

And, in fact, you really should consider upgrading your scripts to use it fully since it's a much more capable scripting language than cmd.exe. However, if you want to keep the bulk of your code as cmd.exe scripts (such as if you have a lot of code that you don't want to convert), you can use the same trick.

First, modify the cmd script so it calls Powershell rather than CScript:

@echo off
for /f "delims=" %%i in ('powershell -file getpwd.ps1') do set passwd=%%i

The Powershell script is equally simple:

$password = Read-Host "Enter password" -AsSecureString
$password = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($password)
$password = [Runtime.InteropServices.Marshal]::PtrToStringAuto($password)
echo $password

although with some marshalling to get the actual password text.

Remember that, to run local unsigned Powershell scripts on your machine, you may need to modify the execution policy from the (draconian, though very safe) default, with something like:

set-executionpolicy remotesigned

from within Powershell itself.

How line ending conversions work with git core.autocrlf between different operating systems

core.autocrlf value does not depend on OS type but on Windows default value is true and for Linux - input. I explored 3 possible values for commit and checkout cases and this is the resulting table:

+------------------------------------------------------------+
¦ core.autocrlf ¦     false    ¦     input    ¦     true     ¦
¦---------------+--------------+--------------+--------------¦
¦               ¦ LF   => LF   ¦ LF   => LF   ¦ LF   => LF   ¦
¦ git commit    ¦ CR   => CR   ¦ CR   => CR   ¦ CR   => CR   ¦
¦               ¦ CRLF => CRLF ¦ CRLF => LF   ¦ CRLF => LF   ¦
¦---------------+--------------+--------------+--------------¦
¦               ¦ LF   => LF   ¦ LF   => LF   ¦ LF   => CRLF ¦
¦ git checkout  ¦ CR   => CR   ¦ CR   => CR   ¦ CR   => CR   ¦
¦               ¦ CRLF => CRLF ¦ CRLF => CRLF ¦ CRLF => CRLF ¦
+------------------------------------------------------------+

Add JavaScript object to JavaScript object

As my first object is a native javascript object (used like a list of objects), push didn't work in my escenario, but I resolved it by adding new key as following:

MyObjList['newKey'] = obj;

In addition to this, may be usefull to know how to delete same object inserted before:

delete MyObjList['newKey'][id];

Hope it helps someone as it helped me;

Unzipping files in Python

try this :


import zipfile
def un_zipFiles(path):
    files=os.listdir(path)
    for file in files:
        if file.endswith('.zip'):
            filePath=path+'/'+file
            zip_file = zipfile.ZipFile(filePath)
            for names in zip_file.namelist():
                zip_file.extract(names,path)
            zip_file.close() 

path : unzip file's path

How can I test an AngularJS service from the console?

@JustGoscha's answer is spot on, but that's a lot to type when I want access, so I added this to the bottom of my app.js. Then all I have to type is x = getSrv('$http') to get the http service.

// @if DEBUG
function getSrv(name, element) {
    element = element || '*[ng-app]';
    return angular.element(element).injector().get(name);
}
// @endif

It adds it to the global scope but only in debug mode. I put it inside the @if DEBUG so that I don't end up with it in the production code. I use this method to remove debug code from prouduction builds.

text flowing out of div

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

What's the "Content-Length" field in HTTP header?

The Content-Length entity-header field indicates the size of the entity-body, in decimal number of OCTETs, sent to the recipient or, in the case of the HEAD method, the size of the entity-body that would have been sent had the request been a GET.

Content-Length = "Content-Length" ":" 1*DIGIT

An example is

Content-Length: 1024

Applications SHOULD use this field to indicate the transfer-length of the message-body.

In PHP you would use something like this.

header("Content-Length: ".filesize($filename));

In case of "Content-Type: application/x-www-form-urlencoded" the encoded data is sent to the processing agent designated so you can set the length or size of the data you are going to post.

How do you rotate a two dimensional array?

Great answers but for those who are looking for a DRY JavaScript code for this - both +90 Degrees and -90 Degrees:

_x000D_
_x000D_
          // Input: 1 2 3_x000D_
          //        4 5 6_x000D_
          //        7 8 9_x000D_
_x000D_
          // Transpose: _x000D_
          //       1 4 7_x000D_
          //       2 5 8_x000D_
          //       3 6 9_x000D_
_x000D_
          // Output: _x000D_
          // +90 Degree:_x000D_
          //       7 4 1_x000D_
          //       8 5 2_x000D_
          //       9 6 3_x000D_
_x000D_
          // -90 Degree:_x000D_
          //      3 6 9_x000D_
          //      2 5 8_x000D_
          //      1 4 7_x000D_
_x000D_
          // Rotate +90_x000D_
         function rotate90(matrix) {_x000D_
_x000D_
           matrix = transpose(matrix);_x000D_
           matrix.map(function(array) {_x000D_
             array.reverse();_x000D_
           });_x000D_
_x000D_
           return matrix;_x000D_
         }_x000D_
_x000D_
          // Rotate -90_x000D_
         function counterRotate90(matrix) {_x000D_
           var result = createEmptyMatrix(matrix.length);_x000D_
           matrix = transpose(matrix);_x000D_
           var counter = 0;_x000D_
_x000D_
           for (var i = matrix.length - 1; i >= 0; i--) {_x000D_
             result[counter] = matrix[i];_x000D_
             counter++;_x000D_
           }_x000D_
_x000D_
           return result;_x000D_
         }_x000D_
_x000D_
          // Create empty matrix_x000D_
         function createEmptyMatrix(len) {_x000D_
           var result = new Array();_x000D_
           for (var i = 0; i < len; i++) {_x000D_
             result.push([]);_x000D_
           }_x000D_
           return result;_x000D_
         }_x000D_
_x000D_
          // Transpose the matrix_x000D_
         function transpose(matrix) {_x000D_
           // make empty array_x000D_
           var len = matrix.length;_x000D_
           var result = createEmptyMatrix(len);_x000D_
_x000D_
           for (var i = 0; i < matrix.length; i++) {_x000D_
             for (var j = 0; j < matrix[i].length; j++) {_x000D_
               var temp = matrix[i][j];_x000D_
               result[j][i] = temp;_x000D_
             }_x000D_
           }_x000D_
           return result;_x000D_
         }_x000D_
_x000D_
_x000D_
_x000D_
          // Test Cases_x000D_
         var array1 = [_x000D_
           [1, 2],_x000D_
           [3, 4]_x000D_
         ];_x000D_
         var array2 = [_x000D_
           [1, 2, 3],_x000D_
           [4, 5, 6],_x000D_
           [7, 8, 9]_x000D_
         ];_x000D_
         var array3 = [_x000D_
           [1, 2, 3, 4],_x000D_
           [5, 6, 7, 8],_x000D_
           [9, 10, 11, 12],_x000D_
           [13, 14, 15, 16]_x000D_
         ];_x000D_
_x000D_
          // +90 degress Rotation Tests_x000D_
_x000D_
         var test1 = rotate90(array1);_x000D_
         var test2 = rotate90(array2);_x000D_
         var test3 = rotate90(array3);_x000D_
         console.log(test1);_x000D_
         console.log(test2);_x000D_
         console.log(test3);_x000D_
_x000D_
          // -90 degress Rotation Tests_x000D_
         var test1 = counterRotate90(array1);_x000D_
         var test2 = counterRotate90(array2);_x000D_
         var test3 = counterRotate90(array3);_x000D_
         console.log(test1);_x000D_
         console.log(test2);_x000D_
         console.log(test3);
_x000D_
_x000D_
_x000D_

Datatype for storing ip address in SQL Server

sys.dm_exec_connections uses varchar(48) after SQL Server 2005 SP1. Sounds good enough for me especially if you want to use it compare to your value.

Realistically, you won't see IPv6 as mainstream for a while yet, so I'd prefer the 4 tinyint route. Saying that, I'm using varchar(48) because I have to use sys.dm_exec_connections...

Otherwise. Mark Redman's answer mentions a previous SO debate question.

X-Frame-Options on apache

This worked for me on all browsers:

  1. Created one page with all my javascript
  2. Created a 2nd page on the same server and embedded the first page using the object tag.
  3. On my third party site I used the Object tag to embed the 2nd page.
  4. Created a .htaccess file on the original server in the public_html folder and put Header unset X-Frame-Options in it.

C#, Looping through dataset and show each record from a dataset column

I believe you intended it more this way:

foreach (DataTable table in ds.Tables)
{
    foreach (DataRow dr in table.Rows)
    {
        DateTime TaskStart = DateTime.Parse(dr["TaskStart"].ToString());
        TaskStart.ToString("dd-MMMM-yyyy");
        rpt.SetParameterValue("TaskStartDate", TaskStart);
    }
}

You always accessed your first row in your dataset.

How do I specify different Layouts in the ASP.NET MVC 3 razor ViewStart file?

You could put a _ViewStart.cshtml file inside the /Views/Public folder which would override the default one in the /Views folder and specify the desired layout:

@{
    Layout = "~/Views/Shared/_PublicLayout.cshtml";
}

By analogy you could put another _ViewStart.cshtml file inside the /Views/Staff folder with:

@{
    Layout = "~/Views/Shared/_StaffLayout.cshtml";
}

You could also specify which layout should be used when returning a view inside a controller action but that's per action:

return View("Index", "~/Views/Shared/_StaffLayout.cshtml", someViewModel);

Yet another possibility is a custom action filter which would override the layout. As you can see many possibilities to achieve this. Up to you to choose which one fits best in your scenario.


UPDATE:

As requested in the comments section here's an example of an action filter which would choose a master page:

public class LayoutInjecterAttribute : ActionFilterAttribute
{
    private readonly string _masterName;
    public LayoutInjecterAttribute(string masterName)
    {
        _masterName = masterName;
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        base.OnActionExecuted(filterContext);
        var result = filterContext.Result as ViewResult;
        if (result != null)
        {
            result.MasterName = _masterName;
        }
    }
}

and then decorate a controller or an action with this custom attribute specifying the layout you want:

[LayoutInjecter("_PublicLayout")]
public ActionResult Index()
{
    return View();
}

Install pdo for postgres Ubuntu

Try the packaged pecl version instead (the advantage of the packaged installs is that they're easier to upgrade):

apt-get install php5-dev
pecl install pdo
pecl install pdo_pgsql

or, if you just need a driver for PHP, but that it doesn't have to be the PDO one:

apt-get install php5-pgsql

Otherwise, that message most likely means you need to install a more recent libpq package. You can check which version you have by running:

dpkg -s libpq-dev

Android ImageButton with a selected state?

Try this:

 <item
   android:state_focused="true"
   android:state_enabled="true"
   android:drawable="@drawable/map_toolbar_details_selected" />

Also for colors i had success with

<selector
        xmlns:android="http://schemas.android.com/apk/res/android">
        <item
            android:state_selected="true"

            android:color="@color/primary_color" />
        <item
            android:color="@color/secondary_color" />
</selector>

How to iterate through two lists in parallel?

Python 3

for f, b in zip(foo, bar):
    print(f, b)

zip stops when the shorter of foo or bar stops.

In Python 3, zip returns an iterator of tuples, like itertools.izip in Python2. To get a list of tuples, use list(zip(foo, bar)). And to zip until both iterators are exhausted, you would use itertools.zip_longest.

Python 2

In Python 2, zip returns a list of tuples. This is fine when foo and bar are not massive. If they are both massive then forming zip(foo,bar) is an unnecessarily massive temporary variable, and should be replaced by itertools.izip or itertools.izip_longest, which returns an iterator instead of a list.

import itertools
for f,b in itertools.izip(foo,bar):
    print(f,b)
for f,b in itertools.izip_longest(foo,bar):
    print(f,b)

izip stops when either foo or bar is exhausted. izip_longest stops when both foo and bar are exhausted. When the shorter iterator(s) are exhausted, izip_longest yields a tuple with None in the position corresponding to that iterator. You can also set a different fillvalue besides None if you wish. See here for the full story.


Note also that zip and its zip-like brethen can accept an arbitrary number of iterables as arguments. For example,

for num, cheese, color in zip([1,2,3], ['manchego', 'stilton', 'brie'], 
                              ['red', 'blue', 'green']):
    print('{} {} {}'.format(num, color, cheese))

prints

1 red manchego
2 blue stilton
3 green brie

Url to a google maps page to show a pin given a latitude / longitude?

From my notes:

http://maps.google.com/maps?q=37.4185N+122.08774W+(label)&ll=37.419731,-122.088715&spn=0.004250,0.011579&t=h&iwloc=A&hl=en

Which parses like this:

    q=latN+lonW+(label)     location of teardrop

    t=k             keyhole (satelite map)
    t=h             hybrid

    ll=lat,-lon     center of map
    spn=w.w,h.h     span of map, degrees

iwloc has something to do with the info window. hl is obviously language.

See also: http://www.seomoz.org/ugc/everything-you-never-wanted-to-know-about-google-maps-parameters

Open JQuery Datepicker by clicking on an image w/ no input field

The jQuery documentation says that the datePicker needs to be attached to a SPAN or a DIV when it is not associated with an input box. You could do something like this:

<img src='someimage.gif' id="datepickerImage" />
<div id="datepicker"></div>

<script type="text/javascript">
 $(document).ready(function() {
    $("#datepicker").datepicker({
            changeMonth: true,
            changeYear: true,
    })
    .hide()
    .click(function() {
      $(this).hide();
    });

    $("#datepickerImage").click(function() {
       $("#datepicker").show(); 
    });
 });
</script>

Recursive directory listing in DOS

You can use:

dir /s

If you need the list without all the header/footer information try this:

dir /s /b

(For sure this will work for DOS 6 and later; might have worked prior to that, but I can't recall.)

How to get GET (query string) variables in Express.js on Node.js?

If you ever need to send GET request to an IP as well as a Domain (Other answers did not mention you can specify a port variable), you can make use of this function:

function getCode(host, port, path, queryString) {
    console.log("(" + host + ":" + port + path + ")" + "Running httpHelper.getCode()")

    // Construct url and query string
    const requestUrl = url.parse(url.format({
        protocol: 'http',
        hostname: host,
        pathname: path,
        port: port,
        query: queryString
    }));

    console.log("(" + host + path + ")" + "Sending GET request")
    // Send request
    console.log(url.format(requestUrl))
    http.get(url.format(requestUrl), (resp) => {
        let data = '';

        // A chunk of data has been received.
        resp.on('data', (chunk) => {
            console.log("GET chunk: " + chunk);
            data += chunk;
        });

        // The whole response has been received. Print out the result.
        resp.on('end', () => {
            console.log("GET end of response: " + data);
        });

    }).on("error", (err) => {
        console.log("GET Error: " + err);
    });
}

Don't miss requiring modules at the top of your file:

http = require("http");
url = require('url')

Also bare in mind that you may use https module for communicating over secured domains and ssl. so these two lines would change:

https = require("https");
...
https.get(url.format(requestUrl), (resp) => { ......

Filtering by Multiple Specific Model Properties in AngularJS (in OR relationship)

I inspired myself from @maxisam's answer and created my own sort function and I'd though I'd share it (cuz I'm bored).

Situation I want to filter through an array of cars. The selected properties to filter are name, year, price and km. The property price and km are numbers (hence the use of .toString). I also want to control for uppercase letters (hence .toLowerCase). Also I want to be able to split up my filter query into different words (e.g. given the filter 2006 Acura, it finds matches 2006 with the year and Acura with the name).

Function I pass to filter

        var attrs = [car.name.toLowerCase(), car.year, car.price.toString(), car.km.toString()],
            filters = $scope.tableOpts.filter.toLowerCase().split(' '),
            isStringInArray = function (string, array){
                for (var j=0;j<array.length;j++){
                    if (array[j].indexOf(string)!==-1){return true;}
                }
                return false;
            };

        for (var i=0;i<filters.length;i++){
            if (!isStringInArray(filters[i], attrs)){return false;}
        }
        return true;
    };

Working Soap client example

String send = 
    "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
    "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\n" +
    "        <soap:Body>\n" +
    "        </soap:Body>\n" +
    "</soap:Envelope>";

private static String getResponse(String send) throws Exception {
    String url = "https://api.comscore.com/KeyMeasures.asmx"; //endpoint
    String result = "";
    String username="user_name";
    String password="pass_word";
    String[] command = {"curl", "-u", username+":"+password ,"-X", "POST", "-H", "Content-Type: text/xml", "-d", send, url};
    ProcessBuilder process = new ProcessBuilder(command); 
    Process p;
    try {
        p = process.start();
        BufferedReader reader =  new BufferedReader(new InputStreamReader(p.getInputStream()));
        StringBuilder builder = new StringBuilder();
        String line = null;
        while ( (line = reader.readLine()) != null) {
                builder.append(line);
                builder.append(System.getProperty("line.separator"));
        }
        result = builder.toString();
    }
    catch (IOException e)
    {   System.out.print("error");
        e.printStackTrace();
    }

    return result;
}

header('HTTP/1.0 404 Not Found'); not doing anything

Another reason may be if you add any html tag before this redirect. Look carefully, you may left DOCTYPE or any html comment before this line.

How do I stretch an image to fit the whole background (100% height x 100% width) in Flutter?

I think that for your purpose Flex could work better than Container():

new Flex(
    direction: Axis.vertical,
    children: <Widget>[
      Image.asset(asset.background)
    ],
   )

CodeIgniter: How to use WHERE clause and OR clause

You can use or_where() for that - example from the CI docs:

$this->db->where('name !=', $name);

$this->db->or_where('id >', $id); 

// Produces: WHERE name != 'Joe' OR id > 50

Javascript Debugging line by line using Google Chrome

Assuming you're running on a Windows machine...

  1. Hit the F12 key
  2. Select the Scripts, or Sources, tab in the developer tools
  3. Click the little folder icon in the top level
  4. Select your JavaScript file
  5. Add a breakpoint by clicking on the line number on the left (adds a little blue marker)
  6. Execute your JavaScript

Then during execution debugging you can do a handful of stepping motions...

  • F8 Continue: Will continue until the next breakpoint
  • F10 Step over: Steps over next function call (won't enter the library)
  • F11 Step into: Steps into the next function call (will enter the library)
  • Shift + F11 Step out: Steps out of the current function

Update

After reading your updated post; to debug your code I would recommend temporarily using the jQuery Development Source Code. Although this doesn't directly solve your problem, it will allow you to debug more easily. For what you're trying to achieve I believe you'll need to step-in to the library, so hopefully the production code should help you decipher what's happening.

Calling a java method from c++ in Android

If it's an object method, you need to pass the object to CallObjectMethod:

jobject result = env->CallObjectMethod(obj, messageMe, jstr);

What you were doing was the equivalent of jstr.messageMe().

Since your is a void method, you should call:

env->CallVoidMethod(obj, messageMe, jstr);

If you want to return a result, you need to change your JNI signature (the ()V means a method of void return type) and also the return type in your Java code.

How to check if internet connection is present in Java?

The code you basically provided, plus a call to connect should be sufficient. So yeah, it could be that just Google's not available but some other site you need to contact is on but how likely is that? Also, this code should only execute when you actually fail to access your external resource (in a catch block to try and figure out what the cause of the failure was) so I'd say that if both your external resource of interest and Google are not available chances are you have a net connectivity problem.

private static boolean netIsAvailable() {
    try {
        final URL url = new URL("http://www.google.com");
        final URLConnection conn = url.openConnection();
        conn.connect();
        conn.getInputStream().close();
        return true;
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        return false;
    }
}

apache ProxyPass: how to preserve original IP address

If you are using Apache reverse proxy for serving an app running on a localhost port you must add a location to your vhost.

<Location />            
   ProxyPass http://localhost:1339/ retry=0
   ProxyPassReverse http://localhost:1339/
   ProxyPreserveHost On
   ProxyErrorOverride Off
</Location>

To get the IP address have following options

console.log(">>>", req.ip);// this works fine for me returned a valid ip address 
console.log(">>>", req.headers['x-forwarded-for'] );// returned a valid IP address 
console.log(">>>", req.headers['X-Real-IP'] ); // did not work returned undefined 
console.log(">>>", req.connection.remoteAddress );// returned the loopback IP address 

So either use req.ip or req.headers['x-forwarded-for']

Bind class toggle to window scroll event

This is my solution, it's not that tricky and allow you to use it for several markup throught a simple ng-class directive. Like so you can choose the class and the scrollPos for each case.

Your App.js :

angular.module('myApp',[])
    .controller('mainCtrl',function($window, $scope){
        $scope.scrollPos = 0;

        $window.onscroll = function(){
            $scope.scrollPos = document.body.scrollTop || document.documentElement.scrollTop || 0;
            $scope.$apply(); //or simply $scope.$digest();
        };
    });

Your index.html :

<html ng-app="myApp">
    <head></head>
    <body>
        <section ng-controller="mainCtrl">
            <p class="red" ng-class="{fix:scrollPos >= 100}">fix me when scroll is equals to 100</p>
            <p class="blue" ng-class="{fix:scrollPos >= 150}">fix me when scroll is equals to 150</p>
        </section>
    </body>
</html>

working JSFiddle here

EDIT :

As $apply() is actually calling $rootScope.$digest() you can directly use $scope.$digest() instead of $scope.$apply() for better performance depending on context.
Long story short : $apply() will always work but force the $digest on all scopes that may cause perfomance issue.

What are all the common ways to read a file in Ruby?

file_content = File.read('filename with extension');
puts file_content;

http://www.ruby-doc.org/core-1.9.3/IO.html#method-c-read

How do I get the calling method name and type using reflection?

You can use it by using the StackTrace and then you can get reflective types from that.

StackTrace stackTrace = new StackTrace();           // get call stack
StackFrame[] stackFrames = stackTrace.GetFrames();  // get method calls (frames)

StackFrame callingFrame = stackFrames[1];
MethodInfo method = callingFrame.GetMethod();
Console.Write(method.Name);
Console.Write(method.DeclaringType.Name);

How do you run a .bat file from PHP?

<?php
 pclose(popen("start /B test.bat", "r")); die();
?> 

End-line characters from lines read from text file, using Python

Long time ago, there was Dear, clean, old, BASIC code that could run on 16 kb core machines: like that:

if (not open(1,"file.txt")) error "Could not open 'file.txt' for reading"
while(not eof(1)) 
  line input #1 a$
  print a$
wend
close

Now, to read a file line by line, with far better hardware and software (Python), we must reinvent the wheel:

def line_input (file):
    for line in file:
        if line[-1] == '\n':
            yield line[:-1]
        else:
            yield line

f = open("myFile.txt", "r")
for line_input(f):
    # do something with line

I am induced to think that something has gone the wrong way somewhere...

apache mod_rewrite is not working or not enabled

To get mod_rewrite to work for me in Apache 2.4, I had to add the "Require all granted" line below.

<Directory /var/www>
   # Required if running apache > 2.4
   Require all granted

   RewriteEngine on 
   RewriteRule ^cachebust-([a-z0-9]+)\/(.*) /$2 [L] 
 </Directory>

supposedly a similar requirement exists for Apache 2.2 as well, if you're using that:

<Directory /var/www>
   # Required if running apache 2.2
   Order allow,deny
   Allow from all

   RewriteEngine on 
   RewriteRule ^cachebust-([a-z0-9]+)\/(.*) /$2 [L] 
 </Directory>

Note that an ErrorDocument 404 directive can sometimes override these things as well, so if it's not working try commenting out your ErrorDocument directive and see if it works. The above example can be used to ensure a site isn't served from cache by including a subfolder in the path, though the files reside at the root of the server.

How to change UIButton image in Swift

in swift 3.0:

@IBOutlet weak var selectionButton: UIButton!

selectionButton.setImage(UIImage.addBlueIcon, for: .selected)

IllegalMonitorStateException on wait() call

Not sure if this will help somebody else out or not but this was the key part to fix my problem in user "Tom Hawtin - tacklin"'s answer above:

synchronized (lock) {
    makeWakeupNeeded();
    lock.notifyAll();
}

Just the fact that the "lock" is passed as an argument in synchronized() and it is also used in "lock".notifyAll();

Once I made it in those 2 places I got it working

Inject service in app.config

Short answer: you can't. AngularJS won't allow you to inject services into the config because it can't be sure they have been loaded correctly.

See this question and answer: AngularJS dependency injection of value inside of module.config

A module is a collection of configuration and run blocks which get applied to the application during the bootstrap process. In its simplest form the module consist of collection of two kinds of blocks:

Configuration blocks - get executed during the provider registrations and configuration phase. Only providers and constants can be injected into configuration blocks. This is to prevent accidental instantiation of services before they have been fully configured.

How do I compile jrxml to get jasper?

Using Version 5.1.0:

Just click preview and it will create a YourReportName.jasper for you in the same working directory.

JQuery, setTimeout not working

This accomplishes the same thing but is much simpler:

$(document).ready(function() {  
   $("#board").delay(1000).append(".");
});

You can chain a delay before almost any jQuery method.

How to find files modified in last x minutes (find -mmin does not work as expected)

this command may be help you sir

find -type f -mtime -60

Smooth GPS data

What you are looking for is called a Kalman Filter. It's frequently used to smooth navigational data. It is not necessarily trivial, and there is a lot of tuning you can do, but it is a very standard approach and works well. There is a KFilter library available which is a C++ implementation.

My next fallback would be least squares fit. A Kalman filter will smooth the data taking velocities into account, whereas a least squares fit approach will just use positional information. Still, it is definitely simpler to implement and understand. It looks like the GNU Scientific Library may have an implementation of this.

How do I remove a single file from the staging area (undo git add)?

So, a slight tweak to Tim Henigan's answer: you need to use -- before the file name. It would look like this:

git reset HEAD -- <file>

Hiding a form and showing another when a button is clicked in a Windows Forms application

A) The main GUI thread will run endlessly on the call to Application.Run, so your while loop will never be reached

B) You would never want to have an endless loop like that (the while(true) loop) - it would simply freeze the thread. Not really sure what you're trying to achieve there.

I would create and show the "main" (initial) form in the Main method (as Visual Studio does for you by default). Then in your button handler, create the other form and show it as well as hiding the main form (not closing it). Then, ensure that the main form is shown again when that form is closed via an event. Example:

public partial class Form1 : Form
{
  public Form1()
  {
    InitializeComponent();
  }    

  private void button1_Click(object sender, EventArgs e)
  {      
    Form2 otherForm = new Form2();
    otherForm.FormClosed += new FormClosedEventHandler(otherForm_FormClosed);
    this.Hide();
    otherForm.Show();      
  }

  void otherForm_FormClosed(object sender, FormClosedEventArgs e)
  {
    this.Show();      
  }
}

Still Reachable Leak detected by Valgrind

Here is a proper explanation of "still reachable":

"Still reachable" are leaks assigned to global and static-local variables. Because valgrind tracks global and static variables it can exclude memory allocations that are assigned "once-and-forget". A global variable assigned an allocation once and never reassigned that allocation is typically not a "leak" in the sense that it does not grow indefinitely. It is still a leak in the strict sense, but can usually be ignored unless you are pedantic.

Local variables that are assigned allocations and not free'd are almost always leaks.

Here is an example

int foo(void)
{
    static char *working_buf = NULL;
    char *temp_buf;
    if (!working_buf) {
         working_buf = (char *) malloc(16 * 1024);
    }
    temp_buf = (char *) malloc(5 * 1024);

    ....
    ....
    ....

}

Valgrind will report working_buf as "still reachable - 16k" and temp_buf as "definitely lost - 5k".

How to delete an element from a Slice in Golang

Maybe this code will help.

It deletes item with a given index.

Takes the array, and the index to delete and returns a new array pretty much like append function.

func deleteItem(arr []int, index int) []int{
  if index < 0 || index >= len(arr){
    return []int{-1}
  }

    for i := index; i < len(arr) -1; i++{
      arr[i] = arr[i + 1]

    }

    return arr[:len(arr)-1]
}

Here you can play with the code : https://play.golang.org/p/aX1Qj40uTVs

Android device does not show up in adb list

I had a similar issue and solved with the following steps after connecting the device via USB:

  1. turn on developer options on the android device.
  2. enable check box for stay awake.
  3. enable check box for USB debugging.
  4. open cmd
  5. got to platform tools adt tools here https://developer.android.com/studio.
  6. adb kill-server
  7. adb start-server
  8. adb devices

Now we can see attached devices.

How to define a circle shape in an Android XML drawable file?

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="oval">
            <solid android:color="@color/text_color_green"/>
            <!-- Set the same value for both width and height to get a circular shape -->
            <size android:width="250dp" android:height="250dp"/>
        </shape>
    </item>
</selector>

How to get the sizes of the tables of a MySQL database?

Try the following shell command (replace DB_NAME with your database name):

mysql -uroot <<<"SELECT table_name AS 'Tables', round(((data_length + index_length) / 1024 / 1024), 2) 'Size in MB' FROM information_schema.TABLES WHERE table_schema = \"DB_NAME\" ORDER BY (data_length + index_length) DESC;" | head

For Drupal/drush solution, check the following example script which will display the biggest tables in use:

#!/bin/sh
DB_NAME=$(drush status --fields=db-name --field-labels=0 | tr -d '\r\n ')
drush sqlq "SELECT table_name AS 'Tables', round(((data_length + index_length) / 1024 / 1024), 2) 'Size in MB' FROM information_schema.TABLES WHERE table_schema = \"${DB_NAME}\" ORDER BY (data_length + index_length) DESC;" | head -n20

iOS Remote Debugging

I haven't tried it, but iOS WebKit debug proxy (ios_webkit_debug_proxy / iwdp) supposedly lets you remotely debug UIWebView. From the README.md

The ios_webkit_debug_proxy (aka iwdp) allows developers to inspect MobileSafari and UIWebViews on real and simulated iOS devices via the Chrome DevTools UI and Chrome Remote Debugging Protocol. DevTools requests are translated into Apple's Remote Web Inspector service calls.

Is there a way to take a screenshot using Java and save it to some sort of image?

GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();  
GraphicsDevice[] screens = ge.getScreenDevices();       
Rectangle allScreenBounds = new Rectangle();  
for (GraphicsDevice screen : screens) {  
       Rectangle screenBounds = screen.getDefaultConfiguration().getBounds();        
       allScreenBounds.width += screenBounds.width;  
       allScreenBounds.height = Math.max(allScreenBounds.height, screenBounds.height);
       allScreenBounds.x=Math.min(allScreenBounds.x, screenBounds.x);
       allScreenBounds.y=Math.min(allScreenBounds.y, screenBounds.y);
      } 
Robot robot = new Robot();
BufferedImage bufferedImage = robot.createScreenCapture(allScreenBounds);
File file = new File("C:\\Users\\Joe\\Desktop\\scr.png");
if(!file.exists())
    file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
ImageIO.write( bufferedImage, "png", fos );

bufferedImage will contain a full screenshot, this was tested with three monitors

Get sum of MySQL column in PHP

$row['Value'] is probably a string. Try using intval($row['Value']).

Also, make sure you set $sum = 0 before the loop.

Or, better yet, add SUM(Value) AS Val_Sum to your SQL query.

Build query string for System.Net.HttpClient get

Along the same lines as Rostov's post, if you do not want to include a reference to System.Web in your project, you can use FormDataCollection from System.Net.Http.Formatting and do something like the following:

Using System.Net.Http.Formatting.FormDataCollection

var parameters = new Dictionary<string, string>()
{
    { "ham", "Glaced?" },
    { "x-men", "Wolverine + Logan" },
    { "Time", DateTime.UtcNow.ToString() },
}; 
var query = new FormDataCollection(parameters).ReadAsNameValueCollection().ToString();

How do I get an OAuth 2.0 authentication token in C#

https://github.com/IdentityModel/IdentityModel adds extensions to HttpClient to acquire tokens using different flows and the documentation is great too. It's very handy because you don't have to think how to implement it yourself. I'm not aware if any official MS implementation exists.

Convert array to JSON string in swift

If you're already using SwiftyJSON:

https://github.com/SwiftyJSON/SwiftyJSON

You can do this:

// this works with dictionaries too
let paramsDictionary = [
    "title": "foo",
    "description": "bar"
]
let paramsArray = [ "one", "two" ]
let paramsJSON = JSON(paramsArray)
let paramsString = paramsJSON.rawString(encoding: NSUTF8StringEncoding, options: nil)

SWIFT 3 UPDATE

 let paramsJSON = JSON(paramsArray)
 let paramsString = paramsJSON.rawString(String.Encoding.utf8, options: JSONSerialization.WritingOptions.prettyPrinted)!

JSON strings, which are good for transport, don't come up often because you can JSON encode an HTTP body. But one potential use-case for JSON stringify is Multipart Post, which AlamoFire nows supports.

How to solve the system.data.sqlclient.sqlexception (0x80131904) error

The datasource is by default .\SQLEXPRESS (its the instance where databases are placed by default) or if u changed the name of the instance during installation of sql server so i advise you to do this :

connectionString="Data Source=.\\yourInstance(defaulT Data source is SQLEXPRESS);
       Initial Catalog=databaseName;
       User ID=theuser if u use it;
       Password=thepassword if u use it;
       integrated security=true(if u don t use user and pass; else change it false)"

Without to knowing your instance, I could help with this one. Hope it helped

PHP substring extraction. Get the string before the first '/' or the whole string

$string="kalion/home/public_html";

$newstring=( stristr($string,"/")==FALSE ) ? $string : substr($string,0,stripos($string,"/"));

A project with an Output Type of Class Library cannot be started directly

.Exe's and .dll's are both assemblies. The key difference is that executeables define an entry point Main which can be invoked by the runtime. The error

"Class library cannot be started directly"

is due to the fact that said .dll's do not have a Main. To fix this issue, change the project type to a Windows application/Console application and define an entry point. Or, add a new project that is of type Windows application/Console application and reference said .dll.

How to change the blue highlight color of a UITableViewCell?

In Swift, use this in cellForRowAtIndexPath

let selectedView = UIView()
selectedView.backgroundColor = .white
cell.selectedBackgroundView = selectedView

If you want your selection color be the same in every UITableViewCell, use this in AppDelegate.

let selectedView = UIView()
selectedView.backgroundColor = .white
UITableViewCell.appearance().selectedBackgroundView = selectedView

How to get single value from this multi-dimensional PHP array

echo $myarray[0]->['email'];

Try this only if it you are passing the stdclass object

C++ printing spaces or tabs given a user input integer

Appending single space to output file with stream variable.

// declare output file stream varaible and open file ofstream fout; fout.open("flux_capacitor.txt"); fout << var << " ";

MS Access: how to compact current database in VBA

When the user exits the FE attempt to rename the backend MDB preferably with todays date in the name in yyyy-mm-dd format. Ensure you close all bound forms, including hidden forms, and reports before doing this. If you get an error message, oops, its busy so don't bother. If it is successful then compact it back.

See my Backup, do you trust the users or sysadmins? tips page for more info.

How do you convert a byte array to a hexadecimal string in C?

Based on Yannuth's answer but simplified.

Here, length of dest[] is implied to be twice of len, and its allocation is managed by the caller.

void create_hex_string_implied(const unsigned char *src, size_t len, unsigned char *dest)
{
    static const unsigned char table[] = "0123456789abcdef";

    for (; len > 0; --len)
    {
        unsigned char c = *src++;
        *dest++ = table[c >> 4];
        *dest++ = table[c & 0x0f];
    }
}

Alternative to the HTML Bold tag

What you use instead of the b element depends on the semantics of that element's content.

  • The elements b and strong have co-existed for a long time by now. In HTML 4.01, which has been superseded by HTML5, strong was meant to be used for "strong emphasis", i.e. stronger emphasis than the em element (which just indicated emphasis). In HTML 5.2, strong "represents strong importance, seriousness, or urgency for its contents"; the aspects of "seriousness" and "urgency" are new in the specification compared to HTML 4.01. So if you used b to represent content that was important, serious or urgent, it is recommended that you use strong instead. If you want, you can differentiate between these different semantics by adding meaningful class attributes, e.g. <strong class="urgent">...</strong> and <strong class="warning">...</strong> and use appropriate CSS selectors to style these types of "emphasis" different, e.g. using different colours and font sizes (e.g. in your CSS file: strong.warning { color: red; background-color: transparent; border: 2px solid red; }.).
    Another alternative to b is the em element, which in HTML 5.2 "represents stress emphasis of its contents". Note that this element is usually rendered in italics (and has therefore often been recommended as a replacement for the i element).
    I would resist the temptation to follow the advice from some of the other answers to write something like <strong class="bold">...</strong>. Firstly, the class attribute doesn't mean anything in non-visual contexts (listening to an ePub book, text to speech generally, screen readers, Braille); secondly, people maintaining the code will need to read the actual content to figure out why something was bolded.
  • If you used b for entire paragraphs or headings (as opposed to shorter spans of texts, which is the use case in the previous bullet point), I would replace it with appropriate class attributes or, if applicable, WAI-ARIA roles such as alert for a live region "with important, and usually time-sensitive, information". As mentioned above, you should use "semantic" class attribute values, so that people maintaining the code (including your future self) can figure out why something was bolded.
  • Not all uses of the b may represent something semantic. For example, when you are converting printed documents into HTML, text may be bolded for reasons that have nothing to do with emphasis or importance but as a visual guide. For example, the headwords in dictionaries aren't any more "serious", "urgent" than the other content, so you may keep the b element and optionallly add a meaningful class attribute, e.g. <b class="headword"> or replace the tag with <span class="headword"> based on the argument that b has no meaning in non-visual contexts.

In your CSS file (instead of using style attributes, as some of the other answers have recommended), you have several options for styling the "bold" or important text:

  • specifying different colours (foreground and/or background);
  • specifying different font faces;
  • specifying borders (see example above);
  • using different font weights using the font-weight property, which allows more values than just normal and bold, namely normal | bold | bolder | lighter | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900,
  • etc.

Note that support for numeric font-weight values has not always been great.

How do I concatenate const/literal strings in C?

If you have experience in C you will notice that strings are only char arrays where the last character is a null character.

Now that is quite inconvenient as you have to find the last character in order to append something. strcat will do that for you.

So strcat searches through the first argument for a null character. Then it will replace this with the second argument's content (until that ends in a null).

Now let's go through your code:

message = strcat("TEXT " + var);

Here you are adding something to the pointer to the text "TEXT" (the type of "TEXT" is const char*. A pointer.).

That will usually not work. Also modifying the "TEXT" array will not work as it is usually placed in a constant segment.

message2 = strcat(strcat("TEXT ", foo), strcat(" TEXT ", bar));

That might work better, except that you are again trying to modify static texts. strcat is not allocating new memory for the result.

I would propose to do something like this instead:

sprintf(message2, "TEXT %s TEXT %s", foo, bar);

Read the documentation of sprintf to check for it's options.

And now an important point:

Ensure that the buffer has enough space to hold the text AND the null character. There are a couple of functions that can help you, e.g., strncat and special versions of printf that allocate the buffer for you. Not ensuring the buffer size will lead to memory corruption and remotely exploitable bugs.

Properly Handling Errors in VBA (Excel)

Two main purposes for error handling:

  1. Trap errors you can predict but can't control the user from doing (e.g. saving a file to a thumb drive when the thumb drives has been removed)
  2. For unexpected errors, present user with a form that informs them what the problem is. That way, they can relay that message to you and you might be able to give them a work-around while you work on a fix.

So, how would you do this?

First of all, create an error form to display when an unexpected error occurs.

It could look something like this (FYI: Mine is called frmErrors): Company Error Form

Notice the following labels:

  • lblHeadline
  • lblSource
  • lblProblem
  • lblResponse

Also, the standard command buttons:

  • Ignore
  • Retry
  • Cancel

There's nothing spectacular in the code for this form:

Option Explicit

Private Sub cmdCancel_Click()
  Me.Tag = CMD_CANCEL
  Me.Hide
End Sub

Private Sub cmdIgnore_Click()
  Me.Tag = CMD_IGNORE
  Me.Hide
End Sub

Private Sub cmdRetry_Click()
  Me.Tag = CMD_RETRY
  Me.Hide
End Sub

Private Sub UserForm_Initialize()
  Me.lblErrorTitle.Caption = "Custom Error Title Caption String"
End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
  'Prevent user from closing with the Close box in the title bar.
    If CloseMode <> 1 Then
      cmdCancel_Click
    End If
End Sub

Basically, you want to know which button the user pressed when the form closes.

Next, create an Error Handler Module that will be used throughout your VBA app:

'****************************************************************
'    MODULE: ErrorHandler
'
'   PURPOSE: A VBA Error Handling routine to handle
'             any unexpected errors
'
'     Date:    Name:           Description:
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'03/22/2010    Ray      Initial Creation
'****************************************************************
Option Explicit

Global Const CMD_RETRY = 0
Global Const CMD_IGNORE = 1
Global Const CMD_CANCEL = 2
Global Const CMD_CONTINUE = 3

Type ErrorType
    iErrNum As Long
    sHeadline As String
    sProblemMsg As String
    sResponseMsg As String
    sErrorSource As String
    sErrorDescription As String
    iBtnCap(3) As Integer
    iBitmap As Integer
End Type

Global gEStruc As ErrorType
Sub EmptyErrStruc_S(utEStruc As ErrorType)
  Dim i As Integer

  utEStruc.iErrNum = 0
  utEStruc.sHeadline = ""
  utEStruc.sProblemMsg = ""
  utEStruc.sResponseMsg = ""
  utEStruc.sErrorSource = ""
  For i = 0 To 2
    utEStruc.iBtnCap(i) = -1
  Next
  utEStruc.iBitmap = 1

End Sub
Function FillErrorStruct_F(EStruc As ErrorType) As Boolean
  'Must save error text before starting new error handler
  'in case we need it later
  EStruc.sProblemMsg = Error(EStruc.iErrNum)
  On Error GoTo vbDefaultFill

  EStruc.sHeadline = "Error " & Format$(EStruc.iErrNum)
  EStruc.sProblemMsg = EStruc.sErrorDescription
  EStruc.sErrorSource = EStruc.sErrorSource
  EStruc.sResponseMsg = "Contact the Company and tell them you received Error # " & Str$(EStruc.iErrNum) & ". You should write down the program function you were using, the record you were working with, and what you were doing."

   Select Case EStruc.iErrNum
       'Case Error number here
       'not sure what numeric errors user will ecounter, but can be implemented here
       'e.g.
       'EStruc.sHeadline = "Error 3265"
       'EStruc.sResponseMsg = "Contact tech support. Tell them what you were doing in the program."

     Case Else

       EStruc.sHeadline = "Error " & Format$(EStruc.iErrNum) & ": " & EStruc.sErrorDescription
       EStruc.sProblemMsg = EStruc.sErrorDescription

   End Select

   GoTo FillStrucEnd

vbDefaultFill:

  'Error Not on file
  EStruc.sHeadline = "Error " & Format$(EStruc.iErrNum) & ": Contact Tech Support"
  EStruc.sResponseMsg = "Contact the Company and tell them you received Error # " & Str$(EStruc.iErrNum)
FillStrucEnd:

  Exit Function

End Function
Function iErrorHandler_F(utEStruc As ErrorType) As Integer
  Static sCaption(3) As String
  Dim i As Integer
  Dim iMCursor As Integer

  Beep

  'Setup static array
  If Len(sCaption(0)) < 1 Then
    sCaption(CMD_IGNORE) = "&Ignore"
    sCaption(CMD_RETRY) = "&Retry"
    sCaption(CMD_CANCEL) = "&Cancel"
    sCaption(CMD_CONTINUE) = "Continue"
  End If

  Load frmErrors

  'Did caller pass error info?  If not fill struc with the needed info
  If Len(utEStruc.sHeadline) < 1 Then
    i = FillErrorStruct_F(utEStruc)
  End If

  frmErrors!lblHeadline.Caption = utEStruc.sHeadline
  frmErrors!lblProblem.Caption = utEStruc.sProblemMsg
  frmErrors!lblSource.Caption = utEStruc.sErrorSource
  frmErrors!lblResponse.Caption = utEStruc.sResponseMsg

  frmErrors.Show
  iErrorHandler_F = frmErrors.Tag   ' Save user response
  Unload frmErrors                  ' Unload and release form

  EmptyErrStruc_S utEStruc          ' Release memory

End Function

You may have errors that will be custom only to your application. This would typically be a short list of errors specifically only to your application. If you don't already have a constants module, create one that will contain an ENUM of your custom errors. (NOTE: Office '97 does NOT support ENUMS.). The ENUM should look something like this:

Public Enum CustomErrorName
  MaskedFilterNotSupported
  InvalidMonthNumber
End Enum

Create a module that will throw your custom errors.

'********************************************************************************************************************************
'    MODULE: CustomErrorList
'
'   PURPOSE: For trapping custom errors applicable to this application
'
'INSTRUCTIONS:  To use this module to create your own custom error:
'               1.  Add the Name of the Error to the CustomErrorName Enum
'               2.  Add a Case Statement to the raiseCustomError Sub
'               3.  Call the raiseCustomError Sub in the routine you may see the custom error
'               4.  Make sure the routine you call the raiseCustomError has error handling in it
'
'
'     Date:    Name:           Description:
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'03/26/2010    Ray       Initial Creation
'********************************************************************************************************************************
Option Explicit
Const MICROSOFT_OFFSET = 512 'Microsoft reserves error values between vbObjectError and vbObjectError + 512
'************************************************************************************************
'  FUNCTION:  raiseCustomError
'
'   PURPOSE:  Raises a custom error based on the information passed
'
'PARAMETERS:  customError - An integer of type CustomErrorName Enum that defines the custom error
'             errorSource - The place the error came from
'
'   Returns:  The ASCII vaule that should be used for the Keypress
'
'     Date:    Name:           Description:
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'03/26/2010    Ray       Initial Creation
'************************************************************************************************
Public Sub raiseCustomError(customError As Integer, Optional errorSource As String = "")
  Dim errorLong As Long
  Dim errorDescription As String

  errorLong = vbObjectError + MICROSOFT_OFFSET + customError

  Select Case customError

    Case CustomErrorName.MaskedFilterNotSupported
      errorDescription = "The mask filter passed is not supported"

    Case CustomErrorName.InvalidMonthNumber
      errorDescription = "Invalid Month Number Passed"

    Case Else
      errorDescription = "The custom error raised is unknown."

  End Select

  Err.Raise errorLong, errorSource, errorDescription

End Sub

You are now well equipped to trap errors in your program. You sub (or function), should look something like this:

Public Sub MySub(monthNumber as Integer)
  On Error GoTo eh  

  Dim sheetWorkSheet As Worksheet

  'Run Some code here

  '************************************************
  '*   OPTIONAL BLOCK 1:  Look for a specific error
  '************************************************
  'Temporarily Turn off Error Handling so that you can check for specific error
  On Error Resume Next
  'Do some code where you might expect an error.  Example below:
  Const ERR_SHEET_NOT_FOUND = 9 'This error number is actually subscript out of range, but for this example means the worksheet was not found

  Set sheetWorkSheet = Sheets("January")

  'Now see if the expected error exists

  If Err.Number = ERR_SHEET_NOT_FOUND Then
    MsgBox "Hey!  The January worksheet is missing.  You need to recreate it."
    Exit Sub
  ElseIf Err.Number <> 0 Then
    'Uh oh...there was an error we did not expect so just run basic error handling 
    GoTo eh
  End If

  'Finished with predictable errors, turn basic error handling back on:
  On Error GoTo eh

  '**********************************************************************************
  '*   End of OPTIONAL BLOCK 1
  '**********************************************************************************

  '**********************************************************************************
  '*   OPTIONAL BLOCK 2:  Raise (a.k.a. "Throw") a Custom Error if applicable
  '**********************************************************************************
  If not (monthNumber >=1 and monthnumber <=12) then
    raiseCustomError CustomErrorName.InvalidMonthNumber, "My Sub"
  end if
  '**********************************************************************************
  '*   End of OPTIONAL BLOCK 2
  '**********************************************************************************

  'Rest of code in your sub

  goto sub_exit

eh:
  gEStruc.iErrNum = Err.Number
  gEStruc.sErrorDescription = Err.Description
  gEStruc.sErrorSource = Err.Source
  m_rc = iErrorHandler_F(gEStruc)

  If m_rc = CMD_RETRY Then
    Resume
  End If

sub_exit:
  'Any final processing you want to do.
  'Be careful with what you put here because if it errors out, the error rolls up.  This can be difficult to debug; especially if calling routine has no error handling.

  Exit Sub 'I was told a long time ago (10+ years) that exit sub was better than end sub...I can't tell you why, so you may not want to put in this line of code.  It's habit I can't break :P
End Sub

A copy/paste of the code above may not work right out of the gate, but should definitely give you the gist.

BTW, if you ever need me to do your company logo, look me up at http://www.MySuperCrappyLogoLabels99.com

Detect current device with UI_USER_INTERFACE_IDIOM() in Swift

Swift 2.x:

Adding to Beslav Turalov answer's the new entry iPad Pro can easily be find with this line

to detect iPad Pro

struct DeviceType
{
    ...
    static let IS_IPAD_PRO = UIDevice.currentDevice().userInterfaceIdiom == .Pad && ScreenSize.SCREEN_MAX_LENGTH == 1366.0
}

Swift 3 (TV and car added):

struct ScreenSize
{
    static let SCREEN_WIDTH         = UIScreen.main.bounds.size.width
    static let SCREEN_HEIGHT        = UIScreen.main.bounds.size.height
    static let SCREEN_MAX_LENGTH    = max(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT)
    static let SCREEN_MIN_LENGTH    = min(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT)
}

struct DeviceType
{
    static let IS_IPHONE            = UIDevice.current.userInterfaceIdiom == .phone
    static let IS_IPHONE_4_OR_LESS  = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH < 568.0
    static let IS_IPHONE_5          = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 568.0
    static let IS_IPHONE_6          = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 667.0
    static let IS_IPHONE_6P         = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 736.0
    static let IS_IPHONE_7          = IS_IPHONE_6
    static let IS_IPHONE_7P         = IS_IPHONE_6P
    static let IS_IPAD              = UIDevice.current.userInterfaceIdiom == .pad && ScreenSize.SCREEN_MAX_LENGTH == 1024.0
    static let IS_IPAD_PRO_9_7      = IS_IPAD
    static let IS_IPAD_PRO_12_9     = UIDevice.current.userInterfaceIdiom == .pad && ScreenSize.SCREEN_MAX_LENGTH == 1366.0
    static let IS_TV                = UIDevice.current.userInterfaceIdiom == .tv
    static let IS_CAR_PLAY          = UIDevice.current.userInterfaceIdiom == .carPlay
}

struct Version{
    static let SYS_VERSION_FLOAT = (UIDevice.current.systemVersion as NSString).floatValue
    static let iOS7 = (Version.SYS_VERSION_FLOAT < 8.0 && Version.SYS_VERSION_FLOAT >= 7.0)
    static let iOS8 = (Version.SYS_VERSION_FLOAT >= 8.0 && Version.SYS_VERSION_FLOAT < 9.0)
    static let iOS9 = (Version.SYS_VERSION_FLOAT >= 9.0 && Version.SYS_VERSION_FLOAT < 10.0)
    static let iOS10 = (Version.SYS_VERSION_FLOAT >= 10.0 && Version.SYS_VERSION_FLOAT < 11.0)
}

USAGE:

if DeviceType.IS_IPHONE_7P { print("iPhone 7 plus") }
if DeviceType.IS_IPAD_PRO_9_7 && Version.iOS10 { print("iPad pro 9.7 with iOS 10 version") }

Use async await with Array.map

You can use:

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

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

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

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

SSRS expression to format two decimal places does not show zeros

If you want to always display some value after decimal for example "12.00" or "12.23" Then use just like below , it worked for me

FormatNumber("145.231000",2) Which will display 145.23

FormatNumber("145",2) Which will display 145.00

Convert string to Python class object?

Using importlib worked the best for me.

import importlib

importlib.import_module('accounting.views') 

This uses string dot notation for the python module that you want to import.

What is the proper way to re-throw an exception in C#?

I found that if the exception is thrown in the same method that it is caught, the stack trace is not preserved, for what it's worth.

void testExceptionHandling()
{
    try
    {
        throw new ArithmeticException("illegal expression");
    }
    catch (Exception ex)
    {
        throw;
    }
    finally
    {
        System.Diagnostics.Debug.WriteLine("finally called.");
    }
}

Merge two Excel tables Based on matching data in Columns

Put the table in the second image on Sheet2, columns D to F.

In Sheet1, cell D2 use the formula

=iferror(vlookup($A2,Sheet2!$D$1:$F$100,column(A1),false),"")

copy across and down.

Edit: here is a picture. The data is in two sheets. On Sheet1, enter the formula into cell D2. Then copy the formula across to F2 and then down as many rows as you need.

enter image description here

How can I format DateTime to web UTC format?

You want to use DateTimeOffset class.

var date = new DateTimeOffset(2009, 9, 1, 0, 0, 0, 0, new TimeSpan(0L));
var stringDate = date.ToString("u");

sorry I missed your original formatting with the miliseconds

var stringDate = date.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'");

How to see query history in SQL Server Management Studio

A slightly out-of-the-box method would be to script up a solution in AutoHotKey. I use this, and it's not perfect, but works and is free. Essentially, this script assigns a hotkey to CTRL+SHIFT+R which will copy the selected SQL in SSMS (CTRL+C), save off a datestamp SQL file, and then execute the highlighted query (F5). If you aren't used to AHK scripts, the leading semicolon is a comment.

;CTRL+SHIFT+R to run a query that is first saved off
^+r::
;Copy
Send, ^c
; Set variables
EnvGet, HomeDir, USERPROFILE
FormatTime, DateString,,yyyyMMdd
FormatTime, TimeString,,hhmmss
; Make a spot to save the clipboard
FileCreateDir %HomeDir%\Documents\sqlhist\%DateString%
FileAppend, %Clipboard%, %HomeDir%\Documents\sqlhist\%DateString%\%TimeString%.sql
; execute the query
Send, {f5}
Return

The biggest limitations are that this script won't work if you click "Execute" rather than use the keyboard shortcut, and this script won't save off the whole file - just the selected text. But, you could always modify the script to execute the query, and then select all (CTRL+A) before the copy/save.

Using a modern editor with "find in files" features will let you search your SQL history. You could even get fancy and scrape your files into a SQLite3 database to query your queries.

Converting string to integer

The function you need is CInt.

ie CInt(PrinterLabel)

See Type Conversion Functions (Visual Basic) on MSDN

Edit: Be aware that CInt and its relatives behave differently in VB.net and VBScript. For example, in VB.net, CInt casts to a 32-bit integer, but in VBScript, CInt casts to a 16-bit integer. Be on the lookout for potential overflows!

Create Excel files from C# without office

An interop calls something else, it's an interoperability assembly, so you're inter-operating with something...in this case Excel, the actual installed Excel.

In this case yes, it will fail to run because it depends on excel, you're just calling excel functions. If they don't have it installed...out of luck.

There are methods to generate without Excel, provided the 2007 file format is ok, here's a few:

as I said though, this is the 2007 format, normally if anything, that's the deal-breaker.

Iterate through 2 dimensional array

Just change the indexes. i and j....in the loop, plus if you're dealing with Strings you have to use concat and initialize the variable to an empty Strong otherwise you'll get an exception.

String string="";
for (int i = 0; i<array.length; i++){
    for (int j = 0; j<array[i].length; j++){
        string = string.concat(array[j][i]);
    } 
}
System.out.println(string)

Understanding unique keys for array children in React.js

Just add the unique key to the your Components

data.map((marker)=>{
    return(
        <YourComponents 
            key={data.id}     // <----- unique key
        />
    );
})

Delete last char of string

string.Join is better, but if you really want a LINQ ForEach:

var strgroupids = string.Empty;

groupIds.ForEach(g =>
{
    if(strgroupids != string.Empty){
        strgroupids += ",";
    }

    strgroupids += g;
});

Some notes:

  • string.Join and foreach are both better than this, vastly slower, approach
  • No need to remove the last , since it's never appended
  • The increment operator (+=) is handy for appending to strings
  • .ToString() is unnecessary as it is called automatically when concatenating non-strings
  • When handling large strings, StringBuilder should be considered instead of concatenating strings

What is the difference between '@' and '=' in directive scope in AngularJS?

the main difference between them is just

@ Attribute string binding
= Two-way model binding
& Callback method binding

WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser

Old question but a similar issue nearly drove me to insanity so sharing my solution. None of the other suggestions fixed my issue.

When I updated my Docker image Chrome installation from an old version to Chrome 86, I got this error. My setup was not identical but we were instantiating Chrome through a selenium webdriver.

The solution was to pass the options as goog:chromeOptions hash instead of chromeOptions hash. I truly don't know if this was a Selenium, Chrome, Chromedriver, or some other update, but maybe some poor soul will find solace in this answer in the future.

Does Android keep the .apk files? if so where?

In /data/app but for copy protection I don't think you can access it.

Use grep to report back only line numbers

All of these answers require grep to generate the entire matching lines, then pipe it to another program. If your lines are very long, it might be more efficient to use just sed to output the line numbers:

sed -n '/pattern/=' filename

Hiding user input on terminal in Linux script

Update

In case you want to get fancy by outputting an * for each character they type, you can do something like this (using andreas' read -s solution):

unset password;
while IFS= read -r -s -n1 pass; do
  if [[ -z $pass ]]; then
     echo
     break
  else
     echo -n '*'
     password+=$pass
  fi
done

Without being fancy

echo "Please enter your username";
read username;

echo "Please enter your password";
stty -echo
read password;
stty echo

Android TextView Text not getting wrapped

In my case, with a TableRow > ScrollView > TextView nesting, I solved the problem by setting android:layout_width to fill_parent on TableRow, and to wrap_content on ScrollView and TextView.

Can I change the fill color of an svg path with CSS?

If you go into the source code of an SVG file you can change the color fill by modifying the fill property.

<svg fill="#3F6078" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
</svg> 

Use your favorite text editor, open the SVG file and play around with it.

How to pass parameters to a partial view in ASP.NET MVC?

make sure you add {} around Html.RenderPartial, as:

@{Html.RenderPartial("FullName", new { firstName = model.FirstName, lastName = model.LastName});}

not

@Html.RenderPartial("FullName", new { firstName = model.FirstName, lastName = model.LastName});

Checking if a number is an Integer in Java

Check if ceil function and floor function returns the same value

static boolean isInteger(int n) 
{ 
return (int)(Math.ceil(n)) == (int)(Math.floor(n)); 
} 

Get last field using awk substr

I know I'm like 3 years late on this but.... you should consider parameter expansion, it's built-in and faster.

if your input is in a var, let's say, $var1, just do ${var1##*/}. Look below

$ var1='/home/parent/child1/filename'
$ echo ${var1##*/}
filename
$ var1='/home/parent/child1/child2/filename'
$ echo ${var1##*/}
filename
$ var1='/home/parent/child1/child2/child3/filename'
$ echo ${var1##*/}
filename

graphing an equation with matplotlib

To plot an equation that is not solved for a specific variable (like circle or hyperbola):

import numpy as np  
import matplotlib.pyplot as plt  
plt.figure() # Create a new figure window
xlist = np.linspace(-2.0, 2.0, 100) # Create 1-D arrays for x,y dimensions
ylist = np.linspace(-2.0, 2.0, 100) 
X,Y = np.meshgrid(xlist, ylist) # Create 2-D grid xlist,ylist values
F = X**2 + Y**2 - 1  #  'Circle Equation
plt.contour(X, Y, F, [0], colors = 'k', linestyles = 'solid')
plt.show()

More about it: http://courses.csail.mit.edu/6.867/wiki/images/3/3f/Plot-python.pdf

Can gcc output C code after preprocessing?

Yes. Pass gcc the -E option. This will output preprocessed source code.

org.apache.jasper.JasperException: Unable to compile class for JSP:

Please remove the servlet jar from web project,as any how, the application/web server already had.

How to get the latest tag name in current branch in Git?

I'm not sure why there are no answers to what the question is asking for. i.e. All tags (non-annotated included) and without the suffix:

git describe --tags --abbrev=0

Create view with primary key?

I got the error "The table/view 'dbo.vMyView' does not have a primary key defined" after I created a view in SQL server query designer. I solved the problem by using ISNULL on a column to force entity framework to use it as a primary key. You might have to restart visual studio to get the warnings to go away.

CREATE VIEW [dbo].[vMyView]
AS
SELECT ISNULL(Id, -1) AS IdPrimaryKey, Name
FROM  dbo.MyTable

Check if URL has certain string with PHP

$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];


if (!strpos($url,'car')) {
    echo 'Car exists.';
} else {
    echo 'No cars.';
}

This seems to work.

Web colors in an Android color xml resource file

<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="Black">#FF000000</color>   
<color name="Black_overlay">#66000000</color>

<color name="Black_transparent_black_hex_1">#11000000</color>
<color name="Black_transparent_black_hex_10">#aa000000</color>
<color name="Black_transparent_black_hex_11">#bb000000</color>
<color name="Black_transparent_black_hex_12">#cc000000</color>
<color name="Black_transparent_black_hex_13">#dd000000</color>
<color name="Black_transparent_black_hex_14">#ee000000</color>
<color name="Black_transparent_black_hex_15">#ff000000</color>
<color name="Black_transparent_black_hex_2">#22000000</color>
<color name="Black_transparent_black_hex_3">#33000000</color>
<color name="Black_transparent_black_hex_4">#44000000</color>
<color name="Black_transparent_black_hex_5">#55000000</color>
<color name="Black_transparent_black_hex_6">#66000000</color>
<color name="Black_transparent_black_hex_7">#77000000</color>
<color name="Black_transparent_black_hex_8">#88000000</color>
<color name="Black_transparent_black_hex_9">#99000000</color>

<color name="Black_transparent_black_percent_10">#1A000000</color>
<color name="Black_transparent_black_percent_15">#26000000</color>
<color name="Black_transparent_black_percent_20">#33000000</color>
<color name="Black_transparent_black_percent_25">#40000000</color>
<color name="Black_transparent_black_percent_30">#4D000000</color>
<color name="Black_transparent_black_percent_35">#59000000</color>
<color name="Black_transparent_black_percent_40">#66000000</color>
<color name="Black_transparent_black_percent_45">#73000000</color>
<color name="Black_transparent_black_percent_5">#0D000000</color>
<color name="Black_transparent_black_percent_50">#80000000</color>
<color name="Black_transparent_black_percent_55">#8C000000</color>
<color name="Black_transparent_black_percent_60">#99000000</color>
<color name="Black_transparent_black_percent_65">#A6000000</color>
<color name="Black_transparent_black_percent_70">#B3000000</color>
<color name="Black_transparent_black_percent_75">#BF000000</color>
<color name="Black_transparent_black_percent_80">#CC000000</color>
<color name="Black_transparent_black_percent_85">#D9000000</color>
<color name="Black_transparent_black_percent_90">#E6000000</color>
<color name="Black_transparent_black_percent_95">#F2000000</color>

 <color name="BlanchedAlmond">#FFEBCD</color>
 <color name="Blue_AliceBlue">#F0F8FF</color>
 <color name="Blue_Aqua">#00FFFF</color>
 <color name="Blue_Aquamarine">#7FFFD4</color>
 <color name="Blue">#0000FF</color>
 <color name="Blue_BlueNavy">#000080</color>
 <color name="Blue_BlueViolet">#8A2BE2</color>
 <color name="Blue_CadetBlue">#5F9EA0</color>
 <color name="Blue_CornflowerBlue">#6495ED</color>
 <color name="Blue_DarkBlue">#00008B</color>
 <color name="Blue_DarkSlateBlue">#483D8B</color>
 <color name="Blue_DeepSkyBlue">#00BFFF</color>
 <color name="Blue_DodgerBlue">#1E90FF</color>
 <color name="Blue_Lavender">#E6E6FA</color>
 <color name="Blue_LavenderBlush">#FFF0F5</color>
 <color name="Blue_LightBlue">#ADD8E6</color>
 <color name="Blue_LightSkyBlue">#87CEFA</color>
 <color name="Blue_LightSteelBlue">#B0C4DE</color>
 <color name="Blue_MediumBlue">#0000CD</color>
 <color name="Blue_MediumSlateBlue">#7B68EE</color>
 <color name="Blue_MidnightBlue">#191970</color>
 <color name="Blue_Navy">#000080</color>
 <color name="Blue_PowderBlue">#B0E0E6</color>
 <color name="Blue_RoyalBlue">#4169E1</color>
 <color name="Blue_SkyBlue">#87CEEB</color>
 <color name="Blue_SlateBlue">#6A5ACD</color>
 <color name="Blue_SteelBlue">#4682B4</color>

 <color name="Brown">#A52A2A</color>
 <color name="Brown_BurlyWood">#DEB887</color>
 <color name="Brown_Chocolate">#D2691E</color>
 <color name="Brown_DarkKhaki">#BDB76B</color>
 <color name="Brown_RosyBrown">#BC8F8F</color>
 <color name="Brown_SandyBrown">#F4A460</color>

 <color name="Chartreuse">#7FFF00</color>
 <color name="Coral">#FF7F50</color>
 <color name="Cornsilk">#FFF8DC</color>
 <color name="Cyan">#00FFFF</color>
 <color name="DarkMagenta">#8B008B</color>
 <color name="DarkOrchid">#9932CC</color>
 <color name="DarkSalmon">#E9967A</color>
 <color name="DarkTurquoise">#00CED1</color>
 <color name="DarkViolet">#9400D3</color>
 <color name="Fuchsia">#FF00FF</color>
 <color name="Gainsboro">#DCDCDC</color>

 <color name="Gray">#808080</color>
 <color name="Gray_DarkGray1">#A9A9A9</color>
 <color name="Gray_DarkGray">#2F4F4F</color>
 <color name="Gray_DimGray">#696969</color>
 <color name="Gray_LightGray">#D3D3D3</color>
 <color name="Gray_LightSlateGray">#778899</color>
 <color name="Gray_SlateGray">#708090</color>

 <color name="Green">#008000</color>
 <color name="Green_DarkGreen">#006400</color>
 <color name="Green_DarkOliveGreen">#556B2F</color>
 <color name="Green_DarkSeaGreen">#8FBC8F</color>
 <color name="Green_ForestGreen">#228B22</color>
 <color name="Green_GreenYellow">#ADFF2F</color>
 <color name="Green_LawnGreen">#7CFC00</color>
 <color name="Green_LightGreen">#90EE90</color>
 <color name="Green_LightSeaGreen">#20B2AA</color>
 <color name="Green_LimeGreen">#32CD32</color>
 <color name="Green_MediumSeaGreen">#3CB371</color>
 <color name="Green_MediumSpringGreen">#00FA9A</color>
 <color name="Green_PaleGreen">#98FB98</color>
 <color name="Green_SeaGreen">#2E8B57</color>
 <color name="Green_SpringGreen">#00FF7F</color>
 <color name="Green_YellowGreen">#9ACD32</color>

 <color name="Indigo">#4B0082</color>
 <color name="Khaki">#F0E68C</color>
 <color name="LemonChiffon">#FFFACD</color>
 <color name="LightCoral">#F08080</color>
 <color name="LightGoldenrodYellow">#FAFAD2</color>
 <color name="LightSalmon">#FFA07A</color>
 <color name="Lime">#00FF00</color>
 <color name="Linen">#FAF0E6</color>
 <color name="Magenta">#FF00FF</color>
 <color name="Maroon">#800000</color>
 <color name="MediumAquamarine">#66CDAA</color>
 <color name="MediumOrchid">#BA55D3</color>
 <color name="MediumPurple">#9370DB</color>
 <color name="MediumTurquoise">#48D1CC</color>
 <color name="MintCream">#F5FFFA</color>
 <color name="Moccasin">#FFE4B5</color>
 <color name="OldLace">#FDF5E6</color>
 <color name="Olive">#808000</color>
 <color name="OliveDrab">#6B8E23</color>

 <color name="Orange">#FFA500</color>
 <color name="Orange_DarkOrange">#FF8C00</color>
 <color name="Orchid">#DA70D6</color>
 <color name="PaleTurquoise">#AFEEEE</color>
 <color name="PapayaWhip">#FFEFD5</color>
 <color name="PeachPuff">#FFDAB9</color>
 <color name="Peru">#CD853F</color>

 <color name="Pink">#FFC0CB</color>
 <color name="Pink_DeepPink">#FF1493</color>
 <color name="Pink_HotPink">#FF69B4</color>
 <color name="Pink_LightPink">#FFB6C1</color>

 <color name="Plum">#DDA0DD</color>
 <color name="Purple">#800080</color>

 <color name="Red">#FF0000</color>
 <color name="Red_Crimson">#DC143C</color>
 <color name="Red_DarkCyan">#008B8B</color>
 <color name="Red_DarkRed">#8B0000</color>
 <color name="Red_FireBrick">#B22222</color>
 <color name="Red_IndianRed">#CD5C5C</color>
 <color name="Red_LightCyan">#E0FFFF</color>
 <color name="Red_MediumVioletRed">#C71585</color>
 <color name="Red_MistyRose">#FFE4E1</color>
 <color name="Red_OrangeRed">#FF4500</color>
 <color name="Red_PaleVioletRed">#DB7093</color>
 <color name="Red_Tomato">#FF6347</color>

 <color name="SaddleBrown">#8B4513</color>
 <color name="Salmon">#FA8072</color>
 <color name="Seashell">#FFF5EE</color>
 <color name="Sienna">#A0522D</color>
 <color name="Silver">#C0C0C0</color>
 <color name="Tan">#D2B48C</color>
 <color name="Thistle">#D8BFD8</color>
 <color name="Turquoise">#40E0D0</color>
 <color name="Violet">#EE82EE</color>

 <color name="White_AntiqueWhite">#FAEBD7</color>
 <color name="White_Azure">#F0FFFF</color>
 <color name="White_Beige">#F5F5DC</color>
 <color name="White_Bisque">#FFE4C4</color>
 <color name="White_FloralWhite">#FFFAF0</color>
 <color name="White_GhostWhite">#F8F8FF</color>
 <color name="White_Honeydew">#F0FFF0</color>
 <color name="White_Ivory">#FFFFF0</color>
 <color name="White_NavajoWhite">#FFDEAD</color>
 <color name="White_Snow">#FFFAFA</color>
 <color name="White_Teal">#008080</color>

<color name="White_transparent_white_hex_1">#11ffffff</color>
<color name="White_transparent_white_hex_10">#aaffffff</color>
<color name="White_transparent_white_hex_11">#bbffffff</color>
<color name="White_transparent_white_hex_12">#ccffffff</color>
<color name="White_transparent_white_hex_13">#ddffffff</color>
<color name="White_transparent_white_hex_14">#eeffffff</color>
<color name="White_transparent_white_hex_15">#ffffffff</color>
<color name="White_transparent_white_hex_2">#22ffffff</color>
<color name="White_transparent_white_hex_3">#33ffffff</color>
<color name="White_transparent_white_hex_4">#44ffffff</color>
<color name="White_transparent_white_hex_5">#55ffffff</color>
<color name="White_transparent_white_hex_6">#66ffffff</color>
<color name="White_transparent_white_hex_7">#77ffffff</color>
<color name="White_transparent_white_hex_8">#88ffffff</color>
<color name="White_transparent_white_hex_9">#99ffffff</color>

<color name="White_transparent_white_percent_10">#1Affffff</color>
<color name="White_transparent_white_percent_15">#26ffffff</color>
<color name="White_transparent_white_percent_20">#33ffffff</color>
<color name="White_transparent_white_percent_25">#40ffffff</color>
<color name="White_transparent_white_percent_30">#4Dffffff</color>
<color name="White_transparent_white_percent_35">#59ffffff</color>
<color name="White_transparent_white_percent_40">#66ffffff</color>
<color name="White_transparent_white_percent_45">#73ffffff</color>
<color name="White_transparent_white_percent_5">#0Dffffff</color>
<color name="White_transparent_white_percent_50">#80ffffff</color>
<color name="White_transparent_white_percent_55">#8Cffffff</color>
<color name="White_transparent_white_percent_60">#99ffffff</color>
<color name="White_transparent_white_percent_65">#A6ffffff</color>
<color name="White_transparent_white_percent_70">#B3ffffff</color>
<color name="White_transparent_white_percent_75">#BFffffff</color>
<color name="White_transparent_white_percent_80">#CCffffff</color>
<color name="White_transparent_white_percent_85">#D9ffffff</color>
<color name="White_transparent_white_percent_90">#E6ffffff</color>
<color name="White_transparent_white_percent_95">#F2ffffff</color>

 <color name="White_Wheat">#F5DEB3</color>
 <color name="White_White">#FFFFFF</color>
 <color name="White_WhiteSmoke">#F5F5F5</color>

 <color name="Yellow">#FFFF00</color>
 <color name="Yellow_DarkGoldenrod">#B8860B</color>
 <color name="Yellow_Gold">#FFD700</color>
 <color name="Yellow_GoldenRod">#DAA520</color>
 <color name="Yellow_LightYellow">#FFFFE0</color>
 <color name="Yellow_PaleGoldenrod">#EEE8AA</color>

Switch tabs using Selenium WebDriver with Java

A brief example of how to switch between tabs in a browser (in case with one window):

// open the first tab
driver.get("https://www.google.com");
Thread.sleep(2000);

// open the second tab
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");
driver.get("https://www.google.com");
Thread.sleep(2000);

// switch to the previous tab
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "" + Keys.SHIFT + "" + Keys.TAB);
Thread.sleep(2000);

I write Thread.sleep(2000) just to have a timeout to see switching between the tabs.

You can use CTRL+TAB for switching to the next tab and CTRL+SHIFT+TAB for switching to the previous tab.

Intro to GPU programming

Take a look at the ATI Stream Computing SDK. It is based on BrookGPU developed at Stanford.

In the future all GPU work will be standardized using OpenCL. It's an Apple-sponsored initiative that will be graphics card vendor neutral.

HTML5 Canvas vs. SVG vs. div

The short answer:

SVG would be easier for you, since selection and moving it around is already built in. SVG objects are DOM objects, so they have "click" handlers, etc.

DIVs are okay but clunky and have awful performance loading at large numbers.

Canvas has the best performance hands-down, but you have to implement all concepts of managed state (object selection, etc) yourself, or use a library.


The long answer:

HTML5 Canvas is simply a drawing surface for a bit-map. You set up to draw (Say with a color and line thickness), draw that thing, and then the Canvas has no knowledge of that thing: It doesn't know where it is or what it is that you've just drawn, it's just pixels. If you want to draw rectangles and have them move around or be selectable then you have to code all of that from scratch, including the code to remember that you drew them.

SVG on the other hand must maintain references to each object that it renders. Every SVG/VML element you create is a real element in the DOM. By default this allows you to keep much better track of the elements you create and makes dealing with things like mouse events easier by default, but it slows down significantly when there are a large number of objects

Those SVG DOM references mean that some of the footwork of dealing with the things you draw is done for you. And SVG is faster when rendering really large objects, but slower when rendering many objects.

A game would probably be faster in Canvas. A huge map program would probably be faster in SVG. If you do want to use Canvas, I have some tutorials on getting movable objects up and running here.

Canvas would be better for faster things and heavy bitmap manipulation (like animation), but will take more code if you want lots of interactivity.

I've run a bunch of numbers on HTML DIV-made drawing versus Canvas-made drawing. I could make a huge post about the benefits of each, but I will give some of the relevant results of my tests to consider for your specific application:

I made Canvas and HTML DIV test pages, both had movable "nodes." Canvas nodes were objects I created and kept track of in Javascript. HTML nodes were movable Divs.

I added 100,000 nodes to each of my two tests. They performed quite differently:

The HTML test tab took forever to load (timed at slightly under 5 minutes, chrome asked to kill the page the first time). Chrome's task manager says that tab is taking up 168MB. It takes up 12-13% CPU time when I am looking at it, 0% when I am not looking.

The Canvas tab loaded in one second and takes up 30MB. It also takes up 13% of CPU time all of the time, regardless of whether or not one is looking at it. (2013 edit: They've mostly fixed that)

Dragging on the HTML page is smoother, which is expected by the design, since the current setup is to redraw EVERYTHING every 30 milliseconds in the Canvas test. There are plenty of optimizations to be had for Canvas for this. (canvas invalidation being the easiest, also clipping regions, selective redrawing, etc.. just depends on how much you feel like implementing)

There is no doubt you could get Canvas to be faster at object manipulation as the divs in that simple test, and of course far faster in the load time. Drawing/loading is faster in Canvas and has far more room for optimizations, too (ie, excluding things that are off-screen is very easy).

Conclusion:

  • SVG is probably better for applications and apps with few items (less than 1000? Depends really)
  • Canvas is better for thousands of objects and careful manipulation, but a lot more code (or a library) is needed to get it off the ground.
  • HTML Divs are clunky and do not scale, making a circle is only possible with rounded corners, making complex shapes is possible but involves hundreds of tiny tiny pixel-wide divs. Madness ensues.

How to automatically generate a stacktrace when my program crashes

Ive been looking at this problem for a while.

And buried deep in the Google Performance Tools README

http://code.google.com/p/google-perftools/source/browse/trunk/README

talks about libunwind

http://www.nongnu.org/libunwind/

Would love to hear opinions of this library.

The problem with -rdynamic is that it can increase the size of the binary relatively significantly in some cases

Finding height in Binary Search Tree

//function to find height of BST

int height(Node* root) {
    if(root == NULL){
        return -1;
    }

    int sum=0;
    int rheight = height(root->right);
    int lheight = height(root->left);

    if(lheight>rheight){
        sum = lheight +1;
    }
    if(rheight > lheight){
        sum = rheight + 1;
    }

    return sum;
}

How to clear basic authentication details in chrome

Just do

https://newUsername:[email protected]

...to override your old credentials.

Chrome ignores autocomplete="off"

Writing a 2020 answer in case if this helps anyone. I tried many combinations above, though there is one key that was missed in my case. Even though I had kept autocomplete="nope" a random string, it didn't work for me because I had name attribute missing!

so I kept name='password' and autocomplete = "new-password"

for username, I kept name="usrid" // DONT KEEP STRING THAT CONTAINS 'user'

and autocomplete = "new-password" // Same for it as well, so google stops suggesting password (manage password dropdown)

this worked very well for me. (I did this for Android and iOS web view that Cordova/ionic uses)

<ion-input [type]="passwordType" name="password" class="input-form-placeholder" formControlName="model_password"
        autocomplete="new-password" [clearInput]="showClearInputIconForPassword">
</ion-input>

How can I reorder a list?

Is the final order defined by a list of indices ?

>>> items = [1, None, "chicken", int]
>>> order = [3, 0, 1, 2]

>>> ordered_list = [items[i] for i in order]
>>> ordered_list
[<type 'int'>, 1, None, 'chicken']

edit: meh. AJ was faster... How can I reorder a list in python?

Copying files into the application folder at compile time

Personally I prefer this way.

Modify the .csproj to add

<ItemGroup>
    <ContentWithTargetPath Include="ConfigFiles\MyFirstConfigFile.txt">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <TargetPath>%(Filename)%(Extension)</TargetPath>
    </ContentWithTargetPath>
</ItemGroup>

or generalizing, if you want to copy all subfolders and files, you could do:

<ItemGroup>
    <ContentWithTargetPath Include="ConfigFiles\**">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <TargetPath>%(RecursiveDir)\%(Filename)%(Extension)</TargetPath>
    </ContentWithTargetPath>
</ItemGroup>

Export table to file with column headers (column names) using the bcp utility and SQL Server 2008

With a little PowerShell script:

_x000D_
_x000D_
sqlcmd -Q "set nocount on select top 0 * from [DB].[schema].[table]" -o c:\temp\header.txt_x000D_
bcp [DB].[schema].[table] out c:\temp\query.txt -c -T -S BRIZA_x000D_
Get-Content c:\temp\*.txt | Set-Content c:\temp\result.txt_x000D_
Remove-Item c:\temp\header.txt_x000D_
Remove-Item c:\temp\query.txt
_x000D_
_x000D_
_x000D_

Warning: The concatenation follows the .txt file name (in alphabetical order)

Difference between Encapsulation and Abstraction

Encapsulation is wrapping up of data and methods in a single unit and making the data accessible only through methods(getter/setter) to ensure safety of data.

Abstraction is hiding internal implementation details of how work is done.

Take and example of following stack class:

Class Stack
{
private top;
void push();
int pop();
}

Now encapsulation helps to safeguard internal data as top cannot be accessed directly outside.

And abstraction helps to do push or pop on stack without worrying about what are steps to push or pop

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

Try it:

git gc --prune=now

git remote prune origin

git pull

How to get Latitude and Longitude of the mobile device in android?

You can use FusedLocationProvider

For using Fused Location Provider in your project you will have to add the google play services location dependency in our app level build.gradle file

dependencies {
   implementation fileTree(dir: 'libs', include: ['*.jar'])
   ...
   ...
   ...
   implementation 'com.google.android.gms:play-services-location:17.0.0'
}

Permissions in Manifest

Apps that use location services must request location permissions. Android offers two location permissions: ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION.

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

As you may know that from Android 6.0 (Marshmallow) you must request permissions for important access in the runtime. Cause it’s a security issue where while installing an application, user may not clearly understand about an important permission of their device.

ActivityCompat.requestPermissions(
    this,
    arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION),
    PERMISSION_ID
)

Then you can use the FusedLocationProvider Client to get the updated location in your desired place.

    mFusedLocationClient.lastLocation.addOnCompleteListener(this) { task ->
        var location: Location? = task.result
        if (location == null) {
            requestNewLocationData()
        } else {
            findViewById<TextView>(R.id.latTextView).text = location.latitude.toString()
            findViewById<TextView>(R.id.lonTextView).text = location.longitude.toString()
        }
    }

You can also check certain configuration like if the device has location settings on or not. You can also check the article on Detect Current Latitude & Longitude using Kotlin in Android for more functionality. If there is no cache location then it will catch the current location using:

private fun requestNewLocationData() {
    var mLocationRequest = LocationRequest()
    mLocationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
    mLocationRequest.interval = 0
    mLocationRequest.fastestInterval = 0
    mLocationRequest.numUpdates = 1

    mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
    mFusedLocationClient!!.requestLocationUpdates(
            mLocationRequest, mLocationCallback,
            Looper.myLooper()
    )
}

The project type is not supported by this installation

For Visual Studio 2010 (prolly also for other versions):

If you are opening an ASP.NET MVC project make sure that the correct MVC version is installed on your PC. If you try to open an ASP.NET MVC 3 project, first close all your visual studio instances and install MVC3: http://www.microsoft.com/en-us/download/details.aspx?id=1491

For other ASP.NET MVC versions download them from www.asp.net/mvc or via Web Platform Installer 4.0.

What is the difference between Trap and Interrupt?

I think Traps are caused by the execution of current instruction and thus they are called as synchronous events. where as interrupts are caused by an independent instruction that is running in the processor which are related to external events and thus are known as asynchronous ones.

How to add Headers on RESTful call using Jersey Client API

This snippet works fine, for sending the Bearer Token using Jersey Client.

    WebTarget webTarget = client.target("endpoint");

    Invocation.Builder invocationBuilder =  webTarget.request(MediaType.APPLICATION_JSON);
    invocationBuilder.header("Authorization", "Bearer "+"Api Key");

    Response response = invocationBuilder.get();

    String responseData = response.readEntity(String.class);

    System.out.println(response.getStatus());
    System.out.println("responseData "+responseData);

ActiveXObject in Firefox or Chrome (not IE!)

No for the moment.

I doubt it will be possible for the future for ActiveX support will be discontinued in near future (as MS stated).

Look here about HTML Object tag, but not anything will be accepted. You should try.

How to get value of Radio Buttons?

Windows Forms

For cases where there are multiple radio buttons to check, this function is very compact:

/// <summary>
/// Get the value of the radio button that is checked.
/// </summary>
/// <param name="buttons">The radio buttons to look through</param>
/// <returns>The name of the radio button that is checked</returns>
public static string GetCheckedRadioButton(params RadioButton[] radioButtons)
{
    // Look at each button, returning the text of the one that is checked.
    foreach (RadioButton button in radioButtons)
    {
        if (button.Checked)
            return button.Text;
    }
    return null;
}

linux script to kill java process

If you just want to kill any/all java processes, then all you need is;

killall java

If, however, you want to kill the wskInterface process in particular, then you're most of the way there, you just need to strip out the process id;

PID=`ps -ef | grep wskInterface | awk '{ print $2 }'`
kill -9 $PID

Should do it, there is probably an easier way though...

how to set radio button checked in edit mode in MVC razor view

Here is how I do it and works both for create and edit:

//How to do it with enums
<div class="editor-field">
   @Html.RadioButtonFor(x => x.gender, (int)Gender.Male) Male
   @Html.RadioButtonFor(x => x.gender, (int)Gender.Female) Female
</div>

//And with Booleans
<div class="editor-field">
   @Html.RadioButtonFor(x => x.IsMale, true) Male
   @Html.RadioButtonFor(x => x.IsMale, false) Female
</div>

the provided values (true and false) are the values that the engine will render as the values for the html element i.e.:

<input id="IsMale" type="radio" name="IsMale" value="True">
<input id="IsMale" type="radio" name="IsMale" value="False">

And the checked property is dependent on the Model.IsMale value.

Razor engine seems to internally match the set radio button value to your model value, if a proper from and to string convert exists for it. So there is no need to add it as an html attribute in the helper method.

How can I pass a parameter to a t-sql script?

Two options save vijay.sql

declare
begin
execute immediate 
'CREATE TABLE DMS_POP_WKLY_REFRESH_'||to_char(sysdate,'YYYYMMDD')||' NOLOGGING PARALLEL AS
SELECT wk.*,bbc.distance_km ,NVL(bbc.tactical_broadband_offer,0) tactical_broadband_offer ,
       sel.tactical_select_executive_flag,
       sel.agent_name,
       res.DMS_RESIGN_CAMPAIGN_CODE,
       pclub.tactical_select_flag
FROM   spineowner.pop_wkly_refresh_20100201 wk,
       dms_bb_coverage_102009 bbc,
       dms_select_executive_group sel,
       DMS_RESIGN_CAMPAIGN_26052009 res,
       DMS_PRIORITY_CLUB pclub
WHERE  wk.mpn = bbc.mpn(+)
AND    wk.mpn = sel.mpn (+)
AND    wk.mpn = res.mpn (+)
AND    wk.mpn = pclub.mpn (+)'
end;
/

The above will generate table names automatically based on sysdate. If you still need to pass as variable, then save vijay.sql as

declare
begin
execute immediate 
'CREATE TABLE DMS_POP_WKLY_REFRESH_'||&1||' NOLOGGING PARALLEL AS
SELECT wk.*,bbc.distance_km ,NVL(bbc.tactical_broadband_offer,0) tactical_broadband_offer ,
       sel.tactical_select_executive_flag,
       sel.agent_name,
       res.DMS_RESIGN_CAMPAIGN_CODE,
       pclub.tactical_select_flag
FROM   spineowner.pop_wkly_refresh_20100201 wk,
       dms_bb_coverage_102009 bbc,
       dms_select_executive_group sel,
       DMS_RESIGN_CAMPAIGN_26052009 res,
       DMS_PRIORITY_CLUB pclub
WHERE  wk.mpn = bbc.mpn(+)
AND    wk.mpn = sel.mpn (+)
AND    wk.mpn = res.mpn (+)
AND    wk.mpn = pclub.mpn (+)'
end;
/

and then run as sqlplus -s username/password @vijay.sql '20100101'

How do I get a human-readable file size in bytes abbreviation using .NET?

Here's a concise answer that determines the unit automatically.

public static string ToBytesCount(this long bytes)
{
    int unit = 1024;
    string unitStr = "b";
    if (bytes < unit) return string.Format("{0} {1}", bytes, unitStr);
    else unitStr = unitStr.ToUpper();
    int exp = (int)(Math.Log(bytes) / Math.Log(unit));
    return string.Format("{0:##.##} {1}{2}", bytes / Math.Pow(unit, exp), "KMGTPEZY"[exp - 1], unitStr);
}

"b" is for bit, "B" is for Byte and "KMGTPEZY" are respectively for kilo, mega, giga, tera, peta, exa, zetta and yotta

One can expand it to take ISO/IEC80000 into account:

public static string ToBytesCount(this long bytes, bool isISO = true)
{
    int unit = 1024;
    string unitStr = "b";
    if (!isISO) unit = 1000;
    if (bytes < unit) return string.Format("{0} {1}", bytes, unitStr);
    else unitStr = unitStr.ToUpper();
    if (isISO) unitStr = "i" + unitStr;
    int exp = (int)(Math.Log(bytes) / Math.Log(unit));
    return string.Format("{0:##.##} {1}{2}", bytes / Math.Pow(unit, exp), "KMGTPEZY"[exp - 1], unitStr);
}

How do I concatenate multiple C++ strings on one line?

Maybe you like my "Streamer" solution to really do it in one line:

#include <iostream>
#include <sstream>
using namespace std;

class Streamer // class for one line string generation
{
public:

    Streamer& clear() // clear content
    {
        ss.str(""); // set to empty string
        ss.clear(); // clear error flags
        return *this;
    }

    template <typename T>
    friend Streamer& operator<<(Streamer& streamer,T str); // add to streamer

    string str() // get current string
    { return ss.str();}

private:
    stringstream ss;
};

template <typename T>
Streamer& operator<<(Streamer& streamer,T str)
{ streamer.ss<<str;return streamer;}

Streamer streamer; // make this a global variable


class MyTestClass // just a test class
{
public:
    MyTestClass() : data(0.12345){}
    friend ostream& operator<<(ostream& os,const MyTestClass& myClass);
private:
    double data;
};

ostream& operator<<(ostream& os,const MyTestClass& myClass) // print test class
{ return os<<myClass.data;}


int main()
{
    int i=0;
    string s1=(streamer.clear()<<"foo"<<"bar"<<"test").str();                      // test strings
    string s2=(streamer.clear()<<"i:"<<i++<<" "<<i++<<" "<<i++<<" "<<0.666).str(); // test numbers
    string s3=(streamer.clear()<<"test class:"<<MyTestClass()).str();              // test with test class
    cout<<"s1: '"<<s1<<"'"<<endl;
    cout<<"s2: '"<<s2<<"'"<<endl;
    cout<<"s3: '"<<s3<<"'"<<endl;
}

How can I list all the deleted files in a Git repository?

Since Windows doesn't have a grep command, this worked for me in PowerShell:

git log --find-renames --diff-filter=D --summary | Select-String -Pattern "delete mode" | sort -u > deletions.txt

Formula to determine brightness of RGB color

This link explains everything in depth, including why those multiplier constants exist before the R, G and B values.

Edit: It has an explanation to one of the answers here too (0.299*R + 0.587*G + 0.114*B)

How to clear an ImageView in Android?

For ListView item image you can set ImageView.setVisibility(View.INVISIBLE) or ImageView.setImageBitmap(null) in list adapter for "no image" case.

Is it possible to delete an object's property in PHP?

This code is working fine for me in a loop

$remove = array(
    "market_value",
    "sector_id"
);

foreach($remove as $key){
    unset($obj_name->$key);
}

HTML5 record audio to file

Update now Chrome also supports MediaRecorder API from v47. The same thing to do would be to use it( guessing native recording method is bound to be faster than work arounds), the API is really easy to use, and you would find tons of answers as to how to upload a blob for the server.

Demo - would work in Chrome and Firefox, intentionally left out pushing blob to server...

Code Source


Currently, there are three ways to do it:

  1. as wav[ all code client-side, uncompressed recording], you can check out --> Recorderjs. Problem: file size is quite big, more upload bandwidth required.
  2. as mp3[ all code client-side, compressed recording], you can check out --> mp3Recorder. Problem: personally, I find the quality bad, also there is this licensing issue.
  3. as ogg [ client+ server(node.js) code, compressed recording, infinite hours of recording without browser crash ], you can check out --> recordOpus, either only client-side recording, or client-server bundling, the choice is yours.

    ogg recording example( only firefox):

    var mediaRecorder = new MediaRecorder(stream);
    mediaRecorder.start();  // to start recording.    
    ...
    mediaRecorder.stop();   // to stop recording.
    mediaRecorder.ondataavailable = function(e) {
        // do something with the data.
    }
    

    Fiddle Demo for ogg recording.

Check if the file exists using VBA

Note your code contains Dir("thesentence") which should be Dir(thesentence).

Change your code to this

Sub test()

thesentence = InputBox("Type the filename with full extension", "Raw Data File")

Range("A1").Value = thesentence

If Dir(thesentence) <> "" Then
    MsgBox "File exists."
Else
    MsgBox "File doesn't exist."
End If

End Sub

test if display = none

You can use the following code to test if display is equivalent to none:

if ($(element).css('display') === 'none' ){
    // do the stuff
}

How to create roles in ASP.NET Core and assign them to users?

I have created an action in the Accounts controller that calls a function to create the roles and assign the Admin role to the default user. (You should probably remove the default user in production):

    private async Task CreateRolesandUsers()
    {  
        bool x = await _roleManager.RoleExistsAsync("Admin");
        if (!x)
        {
            // first we create Admin rool    
            var role = new IdentityRole();
            role.Name = "Admin";
            await _roleManager.CreateAsync(role);

            //Here we create a Admin super user who will maintain the website                   

            var user = new ApplicationUser();
            user.UserName = "default";
            user.Email = "[email protected]";

            string userPWD = "somepassword";

            IdentityResult chkUser = await _userManager.CreateAsync(user, userPWD);

            //Add default User to Role Admin    
            if (chkUser.Succeeded)
            {
                var result1 = await _userManager.AddToRoleAsync(user, "Admin");
            }
        }

        // creating Creating Manager role     
        x = await _roleManager.RoleExistsAsync("Manager");
        if (!x)
        {
            var role = new IdentityRole();
            role.Name = "Manager";
            await _roleManager.CreateAsync(role);
        }

        // creating Creating Employee role     
        x = await _roleManager.RoleExistsAsync("Employee");
        if (!x)
        {
            var role = new IdentityRole();
            role.Name = "Employee";
            await _roleManager.CreateAsync(role);
        }
  }

After you could create a controller to manage roles for the users.

A cycle was detected in the build path of project xxx - Build Path Problem

When I've had these problems it always has been a true cycle in the dependencies expressed in Manifest.mf

So open the manifest of the project in question, on the Dependencies Tab, look at the "Required Plugins" entry. Then follow from there to the next project(s), and repeat eventually the cycle will become clear.

You can simpify this task somewhat by using the Dependency Analysis links in the bottom right corner of the Dependencies Tab, this has cycle detection and easier navigation depdendencies.

I also don't know why Maven is more tolerant,

Is it possible to preview stash contents in git?

View list of stashed changes

git stash list

For viewing list of files changed in a particular stash

git stash show -p stash@{0} --name-only

For viewing a particular file in stash

git show stash@{0} path/to/file

How do I use $scope.$watch and $scope.$apply in AngularJS?

I found very in-depth videos which cover $watch, $apply, $digest and digest cycles in:

Following are a couple of slides used in those videos to explain the concepts (just in case, if the above links are removed/not working).

Enter image description here

In the above image, "$scope.c" is not being watched as it is not used in any of the data bindings (in markup). The other two ($scope.a and $scope.b) will be watched.

Enter image description here

From the above image: Based on the respective browser event, AngularJS captures the event, performs digest cycle (goes through all the watches for changes), execute watch functions and update the DOM. If not browser events, the digest cycle can be manually triggered using $apply or $digest.

More about $apply and $digest:

Enter image description here

About catching ANY exception

Very simple example, similar to the one found here:

http://docs.python.org/tutorial/errors.html#defining-clean-up-actions

If you're attempting to catch ALL exceptions, then put all your code within the "try:" statement, in place of 'print "Performing an action which may throw an exception."'.

try:
    print "Performing an action which may throw an exception."
except Exception, error:
    print "An exception was thrown!"
    print str(error)
else:
    print "Everything looks great!"
finally:
    print "Finally is called directly after executing the try statement whether an exception is thrown or not."

In the above example, you'd see output in this order:

1) Performing an action which may throw an exception.

2) Finally is called directly after executing the try statement whether an exception is thrown or not.

3) "An exception was thrown!" or "Everything looks great!" depending on whether an exception was thrown.

Hope this helps!

How do I verify that an Android apk is signed with a release certificate?

Use console command:

apksigner verify --print-certs application-development-release.apk

You could find apksigner in ../sdk/build-tools/24.0.3/apksigner.bat. Only for build tools v. 24.0.3 and higher.

Also read google docs: https://developer.android.com/studio/command-line/apksigner.html

Storing database records into array

$memberId =$_SESSION['TWILLO']['Id'];

    $QueryServer=mysql_query("select * from smtp_server where memberId='".$memberId."'");
    $data = array();
    while($ser=mysql_fetch_assoc($QueryServer))
    {

     $data[$ser['Id']] =array('ServerName','ServerPort','Server_limit','email','password','status');

    }

In Bootstrap open Enlarge image in modal

I know your question is tagged as boostrap-modal (althought you didn't mentioned Bootstrap explicity neither), but I loved to see the simple way W3.CSS solved this and I think is good to share it.

  <img src="/myImage.png" style="width:30%;cursor:zoom-in"
  onclick="document.getElementById('modal01').style.display='block'">

  <div id="modal01" class="w3-modal" onclick="this.style.display='none'">
    <div class="w3-modal-content w3-animate-zoom">
      <img src="/myImage.png" style="width:100%">
    </div>
  </div>

I let you a link to the W3School modal image example to see the headers to make W3.CSS work.

How do I POST form data with UTF-8 encoding by using curl?

You CAN use UTF-8 in the POST request, all you need is to specify the charset in your request.

You should use this request:

curl -X POST -H "Content-Type: application/x-www-form-urlencoded; charset=utf-8" --data-ascii "content=derinhält&date=asdf" http://myserverurl.com/api/v1/somemethod

Setting Inheritance and Propagation flags with set-acl and powershell

Here's a table to help find the required flags for different permission combinations.

    +-----------------------------------------------------------------------------------------------------------------------------------------------------------+
    ¦             ¦ folder only ¦ folder, sub-folders and files ¦ folder and sub-folders ¦ folder and files ¦ sub-folders and files ¦ sub-folders ¦    files    ¦
    ¦-------------+-------------+-------------------------------+------------------------+------------------+-----------------------+-------------+-------------¦
    ¦ Propagation ¦ none        ¦ none                          ¦ none                   ¦ none             ¦ InheritOnly           ¦ InheritOnly ¦ InheritOnly ¦
    ¦ Inheritance ¦ none        ¦ Container|Object              ¦ Container              ¦ Object           ¦ Container|Object      ¦ Container   ¦ Object      ¦
    +-----------------------------------------------------------------------------------------------------------------------------------------------------------+

So, as David said, you'll want

InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit
PropagationFlags.None

How / can I display a console window in Intellij IDEA?

More IntelliJ 13+ Shortcuts for Terminal

Mac OS X:

alt ?F12

cmd ?shift ?A then type Terminal then hit Enter

shift ?shift ?shift ?shift ? then type Terminal then hit Enter

Windows:

altF12 press Enter

ctrlshift ?A start typing Terminal then hit Enter

shift ?shift ? then type Terminal then hit Enter

Delayed rendering of React components

I think the most intuitive way to do this is by giving the children a "wait" prop, which hides the component for the duration that was passed down from the parent. By setting the default state to hidden, React will still render the component immediately, but it won't be visible until the state has changed. Then, you can set up componentWillMount to call a function to show it after the duration that was passed via props.

var Child = React.createClass({
    getInitialState : function () {
        return({hidden : "hidden"});
    },
    componentWillMount : function () {
        var that = this;
        setTimeout(function() {
            that.show();
        }, that.props.wait);
    },
    show : function () {
        this.setState({hidden : ""});
    },
    render : function () {
        return (
            <div className={this.state.hidden}>
                <p>Child</p>
            </div>
        )
    }
});

Then, in the Parent component, all you would need to do is pass the duration you want a Child to wait before displaying it.

var Parent = React.createClass({
    render : function () {
        return (
            <div className="parent">
                <p>Parent</p>
                <div className="child-list">
                    <Child wait={1000} />
                    <Child wait={3000} />
                    <Child wait={5000} />
                </div>
            </div>
        )
    }
});

Here's a demo

Auto-center map with multiple markers in Google Maps API v3

To find the exact center of the map you'll need to translate the lat/lon coordinates into pixel coordinates and then find the pixel center and convert that back into lat/lon coordinates.

You might not notice or mind the drift depending how far north or south of the equator you are. You can see the drift by doing map.setCenter(map.getBounds().getCenter()) inside of a setInterval, the drift will slowly disappear as it approaches the equator.

You can use the following to translate between lat/lon and pixel coordinates. The pixel coordinates are based on a plane of the entire world fully zoomed in, but you can then find the center of that and switch it back into lat/lon.

   var HALF_WORLD_CIRCUMFERENCE = 268435456; // in pixels at zoom level 21
   var WORLD_RADIUS = HALF_WORLD_CIRCUMFERENCE / Math.PI;

   function _latToY ( lat ) {
      var sinLat = Math.sin( _toRadians( lat ) );
      return HALF_WORLD_CIRCUMFERENCE - WORLD_RADIUS * Math.log( ( 1 + sinLat ) / ( 1 - sinLat ) ) / 2;
   }

   function _lonToX ( lon ) {
      return HALF_WORLD_CIRCUMFERENCE + WORLD_RADIUS * _toRadians( lon );
   }

   function _xToLon ( x ) {
      return _toDegrees( ( x - HALF_WORLD_CIRCUMFERENCE ) / WORLD_RADIUS );
   }

   function _yToLat ( y ) {
      return _toDegrees( Math.PI / 2 - 2 * Math.atan( Math.exp( ( y - HALF_WORLD_CIRCUMFERENCE ) / WORLD_RADIUS ) ) );
   }

   function _toRadians ( degrees ) {
      return degrees * Math.PI / 180;
   }

   function _toDegrees ( radians ) {
      return radians * 180 / Math.PI;
   }

Checking on a thread / remove from list

The answer has been covered, but for simplicity...

# To filter out finished threads
threads = [t for t in threads if t.is_alive()]

# Same thing but for QThreads (if you are using PyQt)
threads = [t for t in threads if t.isRunning()]

How to make a simple popup box in Visual C#?

Why not make use of a tooltip?

private void ShowToolTip(object sender, string message)
{
  new ToolTip().Show(message, this, Cursor.Position.X - this.Location.X, Cursor.Position.Y - this.Location.Y, 1000);
}

The code above will show message for 1000 milliseconds (1 second) where you clicked.

To call it, you can use the following in your button click event:

ShowToolTip("Hello World");

LDAP Authentication using Java

You will have to provide the entire user dn in SECURITY_PRINCIPAL

like this

env.put(Context.SECURITY_PRINCIPAL, "cn=username,ou=testOu,o=test"); 

Is there a way to disable initial sorting for jquery DataTables?

In datatable options put this:

$(document).ready( function() {
  $('#example').dataTable({
    "aaSorting": [[ 2, 'asc' ]], 
    //More options ...

   });
})

Here is the solution: "aaSorting": [[ 2, 'asc' ]],

2 means table will be sorted by third column,
asc in ascending order.

How to select records from last 24 hours using SQL?

Which SQL was not specified, SQL 2005 / 2008

SELECT yourfields from yourTable WHERE yourfieldWithDate > dateadd(dd,-1,getdate())

If you are on the 2008 increased accuracy date types, then use the new sysdatetime() function instead, equally if using UTC times internally swap to the UTC calls.

What is the correct way to declare a boolean variable in Java?

In your example, You don't need to. As a standard programming practice, all variables being referred to inside some code block, say for example try{} catch(){}, and being referred to outside the block as well, you need to declare the variables outside the try block first e.g.

This is helpful when your equals method call throws some exception e.g. NullPointerException;

     boolean isMatch = false;

     try{
         isMatch = email1.equals (email2);
      }catch(NullPointerException npe){
         .....
      }
      System.out.print("Match=="+isMatch);
      if(isMatch){
        ......
      }

Android Fragment handle back button press

We created tiny library for handling back press across multiple fragments and/or in Activity. Usage is as simple as adding dependency in your gradle file:

compile 'net.skoumal.fragmentback:fragment-back:0.1.0'

Let your fragment implement BackFragment interface:

public abstract class MyFragment extends Fragment implements BackFragment {

    public boolean onBackPressed() {

        // -- your code --

        // return true if you want to consume back-pressed event
        return false;
    }

    public int getBackPriority() {
        return NORMAL_BACK_PRIORITY;
    }
}

Notify your fragments about back presses:

public class MainActivity extends AppCompatActivity {

    @Override
    public void onBackPressed() {
        // first ask your fragments to handle back-pressed event
        if(!BackFragmentHelper.fireOnBackPressedEvent(this)) {
            // lets do the default back action if fragments don't consume it
            super.onBackPressed();
        }
    }
}

For more details and other use-cases visit GitHub page:

https://github.com/skoumalcz/fragment-back

How to drop a database with Mongoose?

The difficulty I've had with the other solutions is they rely on restarting your application if you want to get the indexes working again.

For my needs (i.e. being able to run a unit test the nukes all collections, then recreates them along with their indexes), I ended up implementing this solution:

This relies on the underscore.js and async.js libraries to assemble the indexes in parellel, it could be unwound if you're against that library but I leave that as an exerciser for the developer.

mongoose.connection.db.executeDbCommand( {dropDatabase:1}, function(err, result) {
  var mongoPath = mongoose.connections[0].host + ':' + mongoose.connections[0].port + '/' + mongoose.connections[0].name
  //Kill the current connection, then re-establish it
  mongoose.connection.close()
  mongoose.connect('mongodb://' + mongoPath, function(err){
    var asyncFunctions = []

    //Loop through all the known schemas, and execute an ensureIndex to make sure we're clean
    _.each(mongoose.connections[0].base.modelSchemas, function(schema, key) {
      asyncFunctions.push(function(cb){
        mongoose.model(key, schema).ensureIndexes(function(){
          return cb()
        })
      })
    })

    async.parallel(asyncFunctions, function(err) {
      console.log('Done dumping all collections and recreating indexes')
    })
  })
})

How to find sum of multiple columns in a table in SQL Server 2005?

Hi You can use a simple query,

select emp_cd, val1, val2, val3,
(val1+val2+val3) as total 
from emp;

In case you need to insert a new row,

insert into emp select emp_cd, val1, val2, val3,
(val1+val2+val3) as total 
from emp;

In order to update,

update emp set total = val1+val2+val3;

This will update for all comumns

proper way to logout from a session in PHP

Personally, I do the following:

session_start();
setcookie(session_name(), '', 100);
session_unset();
session_destroy();
$_SESSION = array();

That way, it kills the cookie, destroys all data stored internally, and destroys the current instance of the session information (which is ignored by session_destroy).

google chrome extension :: console.log() from background page?

const log = chrome.extension.getBackgroundPage().console.log;
log('something')

Open log:

  • Open: chrome://extensions/
  • Details > Background page

Android error: Failed to install *.apk on device *: timeout

Reboot the phone.

Seriously! Completely power down and power up. That fixed it for me.

How to compile .c file with OpenSSL includes?

For this gcc error, you should reference to to the gcc document about Search Path.

In short:

1) If you use angle brackets(<>) with #include, gcc will search header file firstly from system path such as /usr/local/include and /usr/include, etc.

2) The path specified by -Ldir command-line option, will be searched before the default directories.

3)If you use quotation("") with #include as #include "file", the directory containing the current file will be searched firstly.

so, the answer to your question is as following:

1) If you want to use header files in your source code folder, replace <> with "" in #include directive.

2) if you want to use -I command line option, add it to your compile command line.(if set CFLAGS in environment variables, It will not referenced automatically)

3) About package configuration(openssl.pc), I do not think it will be referenced without explicitly declared in build configuration.

Pandas unstack problems: ValueError: Index contains duplicate entries, cannot reshape

There's a far more simpler solution to tackle this.

The reason why you get ValueError: Index contains duplicate entries, cannot reshape is because, once you unstack "Location", then the remaining index columns "id" and "date" combinations are no longer unique.

You can avoid this by retaining the default index column (row #) and while setting the index using "id", "date" and "location", add it in "append" mode instead of the default overwrite mode.

So use,

e.set_index(['id', 'date', 'location'], append=True)

Once this is done, your index columns will still have the default index along with the set indexes. And unstack will work.

Let me know how it works out.

How can I query a value in SQL Server XML column

You can query the whole tag, or just the specific value. Here I use a wildcard for the xml namespaces.

declare @myDoc xml
set @myDoc = 
'<Root xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://stackoverflow.com">
    <Child>my value</Child>
 </Root>'

select @myDoc.query('/*:Root/*:Child') -- whole tag
select @myDoc.value('(/*:Root/*:Child)[1]', 'varchar(255)') -- only value

Sending Multipart File as POST parameters with RestTemplate requests

You may simply use MultipartHttpServletRequest

Example:

 @RequestMapping(value={"/upload"}, method = RequestMethod.POST,produces = "text/html; charset=utf-8")
 @ResponseBody
 public String upload(MultipartHttpServletRequest request /*@RequestBody MultipartFile file*/){
    String responseMessage = "OK";
    MultipartFile file = request.getFile("file");
    String param = request.getParameter("param");
    try {
        System.out.println(file.getOriginalFilename());
        System.out.println("some param = "+param);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8));
        // read file
    }
    catch(Exception ex){
        ex.printStackTrace();
        responseMessage = "fail";
    }
     return responseMessage;
}

Where parameters names in request.getParameter() must be same with corresponding frontend names.

Note, that file extracted via getFile() while other additional parameters extracted via getParameter()

SSIS package creating Hresult: 0x80004005 Description: "Login timeout expired" error

I had a similar error..This might be due to two reasons. a) If you have used variables, re-evaluate the expressions in which variables are used and make sure the expression is evaluated without errors. b) If you are deleting the excel sheet and creating excel sheet on the fly in your package.

Collections.sort with multiple fields

Sorting with multiple fields in Java8

package com.java8.chapter1;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import static java.util.Comparator.*;



 public class Example1 {

    public static void main(String[] args) {
        List<Employee> empList = getEmpList();


        // Before Java 8 
        empList.sort(new Comparator<Employee>() {

            @Override
            public int compare(Employee o1, Employee o2) {
                int res = o1.getDesignation().compareTo(o2.getDesignation());
                if (res == 0) {
                    return o1.getSalary() > o2.getSalary() ? 1 : o1.getSalary() < o2.getSalary() ? -1 : 0;
                } else {
                    return res;
                }

            }
        });
        for (Employee emp : empList) {
            System.out.println(emp);
        }
        System.out.println("---------------------------------------------------------------------------");

        // In Java 8

        empList.sort(comparing(Employee::getDesignation).thenComparing(Employee::getSalary));
        empList.stream().forEach(System.out::println);

    }
    private static List<Employee> getEmpList() {
        return Arrays.asList(new Employee("Lakshman A", "Consultent", 450000),
                new Employee("Chaitra S", "Developer", 250000), new Employee("Manoj PVN", "Developer", 250000),
                new Employee("Ramesh R", "Developer", 280000), new Employee("Suresh S", "Developer", 270000),
                new Employee("Jaishree", "Opearations HR", 350000));
    }
}

class Employee {
    private String fullName;
    private String designation;
    private double salary;

    public Employee(String fullName, String designation, double salary) {
        super();
        this.fullName = fullName;
        this.designation = designation;
        this.salary = salary;
    }

    public String getFullName() {
        return fullName;
    }

    public String getDesignation() {
        return designation;
    }

    public double getSalary() {
        return salary;
    }

    @Override
    public String toString() {
        return "Employee [fullName=" + fullName + ", designation=" + designation + ", salary=" + salary + "]";
    }

}

What does "exec sp_reset_connection" mean in Sql Server Profiler?

Like the other answers said, sp_reset_connection indicates that connection pool is being reused. Be aware of one particular consequence!

Jimmy Mays' MSDN Blog said:

sp_reset_connection does NOT reset the transaction isolation level to the server default from the previous connection's setting.

UPDATE: Starting with SQL 2014, for client drivers with TDS version 7.3 or higher, the transaction isolation levels will be reset back to the default.

ref: SQL Server: Isolation level leaks across pooled connections

Here is some additional information:

What does sp_reset_connection do?

Data access API's layers like ODBC, OLE-DB and System.Data.SqlClient all call the (internal) stored procedure sp_reset_connection when re-using a connection from a connection pool. It does this to reset the state of the connection before it gets re-used, however nowhere is documented what things get reset. This article tries to document the parts of the connection that get reset.

sp_reset_connection resets the following aspects of a connection:

  • All error states and numbers (like @@error)

  • Stops all EC's (execution contexts) that are child threads of a parent EC executing a parallel query

  • Waits for any outstanding I/O operations that is outstanding

  • Frees any held buffers on the server by the connection

  • Unlocks any buffer resources that are used by the connection

  • Releases all allocated memory owned by the connection

  • Clears any work or temporary tables that are created by the connection

  • Kills all global cursors owned by the connection

  • Closes any open SQL-XML handles that are open

  • Deletes any open SQL-XML related work tables

  • Closes all system tables

  • Closes all user tables

  • Drops all temporary objects

  • Aborts open transactions

  • Defects from a distributed transaction when enlisted

  • Decrements the reference count for users in current database which releases shared database locks

  • Frees acquired locks

  • Releases any acquired handles

  • Resets all SET options to the default values

  • Resets the @@rowcount value

  • Resets the @@identity value

  • Resets any session level trace options using dbcc traceon()

  • Resets CONTEXT_INFO to NULL in SQL Server 2005 and newer [ not part of the original article ]

sp_reset_connection will NOT reset:

  • Security context, which is why connection pooling matches connections based on the exact connection string

  • Application roles entered using sp_setapprole, since application roles could not be reverted at all prior to SQL Server 2005. Starting in SQL Server 2005, app roles can be reverted, but only with additional information that is not part of the session. Before closing the connection, application roles need to be manually reverted via sp_unsetapprole using a "cookie" value that is captured when sp_setapprole is executed.

Note: I am including the list here as I do not want it to be lost in the ever transient web.

How can I convert ArrayList<Object> to ArrayList<String>?

It's not safe to do that!
Imagine if you had:

ArrayList<Object> list = new ArrayList<Object>();
list.add(new Employee("Jonh"));
list.add(new Car("BMW","M3"));
list.add(new Chocolate("Twix"));

It wouldn't make sense to convert the list of those Objects to any type.

What is the equivalent of 'describe table' in SQL Server?

In addition to above questions, if we have table in DB like db_name.dbo.table_name, we may use following steps

  1. Connect with DB

    USE db_name;

  2. Use EXEC sp_help and don't forget to put table name as 'dbo.tablename' if you have dbo as schema.

    exec sp_help 'dbo.table_name'

This should work!

Show a leading zero if a number is less than 10

There's no built-in JavaScript function to do this, but you can write your own fairly easily:

function pad(n) {
    return (n < 10) ? ("0" + n) : n;
}

EDIT:

Meanwhile there is a native JS function that does that. See String#padStart

_x000D_
_x000D_
console.log(String(5).padStart(2, '0'));
_x000D_
_x000D_
_x000D_

SQL Server, division returns zero

if you declare it as float or any decimal format it will display

0

only

E.g :

declare @weight float;

SET @weight= 47 / 638; PRINT @weight

Output : 0

If you want the output as

0.073667712

E.g

declare @weight float;

SET @weight= 47.000000000 / 638.000000000; PRINT @weight

.htaccess rewrite subdomain to directory

For any sub domain request, use this:

RewriteEngine on 
RewriteCond %{HTTP_HOST} !^www\.band\.s\.co 
RewriteCond %{HTTP_HOST} ^(.*)\.band\.s\.co 
RewriteCond %{REQUEST_URI} !^/([a-zA-Z0-9-z\-]+) 
RewriteRule ^(.*)$ /%1/$1 [L] 

Just make some folder same as sub domain name you need. Folder must be exist like this: domain.com/sub for sub.domain.com.

Case statement with multiple values in each 'when' block

Another nice way to put your logic in data is something like this:

# Initialization.
CAR_TYPES = {
  foo_type: ['honda', 'acura', 'mercedes'],
  bar_type: ['toyota', 'lexus']
  # More...
}
@type_for_name = {}
CAR_TYPES.each { |type, names| names.each { |name| @type_for_name[type] = name } }

case @type_for_name[car]
when :foo_type
  # do foo things
when :bar_type
  # do bar things
end

A circular reference was detected while serializing an object of type 'SubSonic.Schema .DatabaseColumn'.

Provided answers are good, but I think they can be improved by adding an "architectural" perspective.

Investigation

MVC's Controller.Json function is doing the job, but it is very poor at providing a relevant error in this case. By using Newtonsoft.Json.JsonConvert.SerializeObject, the error specifies exactly what is the property that is triggering the circular reference. This is particularly useful when serializing more complex object hierarchies.

Proper architecture

One should never try to serialize data models (e.g. EF models), as ORM's navigation properties is the road to perdition when it comes to serialization. Data flow should be the following:

Database -> data models -> service models -> JSON string 

Service models can be obtained from data models using auto mappers (e.g. Automapper). While this does not guarantee lack of circular references, proper design should do it: service models should contain exactly what the service consumer requires (i.e. the properties).

In those rare cases, when the client requests a hierarchy involving the same object type on different levels, the service can create a linear structure with parent->child relationship (using just identifiers, not references).

Modern applications tend to avoid loading complex data structures at once and service models should be slim. E.g.:

  1. access an event - only header data (identifier, name, date etc.) is loaded -> service model (JSON) containing only header data
  2. managed attendees list - access a popup and lazy load the list -> service model (JSON) containing only the list of attendees

Copy table from one database to another

The quickest way is to use a tool, like RazorSQL or Toad for doing this.

Generating HTML email body in C#

I use dotLiquid for exactly this task.

It takes a template, and fills special identifiers with the content of an anonymous object.

//define template
String templateSource = "<h1>{{Heading}}</h1>Dear {{UserName}},<br/><p>First part of the email body goes here");
Template bodyTemplate = Template.Parse(templateSource); // Parses and compiles the template source

//Create DTO for the renderer
var bodyDto = new {
    Heading = "Heading Here",
    UserName = userName
};
String bodyText = bodyTemplate.Render(Hash.FromAnonymousObject(bodyDto));

It also works with collections, see some online examples.

jQuery ajax request being block because Cross-Origin

Try with cURL request for cross-domain.

If you are working through third party APIs or getting data through CROSS-DOMAIN, it is always recommended to use cURL script (server side) which is more secure.

I always prefer cURL script.

Android 8.0: java.lang.IllegalStateException: Not allowed to start service Intent

Due to controversial votes on this answer (+4/-4 as of this edit), PLEASE LOOK AT THE OTHER ANSWERS FIRST AND USE THIS ONLY AS A LAST RESORT. I only used this once for a networking app that runs as root and I agree with the general opinion that this solution should not be used under normal circumstances.

Original answer below:

The other answers are all correct, but I'd like to point out that another way to get around this is to ask user to disable battery optimizations for your app (this isn't usually a good idea unless your app is system related). See this answer for how to request to opt out of battery optimizations without getting your app banned in Google Play.

You should also check whether battery optimizations are turned off in your receiver to prevent crashes via:

if (Build.VERSION.SDK_INT < 26 || getSystemService<PowerManager>()
        ?.isIgnoringBatteryOptimizations(packageName) != false) {
    startService(Intent(context, MyService::class.java))
} // else calling startService will result in crash

Is there a way to iterate over a dictionary?

Yes, NSDictionary supports fast enumeration. With Objective-C 2.0, you can do this:

// To print out all key-value pairs in the NSDictionary myDict
for(id key in myDict)
    NSLog(@"key=%@ value=%@", key, [myDict objectForKey:key]);

The alternate method (which you have to use if you're targeting Mac OS X pre-10.5, but you can still use on 10.5 and iPhone) is to use an NSEnumerator:

NSEnumerator *enumerator = [myDict keyEnumerator];
id key;
// extra parens to suppress warning about using = instead of ==
while((key = [enumerator nextObject]))
    NSLog(@"key=%@ value=%@", key, [myDict objectForKey:key]);

Jenkins fails when running "service start jenkins"

For ubuntu 16.04, there is firewall issue. You need to open 8080 port using following command:

sudo ufw allow 8080

Detailed steps are given here: https://www.digitalocean.com/community/tutorials/how-to-install-jenkins-on-ubuntu-16-04

Is it valid to replace http:// with // in a <script src="http://...">?

1. Summary

Answer for 2019: you can still use protocol-relative URLs, but this technique an anti-pattern.

Also:

  1. You may have problems in developing.
  2. Some third-party tools may not support them.

Migrating from protocol-relative URLs to https:// it would be nice.


2. Relevance

This answer is relevant for January 2019. In the future, the data of this answer may be obsolete.


3. Anti-pattern

3.1. Argumentation

Paul Irish — front-end engineer and a developer advocate for the Google Chromewrite in 2014, December:

Now that SSL is encouraged for everyone and doesn’t have performance concerns, this technique is now an anti-pattern. If the asset you need is available on SSL, then always use the https:// asset.

Allowing the snippet to request over HTTP opens the door for attacks like the recent GitHub Man-on-the-side attack. It’s always safe to request HTTPS assets even if your site is on HTTP, however the reverse is not true.

3.2. Another links

3.3. Examples


4. Developing process

For example, I try to use clean-console.

  • Example file KiraCleanConsole__cdn_links_demo.html:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>clean-console without protocol demonstration</title>
    <!-- Really dead link -->
    <script src="https://unpkg.com/bowser@latest/bowser.min.js"></script>
    <!-- Package exists; link without “https:” -->
    <script src="//cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js"></script>
    <!-- Package exists: link with “https:” -->
    <script src="https://cdn.jsdelivr.net/npm/gemini-scrollbar/index.js"></script>
</head>
<body>
    Kira Goddess!
</body>
</html>
  • output:
D:\SashaDebugging>clean-console -i KiraCleanConsole__cdn_links_demo.html
checking KiraCleanConsole__cdn_links_demo.html
phantomjs: opening page KiraCleanConsole__cdn_links_demo.html

phantomjs: Unable to load resource (#3URL:file://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js)


phantomjs:   phantomjs://code/runner.js:30 in onResourceError
Error code: 203. Description: Error opening //cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js: The network path was not found.

  phantomjs://code/runner.js:31 in onResourceError

phantomjs: Unable to load resource (#5URL:https://unpkg.com/[email protected]/bowser.min.js)


phantomjs:   phantomjs://code/runner.js:30 in onResourceError
Error code: 203. Description: Error downloading https://unpkg.com/[email protected]/bowser.min.js - server replied: Not Found

  phantomjs://code/runner.js:31 in onResourceError

phantomjs: Checking errors after sleeping for 1000ms
2 error(s) on KiraCleanConsole__cdn_links_demo.html

phantomjs process exited with code 2

Link //cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js is valid, but I getting an error.

Pay attention to file://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js and read Thilo and bg17aw answers about file://.

I didn't know about this behavior and couldn't understand why I have problems like this for pageres.


5. Third-party tools

I use Clickable URLs Sublime Text package. Use it, I can simply open links from my text editor in browser.

CSS links examples

Both links in example are valid. But first link I can successfully open in browser use Clickable URLs, second link — no. This may not be very convenient.


6. Conclusion

Yes:

  1. If you have problems as in Developing process item, you can set your development workflow.
  2. Else you have problems as in Third-party tools item, you can contribute tools.

But you don't need this additional problems. Read information by links in Anti-pattern item: protocol-relative URLs is obsolete.

File tree view in Notepad++

You can also use you own computer built-in functions:

  • Create a file, write this on it:
tree /a /f >tree.txt
  • Save the file as any_name_you_want.BAT
  • Launch it, it will create a file named tree.txt that contains you directory TREE.

How to update json file with python

def updateJsonFile():
    jsonFile = open("replayScript.json", "r") # Open the JSON file for reading
    data = json.load(jsonFile) # Read the JSON into the buffer
    jsonFile.close() # Close the JSON file

    ## Working with buffered content
    tmp = data["location"] 
    data["location"] = path
    data["mode"] = "replay"

    ## Save our changes to JSON file
    jsonFile = open("replayScript.json", "w+")
    jsonFile.write(json.dumps(data))
    jsonFile.close()

Convert HTML5 into standalone Android App

You can use https://appery.io/ It is the same phonegap but in very convinient wrapper

Execute curl command within a Python script

Rephrasing one of the answers in this post, instead of using cmd.split(). Try to use:

import shlex

args = shlex.split(cmd)

Then feed args to subprocess.Popen.

Check this doc for more info: https://docs.python.org/2/library/subprocess.html#popen-constructor

reCAPTCHA ERROR: Invalid domain for site key

In case someone has a similar issue. My resolution was to delete the key that was not working and got a new key for my domain. And this now works with all my sub-domains as well without having to explicitly specify them in the recaptcha admin area.

How to evaluate http response codes from bash/shell script?

Although the accepted response is a good answer, it overlooks failure scenarios. curl will return 000 if there is an error in the request or there is a connection failure.

url='http://localhost:8080/'
status=$(curl --head --location --connect-timeout 5 --write-out %{http_code} --silent --output /dev/null ${url})
[[ $status == 500 ]] || [[ $status == 000 ]] && echo restarting ${url} # do start/restart logic

Note: this goes a little beyond the requested 500 status check to also confirm that curl can even connect to the server (i.e. returns 000).

Create a function from it:

failureCode() {
    local url=${1:-http://localhost:8080}
    local code=${2:-500}
    local status=$(curl --head --location --connect-timeout 5 --write-out %{http_code} --silent --output /dev/null ${url})
    [[ $status == ${code} ]] || [[ $status == 000 ]]
}

Test getting a 500:

failureCode http://httpbin.org/status/500 && echo need to restart

Test getting error/connection failure (i.e. 000):

failureCode http://localhost:77777 && echo need to start

Test not getting a 500:

failureCode http://httpbin.org/status/400 || echo not a failure

tsc throws `TS2307: Cannot find module` for a local file

I was in trouble to import an Enum in typescript

error TS2307: Cannot find module...

What I did to make it work was migrate the enum to another file and make this change:

export enum MyEnum{
    VALUE = "MY_VALUE"
}

to

export enum MyEnum{
    VALUE = 1
}

Select distinct values from a list using LINQ in C#

You could implement a custom IEqualityComparer<Employee>:

public class Employee
{
    public string empName { get; set; }
    public string empID { get; set; }
    public string empLoc { get; set; }
    public string empPL { get; set; }
    public string empShift { get; set; }

    public class Comparer : IEqualityComparer<Employee>
    {
        public bool Equals(Employee x, Employee y)
        {
            return x.empLoc == y.empLoc
                && x.empPL == y.empPL
                && x.empShift == y.empShift;
        }

        public int GetHashCode(Employee obj)
        {
            unchecked  // overflow is fine
            {
                int hash = 17;
                hash = hash * 23 + (obj.empLoc ?? "").GetHashCode();
                hash = hash * 23 + (obj.empPL ?? "").GetHashCode();
                hash = hash * 23 + (obj.empShift ?? "").GetHashCode();
                return hash;
            }
        }
    }
}

Now you can use this overload of Enumerable.Distinct:

var distinct = employees.Distinct(new Employee.Comparer());

The less reusable, robust and efficient approach, using an anonymous type:

var distinctKeys = employees.Select(e => new { e.empLoc, e.empPL, e.empShift })
                            .Distinct();
var joined = from e in employees
             join d in distinctKeys
             on new { e.empLoc, e.empPL, e.empShift } equals d
             select e;
// if you want to replace the original collection
employees = joined.ToList();

Get Selected value from dropdown using JavaScript

Working jsbin: http://jsbin.com/ANAYeDU/4/edit

Main bit:

function answers()
{

var element = document.getElementById("mySelect");
var elementValue = element.value;

if(elementValue == "To measure time"){
  alert("Thats correct"); 
  }
}

Invalid column count in CSV input on line 1 Error

Fixed! I basically just selected "Import" without even making a table myself. phpMyAdmin created the table for me, with all the right column names, from the original document.

My Application Could not open ServletContext resource

If you are getting this error with a Java configuration, it is usually because you forget to pass in the application context to the DispatcherServlet constructor:

AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(WebConfig.class);

ServletRegistration.Dynamic dispatcher = sc.addServlet("dispatcher", 
    new DispatcherServlet()); // <-- no constructor args!
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/*");

Fix it by adding the context as the constructor arg:

AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(WebConfig.class);

ServletRegistration.Dynamic dispatcher = sc.addServlet("dispatcher", 
    new DispatcherServlet(ctx)); // <-- hooray! Spring doesn't look for XML files!
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/*");

Iterate through a HashMap

Smarter:

for (String key : hashMap.keySet()) {
    System.out.println("Key: " + key + ", Value: " + map.get(key));
}

This Handler class should be static or leaks might occur: IncomingHandler

This way worked well for me, keeps code clean by keeping where you handle the message in its own inner class.

The handler you wish to use

Handler mIncomingHandler = new Handler(new IncomingHandlerCallback());

The inner class

class IncomingHandlerCallback implements Handler.Callback{

        @Override
        public boolean handleMessage(Message message) {

            // Handle message code

            return true;
        }
}

CSS container div not getting height

Add the following property:

.c{
    ...
    overflow: hidden;
}

This will force the container to respect the height of all elements within it, regardless of floating elements.
http://jsfiddle.net/gtdfY/3/

UPDATE

Recently, I was working on a project that required this trick, but needed to allow overflow to show, so instead, you can use a pseudo-element to clear your floats, effectively achieving the same effect while allowing overflow on all elements.

.c:after{
    clear: both;
    content: "";
    display: block;
}

http://jsfiddle.net/gtdfY/368/

Python update a key in dict if it doesn't exist

You do not need to call d.keys(), so

if key not in d:
    d[key] = value

is enough. There is no clearer, more readable method.

You could update again with dict.get(), which would return an existing value if the key is already present:

d[key] = d.get(key, value)

but I strongly recommend against this; this is code golfing, hindering maintenance and readability.