Programs & Examples On #Apache roller

How to select a column name with a space in MySQL

I think double quotes works too:

SELECT "Business Name","Other Name" FROM your_Table

But I only tested on SQL Server NOT mySQL in case someone work with MS SQL Server.

How to run a makefile in Windows?

With Visual Studio 2017 I had to add this folder to my Windows 10 path env variable:

C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.10.25017\bin\HostX64\x64

There's also HostX86

Customize list item bullets using CSS

<ul>
    <li id="bigger"></li>
    <li></li>
    <li></li>
  </ul>

  <style>
     #bigger .li {height:##px; width:##px;}
  </style>

How to do an update + join in PostgreSQL?

First Table Name: tbl_table1 (tab1). Second Table Name: tbl_table2 (tab2).

Set the tbl_table1's ac_status column to "INACTIVE"

update common.tbl_table1 as tab1
set ac_status= 'INACTIVE' --tbl_table1's "ac_status"
from common.tbl_table2 as tab2
where tab1.ref_id= '1111111' 
and tab2.rel_type= 'CUSTOMER';

Internet Explorer 11 disable "display intranet sites in compatibility view" via meta tag not working

Make sure:

<meta http-equiv="X-UA-Compatible" content="IE=edge">

is the first <meta> tag on your page, otherwise IE may not respect it.

Alternatively, the problem may be that IE is using Enterprise Mode for this website:

  • Your question mentioned that the console shows: HTML1122: Internet Explorer is running in Enterprise Mode emulating IE8.
  • If so you may need to disable enterprise mode (or like this) or turn it off for that website from the Tools menu in IE.
  • However Enterprise Mode should in theory be overridden by the X-UA-Compatible tag, but IE might have a bug...

How do I set the rounded corner radius of a color drawable using xml?

mbaird's answer works fine. Just be aware that there seems to be a bug in Android (2.1 at least), that if you set any individual corner's radius to 0, it forces all the corners to 0 (at least that's the case with "dp" units; I didn't try it with any other units).

I needed a shape where the top corners were rounded and the bottom corners were square. I got achieved this by setting the corners I wanted to be square to a value slightly larger than 0: 0.1dp. This still renders as square corners, but it doesn't force the other corners to be 0 radius.

What is the difference between the | and || or operators?

Good question. These two operators work the same in PHP and C#.

| is a bitwise OR. It will compare two values by their bits. E.g. 1101 | 0010 = 1111. This is extremely useful when using bit options. E.g. Read = 01 (0X01) Write = 10 (0X02) Read-Write = 11 (0X03). One useful example would be opening files. A simple example would be:

File.Open(FileAccess.Read | FileAccess.Write);  //Gives read/write access to the file

|| is a logical OR. This is the way most people think of OR and compares two values based on their truth. E.g. I am going to the store or I will go to the mall. This is the one used most often in code. For example:

if(Name == "Admin" || Name == "Developer") { //allow access } //checks if name equals Admin OR Name equals Developer

PHP Resource: http://us3.php.net/language.operators.bitwise

C# Resources: http://msdn.microsoft.com/en-us/library/kxszd0kx(VS.71).aspx

http://msdn.microsoft.com/en-us/library/6373h346(VS.71).aspx

How would I access variables from one class to another?

var1 and var2 are instance variables. That means that you have to send the instance of ClassA to ClassB in order for ClassB to access it, i.e:

class ClassA(object):
    def __init__(self):
        self.var1 = 1
        self.var2 = 2

    def methodA(self):
        self.var1 = self.var1 + self.var2
        return self.var1



class ClassB(ClassA):
    def __init__(self, class_a):
        self.var1 = class_a.var1
        self.var2 = class_a.var2

object1 = ClassA()
sum = object1.methodA()
object2 = ClassB(object1)
print sum

On the other hand - if you were to use class variables, you could access var1 and var2 without sending object1 as a parameter to ClassB.

class ClassA(object):
    var1 = 0
    var2 = 0
    def __init__(self):
        ClassA.var1 = 1
        ClassA.var2 = 2

    def methodA(self):
        ClassA.var1 = ClassA.var1 + ClassA.var2
        return ClassA.var1



class ClassB(ClassA):
    def __init__(self):
        print ClassA.var1
        print ClassA.var2

object1 = ClassA()
sum = object1.methodA()
object2 = ClassB()
print sum

Note, however, that class variables are shared among all instances of its class.

"id cannot be resolved or is not a field" error?

Just throwing this out there, but try retyping things manually. There's a chance that your quotation marks are the "wrong" ones as there's a similar unicode character which looks similar but is NOT a quotation mark.

If you copy/pasted the code snippits off a website, that might be your problem.

Convert timestamp in milliseconds to string formatted time in Java

It is possible to use apache commons (commons-lang3) and its DurationFormatUtils class.

<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-lang3</artifactId>
  <version>3.1</version>
</dependency>

For example:

String formattedDuration = DurationFormatUtils.formatDurationHMS(12313152);
// formattedDuration value is "3:25:13.152"
String otherFormattedDuration = DurationFormatUtils.formatDuration(12313152, DurationFormatUtils.ISO_EXTENDED_FORMAT_PATTERN);
// otherFormattedDuration value is "P0000Y0M0DT3H25M13.152S"

Hope it can help ...

How to enable scrolling on website that disabled scrolling?

You can paste the following code to the console to scroll up/down using the a/z keyboard keys. If you want to set your own keys you can visit this page to get the keycodes

function KeyPress(e) {
  var evtobj = window.event? event : e
  if (evtobj.keyCode == 90) {
    window.scrollBy(0, 100) 
  }
  if (evtobj.keyCode == 65) {
    window.scrollBy(0, -100) 
  }
}

document.onkeydown = KeyPress;

How do you display JavaScript datetime in 12 hour AM/PM format?

Here is another way that is simple, and very effective:

        var d = new Date();

        var weekday = new Array(7);
        weekday[0] = "Sunday";
        weekday[1] = "Monday";
        weekday[2] = "Tuesday";
        weekday[3] = "Wednesday";
        weekday[4] = "Thursday";
        weekday[5] = "Friday";
        weekday[6] = "Saturday";

        var month = new Array(11);
        month[0] = "January";
        month[1] = "February";
        month[2] = "March";
        month[3] = "April";
        month[4] = "May";
        month[5] = "June";
        month[6] = "July";
        month[7] = "August";
        month[8] = "September";
        month[9] = "October";
        month[10] = "November";
        month[11] = "December";

        var t = d.toLocaleTimeString().replace(/:\d+ /, ' ');

        document.write(weekday[d.getDay()] + ',' + " " + month[d.getMonth()] + " " + d.getDate() + ',' + " " + d.getFullYear() + '<br>' + d.toLocaleTimeString());

    </script></div><!-- #time -->

How to increase the timeout period of web service in asp.net?

1 - You can set a timeout in your application :

var client = new YourServiceReference.YourServiceClass();
client.Timeout = 60; // or -1 for infinite

It is in milliseconds.

2 - Also you can increase timeout value in httpruntime tag in web/app.config :

<configuration>
     <system.web>
          <httpRuntime executionTimeout="<<**seconds**>>" />
          ...
     </system.web>
</configuration>

For ASP.NET applications, the Timeout property value should always be less than the executionTimeout attribute of the httpRuntime element in Machine.config. The default value of executionTimeout is 90 seconds. This property determines the time ASP.NET continues to process the request before it returns a timed out error. The value of executionTimeout should be the proxy Timeout, plus processing time for the page, plus buffer time for queues. -- Source

Read XML file into XmlDocument

If your .NET version is newer than 3.0 you can try using System.Xml.Linq.XDocument instead of XmlDocument. It is easier to process data with XDocument.

Adobe Acrobat Pro make all pages the same dimension

  • Open the PDF in MacOS´ Preview App
  • Chose File menu –> Export as PDF
  • In the export dialog klick the Details button an select your page size
  • Click save

All pages of the resulting document will be scaled to that size. The resulting file size is nearly identical to the original PDF, so I conclude, that image resolutions/compressions are not changed.

Hints:

  1. I am not sure whether the "Export as PDF" menu item is available by default or only if Adobe Acrobat is installed.

  2. My first trial was to use Preview App and print (!) into a new PDF, but this leads to additional margins around the page content.

"Unorderable types: int() < str()"

Just a side note, in Python 2.0 you could compare anything to anything (int to string). As this wasn't explicit, it was changed in 3.0, which is a good thing as you are not running into the trouble of comparing senseless values with each other or when you forget to convert a type.

More elegant "ps aux | grep -v grep"

You could use preg_split instead of explode and split on [ ]+ (one or more spaces). But I think in this case you could go with preg_match_all and capturing:

preg_match_all('/[ ]php[ ]+\S+[ ]+(\S+)/', $input, $matches);
$result = $matches[1];

The pattern matches a space, php, more spaces, a string of non-spaces (the path), more spaces, and then captures the next string of non-spaces. The first space is mostly to ensure that you don't match php as part of a user name but really only as a command.

An alternative to capturing is the "keep" feature of PCRE. If you use \K in the pattern, everything before it is discarded in the match:

preg_match_all('/[ ]php[ ]+\S+[ ]+\K\S+/', $input, $matches);
$result = $matches[0];

I would use preg_match(). I do something similar for many of my system management scripts. Here is an example:

$test = "user     12052  0.2  0.1 137184 13056 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust1 cron
user     12054  0.2  0.1 137184 13064 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust3 cron
user     12055  0.6  0.1 137844 14220 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust4 cron
user     12057  0.2  0.1 137184 13052 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust89 cron
user     12058  0.2  0.1 137184 13052 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust435 cron
user     12059  0.3  0.1 135112 13000 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust16 cron
root     12068  0.0  0.0 106088  1164 pts/1    S+   10:00   0:00 sh -c ps aux | grep utilities > /home/user/public_html/logs/dashboard/currentlyPosting.txt
root     12070  0.0  0.0 103240   828 pts/1    R+   10:00   0:00 grep utilities";

$lines = explode("\n", $test);

foreach($lines as $line){
        if(preg_match("/.php[\s+](cust[\d]+)[\s+]cron/i", $line, $matches)){
                print_r($matches);
        }

}

The above prints:

Array
(
    [0] => .php cust1 cron
    [1] => cust1
)
Array
(
    [0] => .php cust3 cron
    [1] => cust3
)
Array
(
    [0] => .php cust4 cron
    [1] => cust4
)
Array
(
    [0] => .php cust89 cron
    [1] => cust89
)
Array
(
    [0] => .php cust435 cron
    [1] => cust435
)
Array
(
    [0] => .php cust16 cron
    [1] => cust16
)

You can set $test to equal the output from exec. the values you are looking for would be in the if statement under the foreach. $matches[1] will have the custx value.

How to show progress bar while loading, using ajax

<script>
$(function() {
    $("#client").on("change", function() {
      var clientid=$("#client").val();
     //show the loading div here
    $.ajax({
            type:"post",
            url:"clientnetworkpricelist/yourfile.php",
        data:"title="+clientid,
        success:function(data){
             $("#result").html(data);
          //hide the loading div here
        }
    }); 
    });
});
</script>

Or you can also do this:

$(document).ajaxStart(function() {
        // show loader on start
        $("#loader").css("display","block");
    }).ajaxSuccess(function() {
        // hide loader on success
        $("#loader").css("display","none");
    });

What's the difference between ConcurrentHashMap and Collections.synchronizedMap(Map)?

You are right about HashTable, you can forget about it.

Your article mentions the fact that while HashTable and the synchronized wrapper class provide basic thread-safety by only allowing one thread at a time to access the map, this is not 'true' thread-safety since many compound operations still require additional synchronization, for example:

synchronized (records) {
  Record rec = records.get(id);
  if (rec == null) {
      rec = new Record(id);
      records.put(id, rec);
  }
  return rec;
}

However, don't think that ConcurrentHashMap is a simple alternative for a HashMap with a typical synchronized block as shown above. Read this article to understand its intricacies better.

Enter export password to generate a P12 certificate

OpenSSL command line app does not display any characters when you are entering your password. Just type it then press enter and you will see that it is working.

You can also use openssl pkcs12 -export -inkey mykey.key -in developer_identity.pem -out iphone_dev.p12 -password pass:YourPassword to pass the password YourPassword from command line. Please take a look at section Pass Phrase Options in OpenSSL manual for more information.

Unable to find the requested .Net Framework Data Provider. It may not be installed. - when following mvc3 asp.net tutorial

I was able to solve a problem similar to this in Visual Studio 2010 by using NuGet.

Go to Tools > Library Package Manager > Manage NuGet Packages For Solution...

In the dialog, search for "EntityFramework.SqlServerCompact". You'll find a package with the description "Allows SQL Server Compact 4.0 to be used with Entity Framework." Install this package.

An element similar to the following will be inserted in your web.config:

<entityFramework>
  <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlCeConnectionFactory, EntityFramework">
    <parameters>
      <parameter value="System.Data.SqlServerCe.4.0" />
    </parameters>
  </defaultConnectionFactory>
</entityFramework>

How to change onClick handler dynamically?

Try:

document.getElementById("foo").onclick = function (){alert('foo');};

How to insert strings containing slashes with sed?

The s command can use any character as a delimiter; whatever character comes after the s is used. I was brought up to use a #. Like so:

s#?page=one&#/page/one#g

nginx: [emerg] "server" directive is not allowed here

That is not an nginx configuration file. It is part of an nginx configuration file.

The nginx configuration file (usually called nginx.conf) will look like:

events {
    ...
}
http {
    ...
    server {
        ...
    }
}

The server block is enclosed within an http block.

Often the configuration is distributed across multiple files, by using the include directives to pull in additional fragments (for example from the sites-enabled directory).

Use sudo nginx -t to test the complete configuration file, which starts at nginx.conf and pulls in additional fragments using the include directive. See this document for more.

What's the difference between align-content and align-items?

I had the same confusion. After some tinkering based on many of the answers above, I can finally see the differences. In my humble opinion, the distinction is best demonstrated with a flex container that satisfies the following two conditions:

  1. The flex container itself has a height constraint (e.g., min-height: 60rem) and thus can become too tall for its content
  2. The child items enclosed in the container have uneven heights

Condition 1 helps me understand what content means relative to its parent container. When the content is flush with the container, we will not be able to see any positioning effects coming from align-content. It is only when we have extra space along the cross axis, we start to see its effect: It aligns the content relative to the boundaries of the parent container.

Condition 2 helps me visualize the effects of align-items: it aligns items relative to each other.


Here is a code example. Raw materials come from Wes Bos' CSS Grid tutorial (21. Flexbox vs. CSS Grid)

  • Example HTML:
  <div class="flex-container">
    <div class="item">Short</div>
    <div class="item">Longerrrrrrrrrrrrrr</div>
    <div class="item"></div>
    <div class="item" id="tall">This is Many Words</div>
    <div class="item">Lorem, ipsum.</div>
    <div class="item">10</div>
    <div class="item">Snickers</div>
    <div class="item">Wes Is Cool</div>
    <div class="item">Short</div>
  </div>
  • Example CSS:
.flex-container {
  display: flex;
  /*dictates a min-height*/
  min-height: 60rem;
  flex-flow: row wrap;
  border: 5px solid white;
  justify-content: center;
  align-items: center;
  align-content: flex-start;
 }

#tall {
  /*intentionally made tall*/
  min-height: 30rem;
}

.item {
  margin: 10px;
  max-height: 10rem;
}

Example 1: Let's narrow the viewport so that the content is flush with the container. This is when align-content: flex-start; has no effects since the entire content block is tightly fit inside the container (no extra room for repositioning!)

Also, note the 2nd row--see how the items are center aligned among themselves.

enter image description here

Example 2: As we widen the viewport, we no longer have enough content to fill the entire container. Now we start to see the effects of align-content: flex-start;--it aligns the content relative to the top edge of the container. enter image description here


These examples are based on flexbox, but the same principles are applicable to CSS grid. Hope this helps :)

How to get a list of current open windows/process with Java?

On Windows there is an alternative using JNA:

import com.sun.jna.Native;
import com.sun.jna.platform.win32.*;
import com.sun.jna.win32.W32APIOptions;

public class ProcessList {

    public static void main(String[] args) {
        WinNT winNT = (WinNT) Native.loadLibrary(WinNT.class, W32APIOptions.UNICODE_OPTIONS);

        WinNT.HANDLE snapshot = winNT.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPPROCESS, new WinDef.DWORD(0));

        Tlhelp32.PROCESSENTRY32.ByReference processEntry = new Tlhelp32.PROCESSENTRY32.ByReference();

        while (winNT.Process32Next(snapshot, processEntry)) {
            System.out.println(processEntry.th32ProcessID + "\t" + Native.toString(processEntry.szExeFile));
        }

        winNT.CloseHandle(snapshot);
    }
}

Force table column widths to always be fixed regardless of contents

You can also work with "overflow: hidden" or "overflow-x: hidden" (for just the width). This requires a defined width (and/or height?) and maybe a "display: block" as well.

"Overflow:Hidden" hides the whole content, which does not fit into the defined box.

Example:

http://jsfiddle.net/NAJvp/

HTML:

<table border="1">
    <tr>
        <td><div>aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</div></td>
        <td>bbb</td>
        <td>cccc</td>
    </tr>
</table>

CSS:

td div { width: 100px; overflow-y: hidden; }

EDIT: Shame on me, I've seen, you already use "overflow". I guess it doesn't work, because you don't set "display: block" to your element ...

How to click a browser button with JavaScript automatically?

this will work ,simple and easy

 `<form method="POST">
<input  type="submit" onclick="myFunction()" class="save" value="send" name="send" id="send" style="width:20%;">
</form>
<script language ="javascript" >
function myFunction() {
setInterval(function() {document.getElementById("send").click();}, 10000);    
}
</script>

`

How to do this using jQuery - document.getElementById("selectlist").value

Chaos is spot on, though for these sorts of questions you should check out the Jquery Documentation online - it really is quite comprehensive. The feature you are after is called 'jquery selectors'

Generally you do $('#ID').val() - the .afterwards can do a number of things on the element that is returned from the selector. You can also select all of the elements on a certain class and do something to each of them. Check out the documentation for some good examples.

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

sectionLabel.font = [UIFont fontWithName:@"TrebuchetMS-Bold" size:18];

There is a list of font names that you can set in place of 'fontWithName' attribute.The link is here

SQL select everything in an array

// array of $ids that you need to select
$ids = array('1', '2', '3', '4', '5', '6', '7', '8');

// create sql part for IN condition by imploding comma after each id
$in = '(' . implode(',', $ids) .')';

// create sql
$sql = 'SELECT * FROM products WHERE catid IN ' . $in;

// see what you get
var_dump($sql);

Update: (a short version and update missing comma)

$ids = array('1','2','3','4');
$sql = 'SELECT * FROM products WHERE catid IN (' . implode(',', $ids) . ')';

Converting from hex to string

My Net 5 solution that also handles null characters at the end:

hex = ConvertFromHex( hex.AsSpan(), Encoding.Default );

static string ConvertFromHex( ReadOnlySpan<char> hexString, Encoding encoding )
{
    int realLength = 0;
    for ( int i = hexString.Length - 2; i >= 0; i -= 2 )
    {
        byte b = byte.Parse( hexString.Slice( i, 2 ), NumberStyles.HexNumber, CultureInfo.InvariantCulture );
        if ( b != 0 ) //not NULL character
        {
            realLength = i + 2;
            break;
        }
    }
    
    var bytes = new byte[realLength / 2];
    for ( var i = 0; i < bytes.Length; i++ )
    {
        bytes[i] = byte.Parse( hexString.Slice( i * 2, 2 ), NumberStyles.HexNumber, CultureInfo.InvariantCulture );
    }

    return encoding.GetString( bytes );
}

how to apply click event listener to image in android

ImageView img = (ImageView) findViewById(R.id.myImageId);
img.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
       // your code here
    }
});

$.browser is undefined error

The .browser call has been removed in jquery 1.9 have a look at http://jquery.com/upgrade-guide/1.9/ for more details.

Select a Column in SQL not in Group By

You can join the table on itself to get the PK:

Select cpe1.PK, cpe2.MaxDate, cpe1.fmgcms_cpeclaimid 
from Filteredfmgcms_claimpaymentestimate cpe1
INNER JOIN
(
    select MAX(createdon) As MaxDate, fmgcms_cpeclaimid 
    from Filteredfmgcms_claimpaymentestimate
    group by fmgcms_cpeclaimid
) cpe2
    on cpe1.fmgcms_cpeclaimid = cpe2.fmgcms_cpeclaimid
    and cpe1.createdon = cpe2.MaxDate
where cpe1.createdon < 'reportstartdate'

Android: how to convert whole ImageView to Bitmap?

You could just use the imageView's image cache. It will render the entire view as it is layed out (scaled,bordered with a background etc) to a new bitmap.

just make sure it built.

imageView.buildDrawingCache();
Bitmap bmap = imageView.getDrawingCache();

there's your bitmap as the screen saw it.

java.lang.ClassNotFoundException: javax.servlet.jsp.jstl.core.Config

Download the following jars and add it to your WEB-INF/lib directory:

List all sequences in a Postgres db 8.1 with SQL

select sequence_name, (xpath('/row/last_value/text()', xml_count))[1]::text::int as last_value
from (
    select sequence_schema,
            sequence_name,         
            query_to_xml(format('select last_value from %I.%I', sequence_schema, sequence_name), false, true, '') as xml_count
    from information_schema.sequences
    where sequence_schema = 'public'
) new_table order by last_value desc;

How Can I Remove “public/index.php” in the URL Generated Laravel?

You have to perform following steps to do this, which are as follows

  • Map your domain upto public folder of your project (i.e. /var/www/html/yourproject/public) (if using linux)

  • Go to your public folder edit your .htaccess file there

AddHandler application/x-httpd-php72 .php
<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect non-www to www
    RewriteCond %{HTTP_HOST} !^www\.
    RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

    # Redirect non-http to https
    RewriteCond %{HTTPS} off
    RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]

    # Remove index.php
    RewriteCond %{THE_REQUEST} ^GET.*index\.php [NC]
    RewriteRule (.*?)index\.php/*(.*) /$1$2 [R=301,NE,L]
</IfModule>


  • The last three rules are for if you are directly accessing any route without https, it protect that.

Laravel whereIn OR whereIn

You could have searched just for whereIn function in the core to see that. Here you are. This must answer all your questions

/**
 * Add a "where in" clause to the query.
 *
 * @param  string  $column
 * @param  mixed   $values
 * @param  string  $boolean
 * @param  bool    $not
 * @return \Illuminate\Database\Query\Builder|static
 */
public function whereIn($column, $values, $boolean = 'and', $not = false)
{
    $type = $not ? 'NotIn' : 'In';

    // If the value of the where in clause is actually a Closure, we will assume that
    // the developer is using a full sub-select for this "in" statement, and will
    // execute those Closures, then we can re-construct the entire sub-selects.
    if ($values instanceof Closure)
    {
        return $this->whereInSub($column, $values, $boolean, $not);
    }

    $this->wheres[] = compact('type', 'column', 'values', 'boolean');

    $this->bindings = array_merge($this->bindings, $values);

    return $this;
}

Look that it has a third boolean param. Good luck.

How to exit git log or git diff

Add following alias in the .bashrc file

git --no-pager log --oneline -n 10
  • --no-pager will encounter the (END) word
  • -n 10 will show only the last 10 commits
  • --oneline will show the commit message, ignore the author, date information

How to call a php script/function on a html button click

the_function() {

$.ajax({url:"demo_test.php",success:function(result){

   alert(result); // will alert 1

 }});

}

// demo_test.php

<?php echo 1; ?>

Notes

  1. Include jquery library for using the jquery Ajax
  2. Keep the demo_test.php file in the same folder where your javascript file resides

MongoDB: How To Delete All Records Of A Collection in MongoDB Shell?

To remove all the documents in all the collections:

db.getCollectionNames().forEach( function(collection_name) { 
    if (collection_name.indexOf("system.") == -1) {
        print ( ["Removing: ", db[collection_name].count({}), " documents from ", collection_name].join('') );
        db[collection_name].remove({}); 
    }
});

Get img src with PHP

I have done that the more simple way, not as clean as it should be but it was a quick hack

$htmlContent = file_get_contents('pageURL');

// read all image tags into an array
preg_match_all('/<img[^>]+>/i',$htmlContent, $imgTags); 

for ($i = 0; $i < count($imgTags[0]); $i++) {
  // get the source string
  preg_match('/src="([^"]+)/i',$imgTags[0][$i], $imgage);

  // remove opening 'src=' tag, can`t get the regex right
  $origImageSrc[] = str_ireplace( 'src="', '',  $imgage[0]);
}
// will output all your img src's within the html string
print_r($origImageSrc);

Get file from project folder java

Just did a quick google search and found that

System.getProperty("user.dir");

returns the current working directory as String. So to get a File out of this, just use

File projectDir = new File(System.getProperty("user.dir"));

How to get N rows starting from row M from sorted table in T-SQL

SELECT * FROM (
  SELECT
    Row_Number() Over (Order by (Select 1)) as RawKey,
    * 
  FROM [Alzh].[dbo].[DM_THD_TRANS_FY14]
) AS foo
WHERE RawKey between 17210400 and 17210500

Form Submit jQuery does not work

You can use jQuery like this:

$(function() {
    $("#form").submit(function(event) {
        // do some validation, for example:
        username = $("#username").val();
        if (username.length >= 8)
            return; // valid
        event.preventDefault(); // invalidates the form
    });
});

In your HTML:

<form id="form" method="post">
    <input type="text" name="username" required id="username">
    <button type="submit">Submit</button>
</form>

References:

https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit_event https://api.jquery.com/submit/

PHPmailer sending HTML CODE

In version 5.2.7 I use this to send plain text: $mail->set('Body', $Body);

How to make a copy of an object in C#

You can use MemberwiseClone

obj myobj2 = (obj)myobj.MemberwiseClone();

The copy is a shallow copy which means the reference properties in the clone are pointing to the same values as the original object but that shouldn't be an issue in your case as the properties in obj are of value types.

If you own the source code, you can also implement ICloneable

set div height using jquery (stretch div height)

Off the top of my head:

$('#content').height(
    $(window).height() - $('#header').height() - $('#footer').height()
);

Is that what you mean?

How do I select child elements of any depth using XPath?

If you are using the XmlDocument and XmlNode.

Say:

XmlNode f = root.SelectSingleNode("//form[@id='myform']");

Use:

XmlNode s = f.SelectSingleNode(".//input[@type='submit']");

It depends on the tool that you use. But .// will select any child, any depth from a reference node.

Pad a string with leading zeros so it's 3 characters long in SQL Server 2008

Simple is that

Like:

DECLARE @DUENO BIGINT
SET @DUENO=5

SELECT 'ND'+STUFF('000000',6-LEN(RTRIM(@DueNo))+1,LEN(RTRIM(@DueNo)),RTRIM(@DueNo)) DUENO

Laravel blank white screen

On normal cases errors should be logged Unless

Script can't write to log file

  • check it's path
  • permissions

Or error occurred on higher level check app server logs like Appache || Nginx

Or it's resources limits Like PHP ini settings

memory_limit
max_input_time
max_execution_time

Or OS limit's and so on

Searching for file in directories recursively

you can do something like this:

foreach (var file in Directory.GetFiles(MyFolder, "*.xml", SearchOption.AllDirectories))
        {
            // do something with this file
        }

How do I link object files in C? Fails with "Undefined symbols for architecture x86_64"

Add foo1.c , foo2.c , foo3.c and makefile in one folder the type make in bash

if you do not want to use the makefile, you can run the command

gcc -c foo1.c foo2.c foo3.c

then

gcc -o output foo1.o foo2.o foo3.o

foo1.c

#include <stdio.h>
#include <string.h>

void funk1();

void funk1() {
    printf ("\nfunk1\n");
}


int main(void) {

    char *arg2;
    size_t nbytes = 100;

    while ( 1 ) {

        printf ("\nargv2 = %s\n" , arg2);
        printf ("\n:> ");
        getline (&arg2 , &nbytes , stdin);
        if( strcmp (arg2 , "1\n") == 0 ) {
            funk1 ();
        } else if( strcmp (arg2 , "2\n") == 0 ) {
            funk2 ();
        } else if( strcmp (arg2 , "3\n") == 0 ) {
            funk3 ();
        } else if( strcmp (arg2 , "4\n") == 0 ) {
            funk4 ();
        } else {
            funk5 ();
        }
    }
}

foo2.c

#include <stdio.h>
void funk2(){
    printf("\nfunk2\n");
}
void funk3(){
    printf("\nfunk3\n");
}

foo3.c

#include <stdio.h>

void funk4(){
    printf("\nfunk4\n");
}
void funk5(){
    printf("\nfunk5\n");
}

makefile

outputTest: foo1.o foo2.o foo3.o
    gcc -o output foo1.o foo2.o foo3.o
    make removeO

outputTest.o: foo1.c foo2.c foo3.c
    gcc -c foo1.c foo2.c foo3.c

clean:
    rm -f *.o output

removeO:
    rm -f *.o

Copy entire contents of a directory to another using php

Like said elsewhere, copy only works with a single file for source and not a pattern. If you want to copy by pattern, use glob to determine the files, then run copy. This will not copy subdirectories though, nor will it create the destination directory.

function copyToDir($pattern, $dir)
{
    foreach (glob($pattern) as $file) {
        if(!is_dir($file) && is_readable($file)) {
            $dest = realpath($dir . DIRECTORY_SEPARATOR) . basename($file);
            copy($file, $dest);
        }
    }    
}
copyToDir('./test/foo/*.txt', './test/bar'); // copies all txt files

Java Switch Statement - Is "or"/"and" possible?

From what I understand about your question, before passing the character into the switch statement, you can convert it to lowercase. So you don't have to worry about upper cases because they are automatically converted to lower case. For that you need to use the below function:

Character.toLowerCase(c);

How to filter array when object key value is in array

In 2019 using ES6:

_x000D_
_x000D_
const ids = [1, 4, 5],_x000D_
  data = {_x000D_
    records: [{_x000D_
      "empid": 1,_x000D_
      "fname": "X",_x000D_
      "lname": "Y"_x000D_
    }, {_x000D_
      "empid": 2,_x000D_
      "fname": "A",_x000D_
      "lname": "Y"_x000D_
    }, {_x000D_
      "empid": 3,_x000D_
      "fname": "B",_x000D_
      "lname": "Y"_x000D_
    }, {_x000D_
      "empid": 4,_x000D_
      "fname": "C",_x000D_
      "lname": "Y"_x000D_
    }, {_x000D_
      "empid": 5,_x000D_
      "fname": "C",_x000D_
      "lname": "Y"_x000D_
    }]_x000D_
  };_x000D_
_x000D_
_x000D_
data.records = data.records.filter( i => ids.includes( i.empid ) );_x000D_
_x000D_
console.info( data );
_x000D_
_x000D_
_x000D_

What's the difference between HEAD, working tree and index, in Git?

This is an inevitably long yet easy to follow explanation from ProGit book:

Note: For reference you can read Chapter 7.7 of the book, Reset Demystified

Git as a system manages and manipulates three trees in its normal operation:

  • HEAD: Last commit snapshot, next parent
  • Index: Proposed next commit snapshot
  • Working Directory: Sandbox

The HEAD

HEAD is the pointer to the current branch reference, which is in turn a pointer to the last commit made on that branch. That means HEAD will be the parent of the next commit that is created. It’s generally simplest to think of HEAD as the snapshot of your last commit on that branch.

What does it contain?
To see what that snapshot looks like run the following in root directory of your repository:

                                 git ls-tree -r HEAD

it would result in something like this:

                       $ git ls-tree -r HEAD  
                       100644 blob a906cb2a4a904a152... README  
                       100644 blob 8f94139338f9404f2... Rakefile  
                       040000 tree 99f1a6d12cb4b6f19... lib  

The Index

Git populates this index with a list of all the file contents that were last checked out into your working directory and what they looked like when they were originally checked out. You then replace some of those files with new versions of them, and git commit converts that into the tree for a new commit.

What does it contain?
Use git ls-files -s to see what it looks like. You should see something like this:

                 100644 a906cb2a4a904a152e80877d4088654daad0c859 0 README   
                 100644 8f94139338f9404f26296befa88755fc2598c289 0 Rakefile  
                 100644 47c6340d6459e05787f644c2447d2595f5d3a54b 0 lib/simplegit.rb  

The Working Directory

This is where your files reside and where you can try changes out before committing them to your staging area (index) and then into history.

Visualized Sample

Let's see how do these three trees (As the ProGit book refers to them) work together?
Git’s typical workflow is to record snapshots of your project in successively better states, by manipulating these three trees. Take a look at this picture:

enter image description here

To get a good visualized understanding consider this scenario. Say you go into a new directory with a single file in it. Call this v1 of the file. It is indicated in blue. Running git init will create a Git repository with a HEAD reference which points to the unborn master branch

enter image description here

At this point, only the working directory tree has any content. Now we want to commit this file, so we use git add to take content in the working directory and copy it to the index.

enter image description here

Then we run git commit, which takes the contents of the index and saves it as a permanent snapshot, creates a commit object which points to that snapshot, and updates master to point to that commit.

enter image description here

If we run git status, we’ll see no changes, because all three trees are the same.

The beautiful point

git status shows the difference between these trees in the following manner:

  • If the Working Tree is different from index, then git status will show there are some changes not staged for commit
  • If the Working Tree is the same as index, but they are different from HEAD, then git status will show some files under changes to be committed section in its result
  • If the Working Tree is different from the index, and index is different from HEAD, then git status will show some files under changes not staged for commit section and some other files under changes to be committed section in its result.

For the more curious

Note about git reset command
Hopefully, knowing how reset command works will further brighten the reason behind the existence of these three trees.

reset command is your Time Machine in git which can easily take you back in time and bring some old snapshots for you to work on. In this manner, HEAD is the wormhole through which you can travel in time. Let's see how it works with an example from the book:

Consider the following repository which has a single file and 3 commits which are shown in different colours and different version numbers:

enter image description here

The state of trees is like the next picture:

enter image description here

Step 1: Moving HEAD (--soft):

The first thing reset will do is move what HEAD points to. This isn’t the same as changing HEAD itself (which is what checkout does). reset moves the branch that HEAD is pointing to. This means if HEAD is set to the master branch, running git reset 9e5e6a4 will start by making master point to 9e5e6a4. If you call reset with --soft option it will stop here, without changing index and working directory. Our repo will look like this now:
Notice: HEAD~ is the parent of HEAD

enter image description here

Looking a second time at the image, we can see that the command essentially undid the last commit. As the working tree and the index are the same but different from HEAD, git status will now show changes in green ready to be committed.

Step 2: Updating the index (--mixed):

This is the default option of the command

Running reset with --mixed option updates the index with the contents of whatever snapshot HEAD points to currently, leaving Working Directory intact. Doing so, your repository will look like when you had done some work that is not staged and git status will show that as changes not staged for commit in red. This option will also undo the last commit and also unstage all the changes. It's like you made changes but have not called git add command yet. Our repo would look like this now:

enter image description here

Step 3: Updating the Working Directory (--hard)

If you call reset with --hard option it will copy contents of the snapshot HEAD is pointing to into HEAD, index and Working Directory. After executing reset --hard command, it would mean like you got back to a previous point in time and haven't done anything after that at all. see the picture below:

enter image description here

Conclusion

I hope now you have a better understanding of these trees and have a great idea of the power they bring to you by enabling you to change your files in your repository to undo or redo things you have done mistakenly.

How to do a num_rows() on COUNT query in codeigniter?

$query->num_rows()

The number of rows returned by the query. Note: In this example, $query is the variable that the query result object is assigned to:

$query = $this->db->query('SELECT * FROM my_table');

echo $query->num_rows();

JUnit test for System.out.println()

You don't want to redirect the system.out stream because that redirects for the ENTIRE JVM. Anything else running on the JVM can get messed up. There are better ways to test input/output. Look into stubs/mocks.

"Application tried to present modally an active controller"?

In my case, I was presenting the rootViewController of an UINavigationController when I was supposed to present the UINavigationController itself.

SQL Query - Concatenating Results into One String

For SQL Server 2005 and above use Coalesce for nulls and I am using Cast or Convert if there are numeric values -

declare @CodeNameString  nvarchar(max)
select  @CodeNameString = COALESCE(@CodeNameString + ',', '')  + Cast(CodeName as varchar) from AccountCodes  ORDER BY Sort
select  @CodeNameString

Concatenate String in String Objective-c

Variations on a theme:

NSString *varying = @"whatever it is";
NSString *final = [NSString stringWithFormat:@"first part %@ third part", varying];

NSString *varying = @"whatever it is";
NSString *final = [[@"first part" stringByAppendingString:varying] stringByAppendingString:@"second part"];

NSMutableString *final = [NSMutableString stringWithString:@"first part"];
[final appendFormat:@"%@ third part", varying];

NSMutableString *final = [NSMutableString stringWithString:@"first part"];
[final appendString:varying];
[final appendString:@"third part"];

Configuring Log4j Loggers Programmatically

You can add/remove Appender programmatically to Log4j:

  ConsoleAppender console = new ConsoleAppender(); //create appender
  //configure the appender
  String PATTERN = "%d [%p|%c|%C{1}] %m%n";
  console.setLayout(new PatternLayout(PATTERN)); 
  console.setThreshold(Level.FATAL);
  console.activateOptions();
  //add appender to any Logger (here is root)
  Logger.getRootLogger().addAppender(console);

  FileAppender fa = new FileAppender();
  fa.setName("FileLogger");
  fa.setFile("mylog.log");
  fa.setLayout(new PatternLayout("%d %-5p [%c{1}] %m%n"));
  fa.setThreshold(Level.DEBUG);
  fa.setAppend(true);
  fa.activateOptions();

  //add appender to any Logger (here is root)
  Logger.getRootLogger().addAppender(fa);
  //repeat with all other desired appenders

I'd suggest you put it into an init() somewhere, where you are sure, that this will be executed before anything else. You can then remove all existing appenders on the root logger with

 Logger.getRootLogger().getLoggerRepository().resetConfiguration();

and start with adding your own. You need log4j in the classpath of course for this to work.

Remark:
You can take any Logger.getLogger(...) you like to add appenders. I just took the root logger because it is at the bottom of all things and will handle everything that is passed through other appenders in other categories (unless configured otherwise by setting the additivity flag).

If you need to know how logging works and how is decided where logs are written read this manual for more infos about that.
In Short:

  Logger fizz = LoggerFactory.getLogger("com.fizz")

will give you a logger for the category "com.fizz".
For the above example this means that everything logged with it will be referred to the console and file appender on the root logger.
If you add an appender to Logger.getLogger("com.fizz").addAppender(newAppender) then logging from fizz will be handled by alle the appenders from the root logger and the newAppender.
You don't create Loggers with the configuration, you just provide handlers for all possible categories in your system.

while installing vc_redist.x64.exe, getting error "Failed to configure per-machine MSU package."

Posting answer to my own question as I found it here and was hidden in bottom somewhere -

https://social.msdn.microsoft.com/Forums/vstudio/en-US/64baed8c-b00c-40d5-b19a-99b26a11516e/visual-c-redistributable-for-visual-studio-2015-rc-fails-on-windows-server-2012?forum=vssetup

This is because the OS failed to install the required update Windows8.1-KB2999226-x64.msu.

However, you can install it by extracting that update to a folder (e.g. XXXX), and execute following cmdlet. You can find the Windows8.1-KB2999226-x64.msu at below.

C:\ProgramData\Package Cache\469A82B09E217DDCF849181A586DF1C97C0C5C85\packages\Patch\amd64\Windows8.1-KB2999226-x64.msu

copy this file to a folder you like, and

Create a folder XXXX in that and execute following commands from Admin command propmt

wusa.exe Windows8.1-KB2999226-x64.msu /extract:XXXX

DISM.exe /Online /Add-Package /PackagePath:XXXX\Windows8.1-KB2999226-x64.cab

vc_redist.x64.exe /repair

(last command need not be run. Just execute vc_redist.x64.exe once again)

this worked for me.

How to darken a background using CSS?

when you want to brightness or darker of background-color, you can use this css code

.brighter-span {
  filter: brightness(150%);
}

.darker-span {
  filter: brightness(50%);
}

Import Package Error - Cannot Convert between Unicode and Non Unicode String Data Type

Follow the below steps to avoid (cannot convert between unicode and non-unicode string data types) this error

i) Add the Data conversion Transformation tool to your DataFlow.
ii) To open the DataFlow Conversion and select [string DT_STR] datatype.
iii) Then go to Destination flow, select Mapping.
iv) change your i/p name to copy of the name.

Python Requests and persistent sessions

Save only required cookies and reuse them.

import os
import pickle
from urllib.parse import urljoin, urlparse

login = '[email protected]'
password = 'secret'
# Assuming two cookies are used for persistent login.
# (Find it by tracing the login process)
persistentCookieNames = ['sessionId', 'profileId']
URL = 'http://example.com'
urlData = urlparse(URL)
cookieFile = urlData.netloc + '.cookie'
signinUrl = urljoin(URL, "/signin")
with requests.Session() as session:
    try:
        with open(cookieFile, 'rb') as f:
            print("Loading cookies...")
            session.cookies.update(pickle.load(f))
    except Exception:
        # If could not load cookies from file, get the new ones by login in
        print("Login in...")
        post = session.post(
            signinUrl,
            data={
                'email': login,
                'password': password,
            }
        )
        try:
            with open(cookieFile, 'wb') as f:
                jar = requests.cookies.RequestsCookieJar()
                for cookie in session.cookies:
                    if cookie.name in persistentCookieNames:
                        jar.set_cookie(cookie)
                pickle.dump(jar, f)
        except Exception as e:
            os.remove(cookieFile)
            raise(e)
    MyPage = urljoin(URL, "/mypage")
    page = session.get(MyPage)

Python dictionary: Get list of values for list of keys

A list comprehension seems to be a good way to do this:

>>> [mydict[x] for x in mykeys]
[3, 1]

jQuery: How to capture the TAB keypress within a Textbox

Try this:

$('#contra').focusout(function (){
    $('#btnPassword').focus();
});

What is your single most favorite command-line trick using Bash?

Mac only. This is simple, but MAN do I wish I had known about this years ago.

open ./

Opens the current directory in Finder. You can also use it to open any file with it's default application. Can also be used for URLs, but only if you prefix the URL with http://, which limits it's utility for opening the occasional random site.

C++ vector's insert & push_back difference

Beside the fact, that push_back(x) does the same as insert(x, end()) (maybe with slightly better performance), there are several important thing to know about these functions:

  1. push_back exists only on BackInsertionSequence containers - so, for example, it doesn't exist on set. It couldn't because push_back() grants you that it will always add at the end.
  2. Some containers can also satisfy FrontInsertionSequence and they have push_front. This is satisfied by deque, but not by vector.
  3. The insert(x, ITERATOR) is from InsertionSequence, which is common for set and vector. This way you can use either set or vector as a target for multiple insertions. However, set has additionally insert(x), which does practically the same thing (this first insert in set means only to speed up searching for appropriate place by starting from a different iterator - a feature not used in this case).

Note about the last case that if you are going to add elements in the loop, then doing container.push_back(x) and container.insert(x, container.end()) will do effectively the same thing. However this won't be true if you get this container.end() first and then use it in the whole loop.

For example, you could risk the following code:

auto pe = v.end();
for (auto& s: a)
    v.insert(pe, v);

This will effectively copy whole a into v vector, in reverse order, and only if you are lucky enough to not get the vector reallocated for extension (you can prevent this by calling reserve() first); if you are not so lucky, you'll get so-called UndefinedBehavior(tm). Theoretically this isn't allowed because vector's iterators are considered invalidated every time a new element is added.

If you do it this way:

copy(a.begin(), a.end(), back_inserter(v);

it will copy a at the end of v in the original order, and this doesn't carry a risk of iterator invalidation.

[EDIT] I made previously this code look this way, and it was a mistake because inserter actually maintains the validity and advancement of the iterator:

copy(a.begin(), a.end(), inserter(v, v.end());

So this code will also add all elements in the original order without any risk.

How to verify element present or visible in selenium 2 (Selenium WebDriver)

Here is my Java code for Selenium WebDriver. Write the following method and call it during assertion:

protected boolean isElementPresent(By by){
        try{
            driver.findElement(by);
            return true;
        }
        catch(NoSuchElementException e){
            return false;
        }
    }

Most efficient way to convert an HTMLCollection to an Array

I saw a more concise method of getting Array.prototype methods in general that works just as well. Converting an HTMLCollection object into an Array object is demonstrated below:

[].slice.call( yourHTMLCollectionObject );

And, as mentioned in the comments, for old browsers such as IE7 and earlier, you simply have to use a compatibility function, like:

function toArray(x) {
    for(var i = 0, a = []; i < x.length; i++)
        a.push(x[i]);

    return a
}

I know this is an old question, but I felt the accepted answer was a little incomplete; so I thought I'd throw this out there FWIW.

Excel VBA Run-time Error '32809' - Trying to Understand it

I suffered this problem while developing an application for a client. Working on my machine the code/forms etc worked perfectly but when loaded on to the client's system this error occurred at some point within my application.

My workaround for this error was to strip apart the workbook from the forms and code by removing the VBA modules and forms. After doing this my client copied the 'bare' workbook and the modules and forms. Importing the forms and code into the macro-enabled workbook enabled the application to work again.

Paging with Oracle

Just want to summarize the answers and comments. There are a number of ways doing a pagination.

Prior to oracle 12c there were no OFFSET/FETCH functionality, so take a look at whitepaper as the @jasonk suggested. It's the most complete article I found about different methods with detailed explanation of advantages and disadvantages. It would take a significant amount of time to copy-paste them here, so I won't do it.

There is also a good article from jooq creators explaining some common caveats with oracle and other databases pagination. jooq's blogpost

Good news, since oracle 12c we have a new OFFSET/FETCH functionality. OracleMagazine 12c new features. Please refer to "Top-N Queries and Pagination"

You may check your oracle version by issuing the following statement

SELECT * FROM V$VERSION

Why are elementwise additions much faster in separate loops than in a combined loop?

OK, the right answer definitely has to do something with the CPU cache. But to use the cache argument can be quite difficult, especially without data.

There are many answers, that led to a lot of discussion, but let's face it: Cache issues can be very complex and are not one dimensional. They depend heavily on the size of the data, so my question was unfair: It turned out to be at a very interesting point in the cache graph.

@Mysticial's answer convinced a lot of people (including me), probably because it was the only one that seemed to rely on facts, but it was only one "data point" of the truth.

That's why I combined his test (using a continuous vs. separate allocation) and @James' Answer's advice.

The graphs below shows, that most of the answers and especially the majority of comments to the question and answers can be considered completely wrong or true depending on the exact scenario and parameters used.

Note that my initial question was at n = 100.000. This point (by accident) exhibits special behavior:

  1. It possesses the greatest discrepancy between the one and two loop'ed version (almost a factor of three)

  2. It is the only point, where one-loop (namely with continuous allocation) beats the two-loop version. (This made Mysticial's answer possible, at all.)

The result using initialized data:

Enter image description here

The result using uninitialized data (this is what Mysticial tested):

Enter image description here

And this is a hard-to-explain one: Initialized data, that is allocated once and reused for every following test case of different vector size:

Enter image description here

Proposal

Every low-level performance related question on Stack Overflow should be required to provide MFLOPS information for the whole range of cache relevant data sizes! It's a waste of everybody's time to think of answers and especially discuss them with others without this information.

How to detect the character encoding of a text file?

If your file starts with the bytes 60, 118, 56, 46 and 49, then you have an ambiguous case. It could be UTF-8 (without BOM) or any of the single byte encodings like ASCII, ANSI, ISO-8859-1 etc.

Check if starting characters of a string are alphabetical in T-SQL

select * from my_table where my_field Like '[a-z][a-z]%'

How can I convert tabs to spaces in every file of a directory?

Download and run the following script to recursively convert hard tabs to soft tabs in plain text files.

Execute the script from inside the folder which contains the plain text files.

#!/bin/bash

find . -type f -and -not -path './.git/*' -exec grep -Iq . {} \; -and -print | while read -r file; do {
    echo "Converting... "$file"";
    data=$(expand --initial -t 4 "$file");
    rm "$file";
    echo "$data" > "$file";
}; done;

Returning JSON object from an ASP.NET page

With ASP.NET Web Pages you can do this on a single page as a basic GET example (the simplest possible thing that can work.

var json = Json.Encode(new {
    orientation = Cache["orientation"],
    alerted = Cache["alerted"] as bool?,
    since = Cache["since"] as DateTime?
});
Response.Write(json);

Detect if a page has a vertical scrollbar?

I found vanila solution

_x000D_
_x000D_
var hasScrollbar = function() {_x000D_
  // The Modern solution_x000D_
  if (typeof window.innerWidth === 'number')_x000D_
    return window.innerWidth > document.documentElement.clientWidth_x000D_
_x000D_
  // rootElem for quirksmode_x000D_
  var rootElem = document.documentElement || document.body_x000D_
_x000D_
  // Check overflow style property on body for fauxscrollbars_x000D_
  var overflowStyle_x000D_
_x000D_
  if (typeof rootElem.currentStyle !== 'undefined')_x000D_
    overflowStyle = rootElem.currentStyle.overflow_x000D_
_x000D_
  overflowStyle = overflowStyle || window.getComputedStyle(rootElem, '').overflow_x000D_
_x000D_
    // Also need to check the Y axis overflow_x000D_
  var overflowYStyle_x000D_
_x000D_
  if (typeof rootElem.currentStyle !== 'undefined')_x000D_
    overflowYStyle = rootElem.currentStyle.overflowY_x000D_
_x000D_
  overflowYStyle = overflowYStyle || window.getComputedStyle(rootElem, '').overflowY_x000D_
_x000D_
  var contentOverflows = rootElem.scrollHeight > rootElem.clientHeight_x000D_
  var overflowShown    = /^(visible|auto)$/.test(overflowStyle) || /^(visible|auto)$/.test(overflowYStyle)_x000D_
  var alwaysShowScroll = overflowStyle === 'scroll' || overflowYStyle === 'scroll'_x000D_
_x000D_
  return (contentOverflows && overflowShown) || (alwaysShowScroll)_x000D_
}
_x000D_
_x000D_
_x000D_

How do I load the contents of a text file into a javascript variable?

XMLHttpRequest, i.e. AJAX, without the XML.

The precise manner you do this is dependent on what JavaScript framework you're using, but if we disregard interoperability issues, your code will look something like:

var client = new XMLHttpRequest();
client.open('GET', '/foo.txt');
client.onreadystatechange = function() {
  alert(client.responseText);
}
client.send();

Normally speaking, though, XMLHttpRequest isn't available on all platforms, so some fudgery is done. Once again, your best bet is to use an AJAX framework like jQuery.

One extra consideration: this will only work as long as foo.txt is on the same domain. If it's on a different domain, same-origin security policies will prevent you from reading the result.

Get a list of numbers as input from the user

I think if you do it without the split() as mentioned in the first answer. It will work for all the values without spaces. So you don't have to give spaces as in the first answer which is more convenient I guess.

a = [int(x) for x in input()]
a

Here is my ouput:

11111
[1, 1, 1, 1, 1]

Mask for an Input to allow phone numbers?

Reactive Form


See at Stackblitz

Addition to the @Günter Zöchbauer's answer above, I tried as follows and it seems to be working but I'm not sure whether it is a efficient way.

I use valueChanges observable to listen for change events in the reactive form by subscribing to it. For special handling of backspace, I get the data from subscribe and check it with userForm.value.phone(from [formGroup]="userForm"). Because, at that moment, the data changes to the new value but the latter refers to the previous value because of not setting yet. If the data is less than previous value then the user should remove character from input. In this case, change pattern as follows:

from : newVal = newVal.replace(/^(\d{0,3})/, '($1)');

to : newVal = newVal.replace(/^(\d{0,3})/, '($1');

Otherwise, as Günter Zöchbauer mentioned above, deleting of non-numeric characters is not recognized because when we remove parentheses from input, digits still remain the same and added again parentheses from pattern match.

Controller:

import { Component,OnInit } from '@angular/core';
import { FormGroup,FormBuilder,AbstractControl,Validators } from '@angular/forms';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{

  constructor(private fb:FormBuilder) { 
    this.createForm();
  }

  createForm(){
    this.userForm = this.fb.group({
      phone:['',[Validators.pattern(/^\(\d{3}\)\s\d{3}-\d{4}$/),Validators.required]],
    });
  }

  ngOnInit() {
   this.phoneValidate();
  }

  phoneValidate(){
    const phoneControl:AbstractControl = this.userForm.controls['phone'];

    phoneControl.valueChanges.subscribe(data => {
    /**the most of code from @Günter Zöchbauer's answer.*/

    /**we remove from input but: 
       @preInputValue still keep the previous value because of not setting.
    */
    let preInputValue:string = this.userForm.value.phone;
    let lastChar:string = preInputValue.substr(preInputValue.length - 1);

    var newVal = data.replace(/\D/g, '');
    //when removed value from input
    if (data.length < preInputValue.length) {

      /**while removing if we encounter ) character,
         then remove the last digit too.*/
      if(lastChar == ')'){
         newVal = newVal.substr(0,newVal.length-1); 
      }
      if (newVal.length == 0) {
        newVal = '';
      } 
      else if (newVal.length <= 3) {
        /**when removing, we change pattern match.
        "otherwise deleting of non-numeric characters is not recognized"*/
        newVal = newVal.replace(/^(\d{0,3})/, '($1');
      } else if (newVal.length <= 6) {
        newVal = newVal.replace(/^(\d{0,3})(\d{0,3})/, '($1) $2');
      } else {
        newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(.*)/, '($1) $2-$3');
      }
    //when typed value in input
    } else{


    if (newVal.length == 0) {
      newVal = '';
    } 
    else if (newVal.length <= 3) {
      newVal = newVal.replace(/^(\d{0,3})/, '($1)');
    } else if (newVal.length <= 6) {
      newVal = newVal.replace(/^(\d{0,3})(\d{0,3})/, '($1) $2');
    } else {
      newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(.*)/, '($1) $2-$3');
    }

  }
    this.userForm.controls['phone'].setValue(newVal,{emitEvent: false});
  });
 }

}

Template:

<form [formGroup]="userForm"  novalidate>
  <div class="form-group">
    <label for="tel">Tel:</label>
    <input id="tel" formControlName="phone" maxlength="14">
  </div>
  <button [disabled]="userForm.status == 'INVALID'" type="submit">Send</button>
</form>

UPDATE

Is there a way to preserve cursor position while backspacing in the middle of the string? Currently, it jumps back to the end.

Define an id <input id="tel" formControlName="phone" #phoneRef> and renderer2#selectRootElement to get the native element in the component.

So we can get the cursor position using:

let start = this.renderer.selectRootElement('#tel').selectionStart;
let end = this.renderer.selectRootElement('#tel').selectionEnd;

and then we can apply it after the input is updated to new value:

this.userForm.controls['phone'].setValue(newVal,{emitEvent: false});
//keep cursor the appropriate position after setting the input above.
this.renderer.selectRootElement('#tel').setSelectionRange(start,end);

UPDATE 2

It's probably better to put this sort of logic inside a directive rather than in the component

I also put the logic into a directive. This makes it easier to apply it to other elements.

See at Stackblitz

Note: It is specific to (123) 123-4567 pattern.

Why am I getting AttributeError: Object has no attribute

These kind of bugs are common when Python multi-threading. What happens is that, on interpreter tear-down, the relevant module (myThread in this case) goes through a sort-of del myThread.

The call self.sample() is roughly equivalent to myThread.__dict__["sample"](self). But if we're during the interpreter's tear-down sequence, then its own dictionary of known types might've already had myThread deleted, and now it's basically a NoneType - and has no 'sample' attribute.

How to verify Facebook access token?

I found this official tool from facebook developer page, this page will you following information related to access token - App ID, Type, App-Scoped,User last installed this app via, Issued, Expires, Data Access Expires, Valid, Origin, Scopes. Just need access token.

https://developers.facebook.com/tools/debug/accesstoken/

Can't get value of input type="file"?

@BozidarS: FileAPI is supported quite well nowadays and provides a number of useful options.

var file = document.forms['formName']['inputName'].files[0];
//file.name == "photo.png"
//file.type == "image/png"
//file.size == 300821

Change status bar text color to light in iOS 9 with Objective-C

Using a UINavigationController and setting its navigation bar's barStyle to .Black. past this line in your AppDelegate.m file.

navigationController.navigationBar.barStyle = UIBarStyleBlack;

If you are not using UINavigationController then add following code in your ViewController.m file.

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

And call the method to this line :

[self setNeedsStatusBarAppearanceUpdate];

Create a .csv file with values from a Python list

Here is working copy-paste example for Python 3.x with options to define your own delimiter and quote char.

import csv

mylist = ['value 1', 'value 2', 'value 3']

with open('employee_file.csv', mode='w') as employee_file:
    employee_writer = csv.writer(employee_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL)
    employee_writer.writerow(mylist)

This will generate employee_file.csv that looks like this:

"value 1","value 2","value 3"

NOTE:

If quoting is set to csv.QUOTE_MINIMAL, then .writerow() will quote fields only if they contain the delimiter or the quotechar. This is the default case.

If quoting is set to csv.QUOTE_ALL, then .writerow() will quote all fields.

If quoting is set to csv.QUOTE_NONNUMERIC, then .writerow() will quote all fields containing text data and convert all numeric fields to the float data type.

If quoting is set to csv.QUOTE_NONE, then .writerow() will escape delimiters instead of quoting them. In this case, you also must provide a value for the escapechar optional parameter.

How to print a stack trace in Node.js?

Try Error.captureStackTrace(targetObject[, constructorOpt]).

const myObj = {};
function c() {
  // pass
}

function b() {
    Error.captureStackTrace(myObj)
    c()
} 

function a() {
    b()
}

a()

console.log(myObj.stack)

The function a and b are captured in error stack and stored in myObj.

Is there a constraint that restricts my generic method to numeric types?

If you are using .NET 4.0 and later then you can just use dynamic as method argument and check in runtime that the passed dynamic argument type is numeric/integer type.

If the type of the passed dynamic is not numeric/integer type then throw exception.

An example short code that implements the idea is something like:

using System;
public class InvalidArgumentException : Exception
{
    public InvalidArgumentException(string message) : base(message) {}
}
public class InvalidArgumentTypeException : InvalidArgumentException
{
    public InvalidArgumentTypeException(string message) : base(message) {}
}
public class ArgumentTypeNotIntegerException : InvalidArgumentTypeException
{
    public ArgumentTypeNotIntegerException(string message) : base(message) {}
}
public static class Program
{
    private static bool IntegerFunction(dynamic n)
    {
        if (n.GetType() != typeof(Int16) &&
            n.GetType() != typeof(Int32) &&
            n.GetType() != typeof(Int64) &&
            n.GetType() != typeof(UInt16) &&
            n.GetType() != typeof(UInt32) &&
            n.GetType() != typeof(UInt64))
            throw new ArgumentTypeNotIntegerException("argument type is not integer type");
        //code that implements IntegerFunction goes here
    }
    private static void Main()
    {
         Console.WriteLine("{0}",IntegerFunction(0)); //Compiles, no run time error and first line of output buffer is either "True" or "False" depends on the code that implements "Program.IntegerFunction" static method.
         Console.WriteLine("{0}",IntegerFunction("string")); //Also compiles but it is run time error and exception of type "ArgumentTypeNotIntegerException" is thrown here.
         Console.WriteLine("This is the last Console.WriteLine output"); //Never reached and executed due the run time error and the exception thrown on the second line of Program.Main static method.
    }

Of course that this solution works in run time only but never in compile time.

If you want a solution that always works in compile time and never in run time then you will have to wrap the dynamic with a public struct/class whose overloaded public constructors accept arguments of the desired types only and give the struct/class appropriate name.

It makes sense that the wrapped dynamic is always private member of the class/struct and it is the only member of the struct/class and the name of the only member of the struct/class is "value".

You will also have to define and implement public methods and/or operators that work with the desired types for the private dynamic member of the class/struct if necessary.

It also makes sense that the struct/class has special/unique constructor that accepts dynamic as argument that initializes it's only private dynamic member called "value" but the modifier of this constructor is private of course.

Once the class/struct is ready define the argument's type of IntegerFunction to be that class/struct that has been defined.

An example long code that implements the idea is something like:

using System;
public struct Integer
{
    private dynamic value;
    private Integer(dynamic n) { this.value = n; }
    public Integer(Int16 n) { this.value = n; }
    public Integer(Int32 n) { this.value = n; }
    public Integer(Int64 n) { this.value = n; }
    public Integer(UInt16 n) { this.value = n; }
    public Integer(UInt32 n) { this.value = n; }
    public Integer(UInt64 n) { this.value = n; }
    public Integer(Integer n) { this.value = n.value; }
    public static implicit operator Int16(Integer n) { return n.value; }
    public static implicit operator Int32(Integer n) { return n.value; }
    public static implicit operator Int64(Integer n) { return n.value; }
    public static implicit operator UInt16(Integer n) { return n.value; }
    public static implicit operator UInt32(Integer n) { return n.value; }
    public static implicit operator UInt64(Integer n) { return n.value; }
    public static Integer operator +(Integer x, Int16 y) { return new Integer(x.value + y); }
    public static Integer operator +(Integer x, Int32 y) { return new Integer(x.value + y); }
    public static Integer operator +(Integer x, Int64 y) { return new Integer(x.value + y); }
    public static Integer operator +(Integer x, UInt16 y) { return new Integer(x.value + y); }
    public static Integer operator +(Integer x, UInt32 y) { return new Integer(x.value + y); }
    public static Integer operator +(Integer x, UInt64 y) { return new Integer(x.value + y); }
    public static Integer operator -(Integer x, Int16 y) { return new Integer(x.value - y); }
    public static Integer operator -(Integer x, Int32 y) { return new Integer(x.value - y); }
    public static Integer operator -(Integer x, Int64 y) { return new Integer(x.value - y); }
    public static Integer operator -(Integer x, UInt16 y) { return new Integer(x.value - y); }
    public static Integer operator -(Integer x, UInt32 y) { return new Integer(x.value - y); }
    public static Integer operator -(Integer x, UInt64 y) { return new Integer(x.value - y); }
    public static Integer operator *(Integer x, Int16 y) { return new Integer(x.value * y); }
    public static Integer operator *(Integer x, Int32 y) { return new Integer(x.value * y); }
    public static Integer operator *(Integer x, Int64 y) { return new Integer(x.value * y); }
    public static Integer operator *(Integer x, UInt16 y) { return new Integer(x.value * y); }
    public static Integer operator *(Integer x, UInt32 y) { return new Integer(x.value * y); }
    public static Integer operator *(Integer x, UInt64 y) { return new Integer(x.value * y); }
    public static Integer operator /(Integer x, Int16 y) { return new Integer(x.value / y); }
    public static Integer operator /(Integer x, Int32 y) { return new Integer(x.value / y); }
    public static Integer operator /(Integer x, Int64 y) { return new Integer(x.value / y); }
    public static Integer operator /(Integer x, UInt16 y) { return new Integer(x.value / y); }
    public static Integer operator /(Integer x, UInt32 y) { return new Integer(x.value / y); }
    public static Integer operator /(Integer x, UInt64 y) { return new Integer(x.value / y); }
    public static Integer operator %(Integer x, Int16 y) { return new Integer(x.value % y); }
    public static Integer operator %(Integer x, Int32 y) { return new Integer(x.value % y); }
    public static Integer operator %(Integer x, Int64 y) { return new Integer(x.value % y); }
    public static Integer operator %(Integer x, UInt16 y) { return new Integer(x.value % y); }
    public static Integer operator %(Integer x, UInt32 y) { return new Integer(x.value % y); }
    public static Integer operator %(Integer x, UInt64 y) { return new Integer(x.value % y); }
    public static Integer operator +(Integer x, Integer y) { return new Integer(x.value + y.value); }
    public static Integer operator -(Integer x, Integer y) { return new Integer(x.value - y.value); }
    public static Integer operator *(Integer x, Integer y) { return new Integer(x.value * y.value); }
    public static Integer operator /(Integer x, Integer y) { return new Integer(x.value / y.value); }
    public static Integer operator %(Integer x, Integer y) { return new Integer(x.value % y.value); }
    public static bool operator ==(Integer x, Int16 y) { return x.value == y; }
    public static bool operator !=(Integer x, Int16 y) { return x.value != y; }
    public static bool operator ==(Integer x, Int32 y) { return x.value == y; }
    public static bool operator !=(Integer x, Int32 y) { return x.value != y; }
    public static bool operator ==(Integer x, Int64 y) { return x.value == y; }
    public static bool operator !=(Integer x, Int64 y) { return x.value != y; }
    public static bool operator ==(Integer x, UInt16 y) { return x.value == y; }
    public static bool operator !=(Integer x, UInt16 y) { return x.value != y; }
    public static bool operator ==(Integer x, UInt32 y) { return x.value == y; }
    public static bool operator !=(Integer x, UInt32 y) { return x.value != y; }
    public static bool operator ==(Integer x, UInt64 y) { return x.value == y; }
    public static bool operator !=(Integer x, UInt64 y) { return x.value != y; }
    public static bool operator ==(Integer x, Integer y) { return x.value == y.value; }
    public static bool operator !=(Integer x, Integer y) { return x.value != y.value; }
    public override bool Equals(object obj) { return this == (Integer)obj; }
    public override int GetHashCode() { return this.value.GetHashCode(); }
    public override string ToString() { return this.value.ToString(); }
    public static bool operator >(Integer x, Int16 y) { return x.value > y; }
    public static bool operator <(Integer x, Int16 y) { return x.value < y; }
    public static bool operator >(Integer x, Int32 y) { return x.value > y; }
    public static bool operator <(Integer x, Int32 y) { return x.value < y; }
    public static bool operator >(Integer x, Int64 y) { return x.value > y; }
    public static bool operator <(Integer x, Int64 y) { return x.value < y; }
    public static bool operator >(Integer x, UInt16 y) { return x.value > y; }
    public static bool operator <(Integer x, UInt16 y) { return x.value < y; }
    public static bool operator >(Integer x, UInt32 y) { return x.value > y; }
    public static bool operator <(Integer x, UInt32 y) { return x.value < y; }
    public static bool operator >(Integer x, UInt64 y) { return x.value > y; }
    public static bool operator <(Integer x, UInt64 y) { return x.value < y; }
    public static bool operator >(Integer x, Integer y) { return x.value > y.value; }
    public static bool operator <(Integer x, Integer y) { return x.value < y.value; }
    public static bool operator >=(Integer x, Int16 y) { return x.value >= y; }
    public static bool operator <=(Integer x, Int16 y) { return x.value <= y; }
    public static bool operator >=(Integer x, Int32 y) { return x.value >= y; }
    public static bool operator <=(Integer x, Int32 y) { return x.value <= y; }
    public static bool operator >=(Integer x, Int64 y) { return x.value >= y; }
    public static bool operator <=(Integer x, Int64 y) { return x.value <= y; }
    public static bool operator >=(Integer x, UInt16 y) { return x.value >= y; }
    public static bool operator <=(Integer x, UInt16 y) { return x.value <= y; }
    public static bool operator >=(Integer x, UInt32 y) { return x.value >= y; }
    public static bool operator <=(Integer x, UInt32 y) { return x.value <= y; }
    public static bool operator >=(Integer x, UInt64 y) { return x.value >= y; }
    public static bool operator <=(Integer x, UInt64 y) { return x.value <= y; }
    public static bool operator >=(Integer x, Integer y) { return x.value >= y.value; }
    public static bool operator <=(Integer x, Integer y) { return x.value <= y.value; }
    public static Integer operator +(Int16 x, Integer y) { return new Integer(x + y.value); }
    public static Integer operator +(Int32 x, Integer y) { return new Integer(x + y.value); }
    public static Integer operator +(Int64 x, Integer y) { return new Integer(x + y.value); }
    public static Integer operator +(UInt16 x, Integer y) { return new Integer(x + y.value); }
    public static Integer operator +(UInt32 x, Integer y) { return new Integer(x + y.value); }
    public static Integer operator +(UInt64 x, Integer y) { return new Integer(x + y.value); }
    public static Integer operator -(Int16 x, Integer y) { return new Integer(x - y.value); }
    public static Integer operator -(Int32 x, Integer y) { return new Integer(x - y.value); }
    public static Integer operator -(Int64 x, Integer y) { return new Integer(x - y.value); }
    public static Integer operator -(UInt16 x, Integer y) { return new Integer(x - y.value); }
    public static Integer operator -(UInt32 x, Integer y) { return new Integer(x - y.value); }
    public static Integer operator -(UInt64 x, Integer y) { return new Integer(x - y.value); }
    public static Integer operator *(Int16 x, Integer y) { return new Integer(x * y.value); }
    public static Integer operator *(Int32 x, Integer y) { return new Integer(x * y.value); }
    public static Integer operator *(Int64 x, Integer y) { return new Integer(x * y.value); }
    public static Integer operator *(UInt16 x, Integer y) { return new Integer(x * y.value); }
    public static Integer operator *(UInt32 x, Integer y) { return new Integer(x * y.value); }
    public static Integer operator *(UInt64 x, Integer y) { return new Integer(x * y.value); }
    public static Integer operator /(Int16 x, Integer y) { return new Integer(x / y.value); }
    public static Integer operator /(Int32 x, Integer y) { return new Integer(x / y.value); }
    public static Integer operator /(Int64 x, Integer y) { return new Integer(x / y.value); }
    public static Integer operator /(UInt16 x, Integer y) { return new Integer(x / y.value); }
    public static Integer operator /(UInt32 x, Integer y) { return new Integer(x / y.value); }
    public static Integer operator /(UInt64 x, Integer y) { return new Integer(x / y.value); }
    public static Integer operator %(Int16 x, Integer y) { return new Integer(x % y.value); }
    public static Integer operator %(Int32 x, Integer y) { return new Integer(x % y.value); }
    public static Integer operator %(Int64 x, Integer y) { return new Integer(x % y.value); }
    public static Integer operator %(UInt16 x, Integer y) { return new Integer(x % y.value); }
    public static Integer operator %(UInt32 x, Integer y) { return new Integer(x % y.value); }
    public static Integer operator %(UInt64 x, Integer y) { return new Integer(x % y.value); }
    public static bool operator ==(Int16 x, Integer y) { return x == y.value; }
    public static bool operator !=(Int16 x, Integer y) { return x != y.value; }
    public static bool operator ==(Int32 x, Integer y) { return x == y.value; }
    public static bool operator !=(Int32 x, Integer y) { return x != y.value; }
    public static bool operator ==(Int64 x, Integer y) { return x == y.value; }
    public static bool operator !=(Int64 x, Integer y) { return x != y.value; }
    public static bool operator ==(UInt16 x, Integer y) { return x == y.value; }
    public static bool operator !=(UInt16 x, Integer y) { return x != y.value; }
    public static bool operator ==(UInt32 x, Integer y) { return x == y.value; }
    public static bool operator !=(UInt32 x, Integer y) { return x != y.value; }
    public static bool operator ==(UInt64 x, Integer y) { return x == y.value; }
    public static bool operator !=(UInt64 x, Integer y) { return x != y.value; }
    public static bool operator >(Int16 x, Integer y) { return x > y.value; }
    public static bool operator <(Int16 x, Integer y) { return x < y.value; }
    public static bool operator >(Int32 x, Integer y) { return x > y.value; }
    public static bool operator <(Int32 x, Integer y) { return x < y.value; }
    public static bool operator >(Int64 x, Integer y) { return x > y.value; }
    public static bool operator <(Int64 x, Integer y) { return x < y.value; }
    public static bool operator >(UInt16 x, Integer y) { return x > y.value; }
    public static bool operator <(UInt16 x, Integer y) { return x < y.value; }
    public static bool operator >(UInt32 x, Integer y) { return x > y.value; }
    public static bool operator <(UInt32 x, Integer y) { return x < y.value; }
    public static bool operator >(UInt64 x, Integer y) { return x > y.value; }
    public static bool operator <(UInt64 x, Integer y) { return x < y.value; }
    public static bool operator >=(Int16 x, Integer y) { return x >= y.value; }
    public static bool operator <=(Int16 x, Integer y) { return x <= y.value; }
    public static bool operator >=(Int32 x, Integer y) { return x >= y.value; }
    public static bool operator <=(Int32 x, Integer y) { return x <= y.value; }
    public static bool operator >=(Int64 x, Integer y) { return x >= y.value; }
    public static bool operator <=(Int64 x, Integer y) { return x <= y.value; }
    public static bool operator >=(UInt16 x, Integer y) { return x >= y.value; }
    public static bool operator <=(UInt16 x, Integer y) { return x <= y.value; }
    public static bool operator >=(UInt32 x, Integer y) { return x >= y.value; }
    public static bool operator <=(UInt32 x, Integer y) { return x <= y.value; }
    public static bool operator >=(UInt64 x, Integer y) { return x >= y.value; }
    public static bool operator <=(UInt64 x, Integer y) { return x <= y.value; }
}
public static class Program
{
    private static bool IntegerFunction(Integer n)
    {
        //code that implements IntegerFunction goes here
        //note that there is NO code that checks the type of n in rum time, because it is NOT needed anymore 
    }
    private static void Main()
    {
        Console.WriteLine("{0}",IntegerFunction(0)); //compile error: there is no overloaded METHOD for objects of type "int" and no implicit conversion from any object, including "int", to "Integer" is known.
        Console.WriteLine("{0}",IntegerFunction(new Integer(0))); //both compiles and no run time error
        Console.WriteLine("{0}",IntegerFunction("string")); //compile error: there is no overloaded METHOD for objects of type "string" and no implicit conversion from any object, including "string", to "Integer" is known.
        Console.WriteLine("{0}",IntegerFunction(new Integer("string"))); //compile error: there is no overloaded CONSTRUCTOR for objects of type "string"
    }
}

Note that in order to use dynamic in your code you must Add Reference to Microsoft.CSharp

If the version of the .NET framework is below/under/lesser than 4.0 and dynamic is undefined in that version then you will have to use object instead and do casting to the integer type, which is trouble, so I recommend that you use at least .NET 4.0 or newer if you can so you can use dynamic instead of object.

How do I initialise all entries of a matrix with a specific value?

Given a predefined m-by-n matrix size and the target value val, in your example:

m = 1;
n = 10;
val = 5;

there are currently 7 different approaches that come to my mind:


1) Using the repmat function (0.094066 seconds)

A = repmat(val,m,n)

2) Indexing on the undefined matrix with assignment (0.091561 seconds)

A(1:m,1:n) = val

3) Indexing on the target value using the ones function (0.151357 seconds)

A = val(ones(m,n))

4) Default initialization with full assignment (0.104292 seconds)

A = zeros(m,n);
A(:) = val

5) Using the ones function with multiplication (0.069601 seconds)

A = ones(m,n) * val

6) Using the zeros function with addition (0.057883 seconds)

A = zeros(m,n) + val

7) Using the repelem function (0.168396 seconds)

A = repelem(val,m,n)

After the description of each approach, between parentheses, its corresponding benchmark performed under Matlab 2017a and with 100000 iterations. The winner is the 6th approach, and this doesn't surprise me.

The explaination is simple: allocation generally produces zero-filled slots of memory... hence no other operations are performed except the addition of val to every member of the matrix, and on the top of that, input arguments sanitization is very short.

The same cannot be said for the 5th approach, which is the second fastest one because, despite the input arguments sanitization process being basically the same, on memory side three operations are being performed instead of two:

  • the initial allocation
  • the transformation of every element into 1
  • the multiplication by val

How can I match multiple occurrences with a regex in JavaScript similar to PHP's preg_match_all()?

2020 edit

Use URLSearchParams, as this job no longer requires any kind of custom code. Browsers can do this for you with a single constructor:

const str = "1111342=Adam%20Franco&348572=Bob%20Jones";
const data = new URLSearchParams(str);
for (pair of data) console.log(pair)

yields

Array [ "1111342", "Adam Franco" ]
Array [ "348572", "Bob Jones" ]

So there is no reason to use regex for this anymore.

Original answer

If you don't want to rely on the "blind matching" that comes with running exec style matching, JavaScript does come with match-all functionality built in, but it's part of the replace function call, when using a "what to do with the capture groups" handling function:

var data = {};

var getKeyValue = function(fullPattern, group1, group2, group3) {
  data[group2] = group3;
};

mystring.replace(/(?:&|&amp;)?([^=]+)=([^&]+)/g, getKeyValue);

done.

Instead of using the capture group handling function to actually return replacement strings (for replace handling, the first arg is the full pattern match, and subsequent args are individual capture groups) we simply take the groups 2 and 3 captures, and cache that pair.

So, rather than writing complicated parsing functions, remember that the "matchAll" function in JavaScript is simply "replace" with a replacement handler function, and much pattern matching efficiency can be had.

Convert List to Pandas Dataframe Column

Example:

['Thanks You',
 'Its fine no problem',
 'Are you sure']

code block:

import pandas as pd
df = pd.DataFrame(lst)

Output:

    0
0   Thanks You
1   Its fine no problem
2   Are you sure

It is not recommended to remove the column names of the panda dataframe. but if you still want your data frame without header(as per the format you posted in the question) you can do this:

df = pd.DataFrame(lst)    
df.columns = ['']

Output will be like this:

0   Thanks You
1   Its fine no problem
2   Are you sure

or

df = pd.DataFrame(lst).to_string(header=False)

But the output will be a list instead of a dataframe:

0           Thanks You
1  Its fine no problem
2         Are you sure

Hope this helps!!

how to reset <input type = "file">

_x000D_
_x000D_
document.getElementById("uploadCaptureInputFile").value = "";
_x000D_
_x000D_
_x000D_

How to ssh connect through python Paramiko with ppk public key

@VonC's answer to a duplicate question:

If, as commented, Paraminko does not support PPK key, the official solution, as seen here, would be to use PuTTYgen.

But you can also use the Python library CkSshKey to make that same conversion directly in your program.

See "Convert PuTTY Private Key (ppk) to OpenSSH (pem)"

import sys
import chilkat

key = chilkat.CkSshKey()

#  Load an unencrypted or encrypted PuTTY private key.

#  If  your PuTTY private key is encrypted, set the Password
#  property before calling FromPuttyPrivateKey.
#  If your PuTTY private key is not encrypted, it makes no diffference
#  if Password is set or not set.
key.put_Password("secret")

#  First load the .ppk file into a string:

keyStr = key.loadText("putty_private_key.ppk")

#  Import into the SSH key object:
success = key.FromPuttyPrivateKey(keyStr)
if (success != True):
    print(key.lastErrorText())
    sys.exit()

#  Convert to an encrypted or unencrypted OpenSSH key.

#  First demonstrate converting to an unencrypted OpenSSH key

bEncrypt = False
unencryptedKeyStr = key.toOpenSshPrivateKey(bEncrypt)
success = key.SaveText(unencryptedKeyStr,"unencrypted_openssh.pem")
if (success != True):
    print(key.lastErrorText())
    sys.exit()

Cannot delete or update a parent row: a foreign key constraint fails

This happened to me as well and due to a dependency and reference from other tables, I could not remove the entry. What I did is added a delete column (of type boolean) to the table. The value in that field showed whether the item is marked for deletion or not. If marked for deletion, don't fetch/use; otherwise, use it.

How can I change image source on click with jQuery?

 $('div#imageContainer').click(function () {
      $('div#imageContainerimg').attr('src', 'YOUR NEW IMAGE URL HERE'); 
});

How do I create an executable in Visual Studio 2013 w/ C++?

Just click on "Build" on the top menu and then click on "Publish ".... Then a pop up will open and there u can define the folder which u want to save the .exe file and by clicking "Next" will allow u to set up the advanced settings... DONE!

jQuery.parseJSON throws “Invalid JSON” error due to escaped single quote in JSON

According to the state machine diagram on the JSON website, only escaped double-quote characters are allowed, not single-quotes. Single quote characters do not need to be escaped:

http://www.json.org/string.gif


Update - More information for those that are interested:


Douglas Crockford does not specifically say why the JSON specification does not allow escaped single quotes within strings. However, during his discussion of JSON in Appendix E of JavaScript: The Good Parts, he writes:

JSON's design goals were to be minimal, portable, textual, and a subset of JavaScript. The less we need to agree on in order to interoperate, the more easily we can interoperate.

So perhaps he decided to only allow strings to be defined using double-quotes since this is one less rule that all JSON implementations must agree on. As a result, it is impossible for a single quote character within a string to accidentally terminate the string, because by definition a string can only be terminated by a double-quote character. Hence there is no need to allow escaping of a single quote character in the formal specification.


Digging a little bit deeper, Crockford's org.json implementation of JSON for Java is more permissible and does allow single quote characters:

The texts produced by the toString methods strictly conform to the JSON syntax rules. The constructors are more forgiving in the texts they will accept:

...

  • Strings may be quoted with ' (single quote).

This is confirmed by the JSONTokener source code. The nextString method accepts escaped single quote characters and treats them just like double-quote characters:

public String nextString(char quote) throws JSONException {
    char c;
    StringBuffer sb = new StringBuffer();
    for (;;) {
        c = next();
        switch (c) {

        ...

        case '\\':
            c = this.next();
            switch (c) {

            ...

            case '"':
            case '\'':
            case '\\':
            case '/':
                sb.append(c);
                break;
        ...

At the top of the method is an informative comment:

The formal JSON format does not allow strings in single quotes, but an implementation is allowed to accept them.

So some implementations will accept single quotes - but you should not rely on this. Many popular implementations are quite restrictive in this regard and will reject JSON that contains single quoted strings and/or escaped single quotes.


Finally to tie this back to the original question, jQuery.parseJSON first attempts to use the browser's native JSON parser or a loaded library such as json2.js where applicable (which on a side note is the library the jQuery logic is based on if JSON is not defined). Thus jQuery can only be as permissive as that underlying implementation:

parseJSON: function( data ) {
    ...

    // Attempt to parse using the native JSON parser first
    if ( window.JSON && window.JSON.parse ) {
        return window.JSON.parse( data );
    }

    ...

    jQuery.error( "Invalid JSON: " + data );
},

As far as I know these implementations only adhere to the official JSON specification and do not accept single quotes, hence neither does jQuery.

Data-frame Object has no Attribute

Check your DataFrame with data.columns

It should print something like this

Index([u'regiment', u'company',  u'name',u'postTestScore'], dtype='object')

Check for hidden white spaces..Then you can rename with

data = data.rename(columns={'Number ': 'Number'})

What is apache's maximum url length?

  • Internet Explorer: 2,083 characters, with no more than 2,048 characters in the path portion of the URL
  • Firefox: 65,536 characters show up, but longer URLs do still work even up past 100,000
  • Safari: > 80,000 characters
  • Opera: > 190,000 characters
  • IIS: 16,384 characters, but is configurable
  • Apache: 4,000 characters

From: http://www.danrigsby.com/blog/index.php/2008/06/17/rest-and-max-url-size/

Check to see if cURL is installed locally?

Another way, say in CentOS, is:

$ yum list installed '*curl*'
Loaded plugins: aliases, changelog, fastestmirror, kabi, langpacks, priorities, tmprepo, verify,
              : versionlock
Loading support for Red Hat kernel ABI
Determining fastest mirrors
google-chrome                                                                                    3/3
152 packages excluded due to repository priority protections
Installed Packages
curl.x86_64                                        7.29.0-42.el7                                @base
libcurl.x86_64                                     7.29.0-42.el7                                @base
libcurl-devel.x86_64                               7.29.0-42.el7                                @base
python-pycurl.x86_64                               7.19.0-19.el7                                @base

How to convert a Title to a URL slug in jQuery?

Take a look at this slug function to sanitize URLs, developed by Sean Murphy at https://gist.github.com/sgmurphy/3095196

/**
 * Create a web friendly URL slug from a string.
 *
 * Requires XRegExp (http://xregexp.com) with unicode add-ons for UTF-8 support.
 *
 * Although supported, transliteration is discouraged because
 *     1) most web browsers support UTF-8 characters in URLs
 *     2) transliteration causes a loss of information
 *
 * @author Sean Murphy <[email protected]>
 * @copyright Copyright 2012 Sean Murphy. All rights reserved.
 * @license http://creativecommons.org/publicdomain/zero/1.0/
 *
 * @param string s
 * @param object opt
 * @return string
 */
function url_slug(s, opt) {
    s = String(s);
    opt = Object(opt);

    var defaults = {
        'delimiter': '-',
        'limit': undefined,
        'lowercase': true,
        'replacements': {},
        'transliterate': (typeof(XRegExp) === 'undefined') ? true : false
    };

    // Merge options
    for (var k in defaults) {
        if (!opt.hasOwnProperty(k)) {
            opt[k] = defaults[k];
        }
    }

    var char_map = {
        // Latin
        'À': 'A', 'Á': 'A', 'Â': 'A', 'Ã': 'A', 'Ä': 'A', 'Å': 'A', 'Æ': 'AE', 'Ç': 'C', 
        'È': 'E', 'É': 'E', 'Ê': 'E', 'Ë': 'E', 'Ì': 'I', 'Í': 'I', 'Î': 'I', 'Ï': 'I', 
        'Ð': 'D', 'Ñ': 'N', 'Ò': 'O', 'Ó': 'O', 'Ô': 'O', 'Õ': 'O', 'Ö': 'O', 'O': 'O', 
        'Ø': 'O', 'Ù': 'U', 'Ú': 'U', 'Û': 'U', 'Ü': 'U', 'U': 'U', 'Ý': 'Y', 'Þ': 'TH', 
        'ß': 'ss', 
        'à': 'a', 'á': 'a', 'â': 'a', 'ã': 'a', 'ä': 'a', 'å': 'a', 'æ': 'ae', 'ç': 'c', 
        'è': 'e', 'é': 'e', 'ê': 'e', 'ë': 'e', 'ì': 'i', 'í': 'i', 'î': 'i', 'ï': 'i', 
        'ð': 'd', 'ñ': 'n', 'ò': 'o', 'ó': 'o', 'ô': 'o', 'õ': 'o', 'ö': 'o', 'o': 'o', 
        'ø': 'o', 'ù': 'u', 'ú': 'u', 'û': 'u', 'ü': 'u', 'u': 'u', 'ý': 'y', 'þ': 'th', 
        'ÿ': 'y',

        // Latin symbols
        '©': '(c)',

        // Greek
        '?': 'A', '?': 'B', 'G': 'G', '?': 'D', '?': 'E', '?': 'Z', '?': 'H', 'T': '8',
        '?': 'I', '?': 'K', '?': 'L', '?': 'M', '?': 'N', '?': '3', '?': 'O', '?': 'P',
        '?': 'R', 'S': 'S', '?': 'T', '?': 'Y', 'F': 'F', '?': 'X', '?': 'PS', 'O': 'W',
        '?': 'A', '?': 'E', '?': 'I', '?': 'O', '?': 'Y', '?': 'H', '?': 'W', '?': 'I',
        '?': 'Y',
        'a': 'a', 'ß': 'b', '?': 'g', 'd': 'd', 'e': 'e', '?': 'z', '?': 'h', '?': '8',
        '?': 'i', '?': 'k', '?': 'l', 'µ': 'm', '?': 'n', '?': '3', '?': 'o', 'p': 'p',
        '?': 'r', 's': 's', 't': 't', '?': 'y', 'f': 'f', '?': 'x', '?': 'ps', '?': 'w',
        '?': 'a', '?': 'e', '?': 'i', '?': 'o', '?': 'y', '?': 'h', '?': 'w', '?': 's',
        '?': 'i', '?': 'y', '?': 'y', '?': 'i',

        // Turkish
        'S': 'S', 'I': 'I', 'Ç': 'C', 'Ü': 'U', 'Ö': 'O', 'G': 'G',
        's': 's', 'i': 'i', 'ç': 'c', 'ü': 'u', 'ö': 'o', 'g': 'g', 

        // Russian
        '?': 'A', '?': 'B', '?': 'V', '?': 'G', '?': 'D', '?': 'E', '?': 'Yo', '?': 'Zh',
        '?': 'Z', '?': 'I', '?': 'J', '?': 'K', '?': 'L', '?': 'M', '?': 'N', '?': 'O',
        '?': 'P', '?': 'R', '?': 'S', '?': 'T', '?': 'U', '?': 'F', '?': 'H', '?': 'C',
        '?': 'Ch', '?': 'Sh', '?': 'Sh', '?': '', '?': 'Y', '?': '', '?': 'E', '?': 'Yu',
        '?': 'Ya',
        '?': 'a', '?': 'b', '?': 'v', '?': 'g', '?': 'd', '?': 'e', '?': 'yo', '?': 'zh',
        '?': 'z', '?': 'i', '?': 'j', '?': 'k', '?': 'l', '?': 'm', '?': 'n', '?': 'o',
        '?': 'p', '?': 'r', '?': 's', '?': 't', '?': 'u', '?': 'f', '?': 'h', '?': 'c',
        '?': 'ch', '?': 'sh', '?': 'sh', '?': '', '?': 'y', '?': '', '?': 'e', '?': 'yu',
        '?': 'ya',

        // Ukrainian
        '?': 'Ye', '?': 'I', '?': 'Yi', '?': 'G',
        '?': 'ye', '?': 'i', '?': 'yi', '?': 'g',

        // Czech
        'C': 'C', 'D': 'D', 'E': 'E', 'N': 'N', 'R': 'R', 'Š': 'S', 'T': 'T', 'U': 'U', 
        'Ž': 'Z', 
        'c': 'c', 'd': 'd', 'e': 'e', 'n': 'n', 'r': 'r', 'š': 's', 't': 't', 'u': 'u',
        'ž': 'z', 

        // Polish
        'A': 'A', 'C': 'C', 'E': 'e', 'L': 'L', 'N': 'N', 'Ó': 'o', 'S': 'S', 'Z': 'Z', 
        'Z': 'Z', 
        'a': 'a', 'c': 'c', 'e': 'e', 'l': 'l', 'n': 'n', 'ó': 'o', 's': 's', 'z': 'z',
        'z': 'z',

        // Latvian
        'A': 'A', 'C': 'C', 'E': 'E', 'G': 'G', 'I': 'i', 'K': 'k', 'L': 'L', 'N': 'N', 
        'Š': 'S', 'U': 'u', 'Ž': 'Z', 
        'a': 'a', 'c': 'c', 'e': 'e', 'g': 'g', 'i': 'i', 'k': 'k', 'l': 'l', 'n': 'n',
        'š': 's', 'u': 'u', 'ž': 'z'
    };

    // Make custom replacements
    for (var k in opt.replacements) {
        s = s.replace(RegExp(k, 'g'), opt.replacements[k]);
    }

    // Transliterate characters to ASCII
    if (opt.transliterate) {
        for (var k in char_map) {
            s = s.replace(RegExp(k, 'g'), char_map[k]);
        }
    }

    // Replace non-alphanumeric characters with our delimiter
    var alnum = (typeof(XRegExp) === 'undefined') ? RegExp('[^a-z0-9]+', 'ig') : XRegExp('[^\\p{L}\\p{N}]+', 'ig');
    s = s.replace(alnum, opt.delimiter);

    // Remove duplicate delimiters
    s = s.replace(RegExp('[' + opt.delimiter + ']{2,}', 'g'), opt.delimiter);

    // Truncate slug to max. characters
    s = s.substring(0, opt.limit);

    // Remove delimiter from ends
    s = s.replace(RegExp('(^' + opt.delimiter + '|' + opt.delimiter + '$)', 'g'), '');

    return opt.lowercase ? s.toLowerCase() : s;
}

VBA ADODB excel - read data from Recordset

I am surprised that the connection string works for you, because it is missing a semi-colon. Set is only used with objects, so you would not say Set strNaam.

Set cn = CreateObject("ADODB.Connection")
With cn
 .Provider = "Microsoft.Jet.OLEDB.4.0"
  .ConnectionString = "Data Source=D:\test.xls " & _
  ";Extended Properties=""Excel 8.0;HDR=Yes;"""
.Open
End With
strQuery = "SELECT * FROM [Sheet1$E36:E38]"
Set rs = cn.Execute(strQuery)
Do While Not rs.EOF
  For i = 0 To rs.Fields.Count - 1
    Debug.Print rs.Fields(i).Name, rs.Fields(i).Value
    strNaam = rs.Fields(0).Value
  Next
  rs.MoveNext
Loop
rs.Close

There are other ways, depending on what you want to do, such as GetString (GetString Method Description).

Detecting endianness programmatically in a C++ program

union {
    int i;
    char c[sizeof(int)];
} x;
x.i = 1;
if(x.c[0] == 1)
    printf("little-endian\n");
else    printf("big-endian\n");

This is another solution. Similar to Andrew Hare's solution.

binning data in python with scipy/numpy

It's probably faster and easier to use numpy.digitize():

import numpy
data = numpy.random.random(100)
bins = numpy.linspace(0, 1, 10)
digitized = numpy.digitize(data, bins)
bin_means = [data[digitized == i].mean() for i in range(1, len(bins))]

An alternative to this is to use numpy.histogram():

bin_means = (numpy.histogram(data, bins, weights=data)[0] /
             numpy.histogram(data, bins)[0])

Try for yourself which one is faster... :)

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

I think you want this:

foreach ($myarray as $key => $value) {
    echo "$key = $value\n";
}

"Debug certificate expired" error in Eclipse Android plugins

To fix this problem, simply delete the debug.keystore file.

The default storage location for AVDs is

In ~/.android/ on OS X and Linux.

In C:\Documents and Settings\.android\ on Windows XP

In C:\Users\.android\ on Windows Vista and Windows 7.

Also see this link, which can be helpful.

http://developer.android.com/tools/publishing/app-signing.html

CSS Printing: Avoiding cut-in-half DIVs between pages?

The possible values for page-break-after are: auto, always, avoid, left, right

I believe that you can’t use thie page-break-after property on absolutely positioned elements.

Static Final Variable in Java

Just having final will have the intended effect.

final int x = 5;

...
x = 10; // this will cause a compilation error because x is final

Declaring static is making it a class variable, making it accessible using the class name <ClassName>.x

Can I set text box to readonly when using Html.TextBoxFor?

<%= Html.TextBoxFor(m => Model.Events.Subscribed[i].Action, new { @readonly = true })%>

JQuery $.each() JSON array object iteration

Assign the second variable for the $.each function() as well, makes it lot easier as it'll provide you the data (so you won't have to work with the indicies).

$.each(json, function(arrayID,group) {
            console.log('<a href="'+group.GROUP_ID+'">');
    $.each(group.EVENTS, function(eventID,eventData) {
            console.log('<p>'+eventData.SHORT_DESC+'</p>');
     });
});

Should print out everything you were trying in your question.

http://jsfiddle.net/niklasvh/hZsQS/

edit renamed the variables to make it bit easier to understand what is what.

iPhone - Get Position of UIView within entire UIWindow

For me this code worked best:

private func getCoordinate(_ view: UIView) -> CGPoint {
    var x = view.frame.origin.x
    var y = view.frame.origin.y
    var oldView = view

    while let superView = oldView.superview {
        x += superView.frame.origin.x
        y += superView.frame.origin.y
        if superView.next is UIViewController {
            break //superView is the rootView of a UIViewController
        }
        oldView = superView
    }

    return CGPoint(x: x, y: y)
}

Why do I get a "Null value was assigned to a property of primitive type setter of" error message when using HibernateCriteriaBuilder in Grails

A null value cannot be assigned to a primitive type, like int, long, boolean, etc. If the database column that corresponds to the field in your object can be null, then your field should be a wrapper class, like Integer, Long, Boolean, etc.

The danger is that your code will run fine if there are no nulls in the DB, but will fail once nulls are inserted.

And you can always return the primitive type from the getter. Ex:

  private Integer num;

  public void setNum(Integer i) {
    this.num = i;
  }

  public int getNum() {
    return this.num;
  }

But in most cases you will want to return the wrapper class.

So either set your DB column to not allow nulls, or use a wrapper class.

Get value of c# dynamic property via string

Similar to the accepted answer, you can also try GetField instead of GetProperty.

d.GetType().GetField("value2").GetValue(d);

Depending on how the actual Type was implemented, this may work when GetProperty() doesn't and can even be faster.

Gson: Is there an easier way to serialize a map

Only the TypeToken part is neccesary (when there are Generics involved).

Map<String, String> myMap = new HashMap<String, String>();
myMap.put("one", "hello");
myMap.put("two", "world");

Gson gson = new GsonBuilder().create();
String json = gson.toJson(myMap);

System.out.println(json);

Type typeOfHashMap = new TypeToken<Map<String, String>>() { }.getType();
Map<String, String> newMap = gson.fromJson(json, typeOfHashMap); // This type must match TypeToken
System.out.println(newMap.get("one"));
System.out.println(newMap.get("two"));

Output:

{"two":"world","one":"hello"}
hello
world

Unable to specify the compiler with CMake

I had similar problem as Pietro,

I am on Window 10 and using "Git Bash". I tried to execute >>cmake -G "MinGW Makefiles", but I got the same error as Pietro.

Then, I tried >>cmake -G "MSYS Makefiles", but realized that I need to set my environment correctly.

Make sure set a path to C:\MinGW\msys\1.0\bin and check if you have gcc.exe there. If gcc.exe is not there then you have to run C:/MinGW/bin/mingw-get.exe and install gcc from MSYS.

After that it works fine for me

How to do date/time comparison

Use the time package to work with time information in Go.

Time instants can be compared using the Before, After, and Equal methods. The Sub method subtracts two instants, producing a Duration. The Add method adds a Time and a Duration, producing a Time.

Play example:

package main

import (
    "fmt"
    "time"
)

func inTimeSpan(start, end, check time.Time) bool {
    return check.After(start) && check.Before(end)
}

func main() {
    start, _ := time.Parse(time.RFC822, "01 Jan 15 10:00 UTC")
    end, _ := time.Parse(time.RFC822, "01 Jan 16 10:00 UTC")

    in, _ := time.Parse(time.RFC822, "01 Jan 15 20:00 UTC")
    out, _ := time.Parse(time.RFC822, "01 Jan 17 10:00 UTC")

    if inTimeSpan(start, end, in) {
        fmt.Println(in, "is between", start, "and", end, ".")
    }

    if !inTimeSpan(start, end, out) {
        fmt.Println(out, "is not between", start, "and", end, ".")
    }
}

Simple Java Client/Server Program

My try to do client socket program

server reads file and print it to console and copies it to output file

Server Program:

package SocketProgramming.copy;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerRecieveFile {
    public static void main(String[] args) throws IOException {
        // TODO Auto-enerated method stub
        int filesize = 1022386;
        int bytesRead;
        int currentTot;
        ServerSocket s = new ServerSocket(0);
        int port = s.getLocalPort();
        ServerSocket serverSocket = new ServerSocket(15123);
        while (true) {
            Socket socket = serverSocket.accept();
            byte[] bytearray = new byte[filesize];
            InputStream is = socket.getInputStream();
            File copyFileName = new File("C:/Users/Username/Desktop/Output_file.txt");
            FileOutputStream fos = new FileOutputStream(copyFileName);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            bytesRead = is.read(bytearray, 0, bytearray.length);
            currentTot = bytesRead;
            do {
                bytesRead = is.read(bytearray, currentTot,
                        (bytearray.length - currentTot));
                if (bytesRead >= 0)
                    currentTot += bytesRead;
            } while (bytesRead > -1);
            bos.write(bytearray, 0, currentTot);
            bos.flush();
            bos.close();
            socket.close();
        }
    }
}

Client program:

package SocketProgramming.copy;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

public class ClientSendFile {
    public static void main(String[] args) throws UnknownHostException,
            IOException {
        // final String FILE_NAME="C:/Users/Username/Desktop/Input_file.txt";
        final String FILE_NAME = "C:/Users/Username/Desktop/Input_file.txt";
        ServerSocket s = new ServerSocket(0);
        int port = s.getLocalPort();
        Socket socket = new Socket(InetAddress.getLocalHost(), 15123);
        System.out.println("Accepted connection : " + socket);
        File transferFile = new File(FILE_NAME);
        byte[] bytearray = new byte[(int) transferFile.length()];
        FileInputStream fin = new FileInputStream(transferFile);
        BufferedInputStream bin = new BufferedInputStream(fin);
        bin.read(bytearray, 0, bytearray.length);
        OutputStream os = socket.getOutputStream();
        System.out.println("Sending Files...");

        os.write(bytearray, 0, bytearray.length);

        BufferedReader r = new BufferedReader(new FileReader(FILE_NAME));
        String as = "", line = null;
        while ((line = r.readLine()) != null) {
            as += line + "\n";
            // as += line;

        }
        System.out.print("Input File contains following data: " + as);
        os.flush();
        fin.close();
        bin.close();
        os.close();
        socket.close();

        System.out.println("File transfer complete");
    }
}

what is the use of $this->uri->segment(3) in codeigniter pagination

In your code $this->uri->segment(3) refers to the pagination offset which you use in your query. According to your $config['base_url'] = base_url().'index.php/papplicant/viewdeletedrecords/' ;, $this->uri->segment(3) i.e segment 3 refers to the offset. The first segment is the controller, second is the method, there after comes the parameters sent to the controllers as segments.

How to import and export components using React + ES6 + webpack?

To export a single component in ES6, you can use export default as follows:

class MyClass extends Component {
 ...
}

export default MyClass;

And now you use the following syntax to import that module:

import MyClass from './MyClass.react'

If you are looking to export multiple components from a single file the declaration would look something like this:

export class MyClass1 extends Component {
 ...
}

export class MyClass2 extends Component {
 ...
}

And now you can use the following syntax to import those files:

import {MyClass1, MyClass2} from './MyClass.react'

How to configure multi-module Maven + Sonar + JaCoCo to give merged coverage report?

There is a way to accomplish this. The magic is to create a combined jacoco.exec file. And with maven 3.3.1 there is an easy way to get this. Here my profile:

<profile>
    <id>runSonar</id>
    <activation>
        <property>
            <name>runSonar</name>
            <value>true</value>
        </property>
    </activation>
    <properties>
        <sonar.language>java</sonar.language>
        <sonar.host.url>http://sonar.url</sonar.host.url>
        <sonar.login>tokenX</sonar.login>
        <sonar.jacoco.reportMissing.force.zero>true</sonar.jacoco.reportMissing.force.zero>
        <sonar.jacoco.reportPath>${jacoco.destFile}</sonar.jacoco.reportPath>
        <jacoco.destFile>${maven.multiModuleProjectDirectory}/target/jacoco_analysis/jacoco.exec</jacoco.destFile>
    </properties>
    <build>
        <plugins>
            <plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <id>default-prepare-agent</id>
                        <goals>
                            <goal>prepare-agent</goal>
                        </goals>
                        <configuration>
                            <append>true</append>
                            <destFile>${jacoco.destFile}</destFile>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.sonarsource.scanner.maven</groupId>
                    <artifactId>sonar-maven-plugin</artifactId>
                    <version>3.2</version>
                </plugin>
                <plugin>
                    <groupId>org.jacoco</groupId>
                    <artifactId>jacoco-maven-plugin</artifactId>
                    <version>0.7.8</version>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</profile>

If you add this profile to your parent pom and call mvn clean install sonar:sonar -DrunSonar you get the complete coverage.

The magic here is maven.multiModuleProjectDirectory. This folder is always the folder where you started your maven build.

MySQL: Error Code: 1118 Row size too large (> 8126). Changing some columns to TEXT or BLOB

Switch the table format InnoDB to MyISAM

for change table format

run this query

ALTER TABLE table_name ENGINE = MyISAM;

(replace table_name with actual table name)

Check if element is in the list (contains)

A one-liner solution, similar to python, would be (std::set<int> {1, 2, 3, 4}).count(my_var) > 0.

Minimal working example

int my_var = 3;
bool myVarIn = (std::set<int> {1, 2, 3, 4}).count(my_var) > 0;
std::cout << std::boolalpha << myVarIn << std::endl;

prints true or false dependent of the value of my_var.

Read text from response

Your "application/xrds+xml" was giving me issues, I was receiving a Content-Length of 0 (no response).

After removing that, you can access the response using response.GetResponseStream().

HttpWebRequest request = WebRequest.Create("http://google.com") as HttpWebRequest;

//request.Accept = "application/xrds+xml";  
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

WebHeaderCollection header = response.Headers;

var encoding = ASCIIEncoding.ASCII;
using (var reader = new System.IO.StreamReader(response.GetResponseStream(), encoding))
{
    string responseText = reader.ReadToEnd();
}

How to read value of a registry key c#

Change:

using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\MySQL AB\\MySQL Connector\\Net"))

To:

 using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\Wow6432Node\MySQL AB\MySQL Connector\Net"))

What is the difference between "JPG" / "JPEG" / "PNG" / "BMP" / "GIF" / "TIFF" Image?

Generally these are either:

Lossless compression Lossless compression algorithms reduce file size without losing image quality, though they are not compressed into as small a file as a lossy compression file. When image quality is valued above file size, lossless algorithms are typically chosen.

Lossy compression Lossy compression algorithms take advantage of the inherent limitations of the human eye and discard invisible information. Most lossy compression algorithms allow for variable quality levels (compression) and as these levels are increased, file size is reduced. At the highest compression levels, image deterioration becomes noticeable as "compression artifacting". The images below demonstrate the noticeable artifacting of lossy compression algorithms; select the thumbnail image to view the full size version.

Each format is different as described below:

JPEG JPEG (Joint Photographic Experts Group) files are (in most cases) a lossy format; the DOS filename extension is JPG (other OS might use JPEG). Nearly every digital camera can save images in the JPEG format, which supports 8 bits per color (red, green, blue) for a 24-bit total, producing relatively small files. When not too great, the compression does not noticeably detract from the image's quality, but JPEG files suffer generational degradation when repeatedly edited and saved. Photographic images may be better stored in a lossless non-JPEG format if they will be re-edited, or if small "artifacts" (blemishes caused by the JPEG's compression algorithm) are unacceptable. The JPEG format also is used as the image compression algorithm in many Adobe PDF files.

TIFF The TIFF (Tagged Image File Format) is a flexible format that normally saves 8 bits or 16 bits per color (red, green, blue) for 24-bit and 48-bit totals, respectively, using either the TIFF or the TIF filenames. The TIFF's flexibility is both blessing and curse, because no single reader reads every type of TIFF file. TIFFs are lossy and lossless; some offer relatively good lossless compression for bi-level (black&white) images. Some digital cameras can save in TIFF format, using the LZW compression algorithm for lossless storage. The TIFF image format is not widely supported by web browsers. TIFF remains widely accepted as a photograph file standard in the printing business. The TIFF can handle device-specific colour spaces, such as the CMYK defined by a particular set of printing press inks.

PNG The PNG (Portable Network Graphics) file format was created as the free, open-source successor to the GIF. The PNG file format supports truecolor (16 million colours) while the GIF supports only 256 colours. The PNG file excels when the image has large, uniformly coloured areas. The lossless PNG format is best suited for editing pictures, and the lossy formats, like JPG, are best for the final distribution of photographic images, because JPG files are smaller than PNG files. Many older browsers currently do not support the PNG file format, however, with Internet Explorer 7, all contemporary web browsers fully support the PNG format. The Adam7-interlacing allows an early preview, even when only a small percentage of the image data has been transmitted.

GIF GIF (Graphics Interchange Format) is limited to an 8-bit palette, or 256 colors. This makes the GIF format suitable for storing graphics with relatively few colors such as simple diagrams, shapes, logos and cartoon style images. The GIF format supports animation and is still widely used to provide image animation effects. It also uses a lossless compression that is more effective when large areas have a single color, and ineffective for detailed images or dithered images.

BMP The BMP file format (Windows bitmap) handles graphics files within the Microsoft Windows OS. Typically, BMP files are uncompressed, hence they are large; the advantage is their simplicity, wide acceptance, and use in Windows programs.

Use for Web Pages / Web Applications

The following is a brief summary for these image formats when using them with a web page / application.

  • PNG is great for IE6 and up (will require a small CSS patch to get transparency working well). Great for illustrations and photos.
  • JPG is great for photos online
  • GIF is good for illustrations when you do not wish to move to PNG
  • BMP shouldn't be used online within web pages - wastes bandwidth


  • Source: Image File Formats

    SQL Server CASE .. WHEN .. IN statement

    Thanks for the Answer I have modified the statements to look like below

    SELECT
         AlarmEventTransactionTable.TxnID,
         CASE 
        WHEN DeviceID IN('7', '10', '62', '58', '60',
                '46', '48', '50', '137', '139',
                 '141', '145', '164') THEN '01'
        WHEN DeviceID IN('8', '9', '63', '59', '61',
                '47', '49', '51', '138', '140',
                '142', '146', '165') THEN '02'
                 ELSE 'NA' END AS clocking,
         AlarmEventTransactionTable.DateTimeOfTxn
    FROM
         multiMAXTxn.dbo.AlarmEventTransactionTable
    

    Java Web Service client basic authentication

    The JAX-WS way for basic authentication is

    Service s = new Service();
    Port port = s.getPort();
    
    BindingProvider prov = (BindingProvider)port;
    prov.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, "myusername");
    prov.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, "mypassword");
    
    port.call();
    

    Dynamic function name in javascript?

    What about

    this.f = window["instance:" + a] = function(){};
    

    The only drawback is that the function in its toSource method wouldn't indicate a name. That's usually only a problem for debuggers.

    Select unique values with 'select' function in 'dplyr' library

    In dplyr 0.3 this can be easily achieved using the distinct() method.

    Here is an example:

    distinct_df = df %>% distinct(field1)

    You can get a vector of the distinct values with:

    distinct_vector = distinct_df$field1

    You can also select a subset of columns at the same time as you perform the distinct() call, which can be cleaner to look at if you examine the data frame using head/tail/glimpse.:

    distinct_df = df %>% distinct(field1) %>% select(field1) distinct_vector = distinct_df$field1

    replace all occurrences in a string

    Brighams answer uses literal regexp.

    Solution with a Regex object.

    var regex = new RegExp('\n', 'g');
    text = text.replace(regex, '<br />');
    

    TRY IT HERE : JSFiddle Working Example

    Why don't Java's +=, -=, *=, /= compound assignment operators require casting?

    Subtle point here...

    There is an implicit typecast for i+j when j is a double and i is an int. Java ALWAYS converts an integer into a double when there is an operation between them.

    To clarify i+=j where i is an integer and j is a double can be described as

    i = <int>(<double>i + j)
    

    See: this description of implicit casting

    You might want to typecast j to (int) in this case for clarity.

    Parse XML document in C#

    Try this:

    XmlDocument doc = new XmlDocument();
    doc.Load(@"C:\Path\To\Xml\File.xml");
    

    Or alternatively if you have the XML in a string use the LoadXml method.

    Once you have it loaded, you can use SelectNodes and SelectSingleNode to query specific values, for example:

    XmlNode node = doc.SelectSingleNode("//Company/Email/text()");
    // node.Value contains "[email protected]"
    

    Finally, note that your XML is invalid as it doesn't contain a single root node. It must be something like this:

    <Data>
        <Employee>
            <Name>Test</Name>
            <ID>123</ID>
        </Employee>
        <Company>
            <Name>ABC</Name>
            <Email>[email protected]</Email>
        </Company>
    </Data>
    

    How to convert a structure to a byte array in C#?

            Header header = new Header();
            Byte[] headerBytes = new Byte[Marshal.SizeOf(header)];
            Marshal.Copy((IntPtr)(&header), headerBytes, 0, headerBytes.Length);
    

    This should do the trick quickly, right?

    What should I do if the current ASP.NET session is null?

    ASP.NET Technical Articles

    SUMMARY: In ASP.NET, every Web page derives from the System.Web.UI.Page class. The Page class aggregates an instance of the HttpSession object for session data. The Page class exposes different events and methods for customization. In particular, the OnInit method is used to set the initialize state of the Page object. If the request does not have the Session cookie, a new Session cookie will be issued to the requester.

    EDIT:

    Session: A Concept for Beginners

    SUMMARY: Session is created when user sends a first request to the server for any page in the web application, the application creates the Session and sends the Session ID back to the user with the response and is stored in the client machine as a small cookie. So ideally the "machine that has disabled the cookies, session information will not be stored".

    How to execute IN() SQL queries with Spring's JDBCTemplate effectively?

    Refer to here

    write query with named parameter, use simple ListPreparedStatementSetter with all parameters in sequence. Just add below snippet to convert the query in traditional form based to available parameters,

    ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(namedSql);
    
    List<Integer> parameters = new ArrayList<Integer>();
    for (A a : paramBeans)
        parameters.add(a.getId());
    
    MapSqlParameterSource parameterSource = new MapSqlParameterSource();
    parameterSource.addValue("placeholder1", parameters);
    // create SQL with ?'s
    String sql = NamedParameterUtils.substituteNamedParameters(parsedSql, parameterSource);     
    return sql;
    

    Java error: Comparison method violates its general contract

    I had to sort on several criterion (date, and, if same date; other things...). What was working on Eclipse with an older version of Java, did not worked any more on Android : comparison method violates contract ...

    After reading on StackOverflow, I wrote a separate function that I called from compare() if the dates are the same. This function calculates the priority, according to the criteria, and returns -1, 0, or 1 to compare(). It seems to work now.

    Python Requests - No connection adapters

    One more reason, maybe your url include some hiden characters, such as '\n'.

    If you define your url like below, this exception will raise:

    url = '''
    http://google.com
    '''
    

    because there are '\n' hide in the string. The url in fact become:

    \nhttp://google.com\n
    

    How to save/restore serializable object to/from file?

    I just wrote a blog post on saving an object's data to Binary, XML, or Json. You are correct that you must decorate your classes with the [Serializable] attribute, but only if you are using Binary serialization. You may prefer to use XML or Json serialization. Here are the functions to do it in the various formats. See my blog post for more details.

    Binary

    /// <summary>
    /// Writes the given object instance to a binary file.
    /// <para>Object type (and all child types) must be decorated with the [Serializable] attribute.</para>
    /// <para>To prevent a variable from being serialized, decorate it with the [NonSerialized] attribute; cannot be applied to properties.</para>
    /// </summary>
    /// <typeparam name="T">The type of object being written to the binary file.</typeparam>
    /// <param name="filePath">The file path to write the object instance to.</param>
    /// <param name="objectToWrite">The object instance to write to the binary file.</param>
    /// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
    public static void WriteToBinaryFile<T>(string filePath, T objectToWrite, bool append = false)
    {
        using (Stream stream = File.Open(filePath, append ? FileMode.Append : FileMode.Create))
        {
            var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            binaryFormatter.Serialize(stream, objectToWrite);
        }
    }
    
    /// <summary>
    /// Reads an object instance from a binary file.
    /// </summary>
    /// <typeparam name="T">The type of object to read from the binary file.</typeparam>
    /// <param name="filePath">The file path to read the object instance from.</param>
    /// <returns>Returns a new instance of the object read from the binary file.</returns>
    public static T ReadFromBinaryFile<T>(string filePath)
    {
        using (Stream stream = File.Open(filePath, FileMode.Open))
        {
            var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            return (T)binaryFormatter.Deserialize(stream);
        }
    }
    

    XML

    Requires the System.Xml assembly to be included in your project.

    /// <summary>
    /// Writes the given object instance to an XML file.
    /// <para>Only Public properties and variables will be written to the file. These can be any type though, even other classes.</para>
    /// <para>If there are public properties/variables that you do not want written to the file, decorate them with the [XmlIgnore] attribute.</para>
    /// <para>Object type must have a parameterless constructor.</para>
    /// </summary>
    /// <typeparam name="T">The type of object being written to the file.</typeparam>
    /// <param name="filePath">The file path to write the object instance to.</param>
    /// <param name="objectToWrite">The object instance to write to the file.</param>
    /// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
    public static void WriteToXmlFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
    {
        TextWriter writer = null;
        try
        {
            var serializer = new XmlSerializer(typeof(T));
            writer = new StreamWriter(filePath, append);
            serializer.Serialize(writer, objectToWrite);
        }
        finally
        {
            if (writer != null)
                writer.Close();
        }
    }
    
    /// <summary>
    /// Reads an object instance from an XML file.
    /// <para>Object type must have a parameterless constructor.</para>
    /// </summary>
    /// <typeparam name="T">The type of object to read from the file.</typeparam>
    /// <param name="filePath">The file path to read the object instance from.</param>
    /// <returns>Returns a new instance of the object read from the XML file.</returns>
    public static T ReadFromXmlFile<T>(string filePath) where T : new()
    {
        TextReader reader = null;
        try
        {
            var serializer = new XmlSerializer(typeof(T));
            reader = new StreamReader(filePath);
            return (T)serializer.Deserialize(reader);
        }
        finally
        {
            if (reader != null)
                reader.Close();
        }
    }
    

    Json

    You must include a reference to Newtonsoft.Json assembly, which can be obtained from the Json.NET NuGet Package.

    /// <summary>
    /// Writes the given object instance to a Json file.
    /// <para>Object type must have a parameterless constructor.</para>
    /// <para>Only Public properties and variables will be written to the file. These can be any type though, even other classes.</para>
    /// <para>If there are public properties/variables that you do not want written to the file, decorate them with the [JsonIgnore] attribute.</para>
    /// </summary>
    /// <typeparam name="T">The type of object being written to the file.</typeparam>
    /// <param name="filePath">The file path to write the object instance to.</param>
    /// <param name="objectToWrite">The object instance to write to the file.</param>
    /// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
    public static void WriteToJsonFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
    {
        TextWriter writer = null;
        try
        {
            var contentsToWriteToFile = JsonConvert.SerializeObject(objectToWrite);
            writer = new StreamWriter(filePath, append);
            writer.Write(contentsToWriteToFile);
        }
        finally
        {
            if (writer != null)
                writer.Close();
        }
    }
    
    /// <summary>
    /// Reads an object instance from an Json file.
    /// <para>Object type must have a parameterless constructor.</para>
    /// </summary>
    /// <typeparam name="T">The type of object to read from the file.</typeparam>
    /// <param name="filePath">The file path to read the object instance from.</param>
    /// <returns>Returns a new instance of the object read from the Json file.</returns>
    public static T ReadFromJsonFile<T>(string filePath) where T : new()
    {
        TextReader reader = null;
        try
        {
            reader = new StreamReader(filePath);
            var fileContents = reader.ReadToEnd();
            return JsonConvert.DeserializeObject<T>(fileContents);
        }
        finally
        {
            if (reader != null)
                reader.Close();
        }
    }
    

    Example

    // Write the contents of the variable someClass to a file.
    WriteToBinaryFile<SomeClass>("C:\someClass.txt", object1);
    
    // Read the file contents back into a variable.
    SomeClass object1= ReadFromBinaryFile<SomeClass>("C:\someClass.txt");
    

    How to encrypt and decrypt String with my passphrase in Java (Pc not mobile platform)?

    Use This This Will work For sure

    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    import java.security.GeneralSecurityException;
    import javax.crypto.Cipher;
    import javax.crypto.SecretKey;
    import javax.crypto.SecretKeyFactory;
    import javax.crypto.spec.PBEKeySpec;
    import javax.crypto.spec.PBEParameterSpec;
    import sun.misc.BASE64Decoder;
    import sun.misc.BASE64Encoder;
    
    public class ProtectedConfigFile {
    
        private static final char[] PASSWORD = "enfldsgbnlsngdlksdsgm".toCharArray();
        private static final byte[] SALT = { (byte) 0xde, (byte) 0x33, (byte) 0x10, (byte) 0x12, (byte) 0xde, (byte) 0x33,
                (byte) 0x10, (byte) 0x12, };
    
        public static void main(String[] args) throws Exception {
            String originalPassword = "Aman";
            System.out.println("Original password: " + originalPassword);
            String encryptedPassword = encrypt(originalPassword);
            System.out.println("Encrypted password: " + encryptedPassword);
            String decryptedPassword = decrypt(encryptedPassword);
            System.out.println("Decrypted password: " + decryptedPassword);
        }
    
        private static String encrypt(String property) throws GeneralSecurityException, UnsupportedEncodingException {
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
            SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
            Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
            pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
            return base64Encode(pbeCipher.doFinal(property.getBytes("UTF-8")));
        }
    
        private static String base64Encode(byte[] bytes) {
            // NB: This class is internal, and you probably should use another impl
            return new BASE64Encoder().encode(bytes);
        }
    
        private static String decrypt(String property) throws GeneralSecurityException, IOException {
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
            SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
            Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
            pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
            return new String(pbeCipher.doFinal(base64Decode(property)), "UTF-8");
        }
    
        private static byte[] base64Decode(String property) throws IOException {
            // NB: This class is internal, and you probably should use another impl
            return new BASE64Decoder().decodeBuffer(property);
        }
    
    }
    

    Are there any Java method ordering conventions?

    Are you using Eclipse? If so I would stick with the default member sort order, because that is likely to be most familiar to whoever reads your code (although it is not my favourite sort order.)

    How to pass data in the ajax DELETE request other than headers

    I was able to successfully pass through the data attribute in the ajax method. Here is my code

    $.ajax({
         url: "/api/Gigs/Cancel",
         type: "DELETE",
         data: {
                 "GigId": link.attr('data-gig-id')
               }
    
      })
    

    The link.attr method simply returned the value of 'data-gig-id' .

    Replace preg_replace() e modifier with preg_replace_callback

    In a regular expression, you can "capture" parts of the matched string with (brackets); in this case, you are capturing the (^|_) and ([a-z]) parts of the match. These are numbered starting at 1, so you have back-references 1 and 2. Match 0 is the whole matched string.

    The /e modifier takes a replacement string, and substitutes backslash followed by a number (e.g. \1) with the appropriate back-reference - but because you're inside a string, you need to escape the backslash, so you get '\\1'. It then (effectively) runs eval to run the resulting string as though it was PHP code (which is why it's being deprecated, because it's easy to use eval in an insecure way).

    The preg_replace_callback function instead takes a callback function and passes it an array containing the matched back-references. So where you would have written '\\1', you instead access element 1 of that parameter - e.g. if you have an anonymous function of the form function($matches) { ... }, the first back-reference is $matches[1] inside that function.

    So a /e argument of

    'do_stuff(\\1) . "and" . do_stuff(\\2)'
    

    could become a callback of

    function($m) { return do_stuff($m[1]) . "and" . do_stuff($m[2]); }
    

    Or in your case

    'strtoupper("\\2")'
    

    could become

    function($m) { return strtoupper($m[2]); }
    

    Note that $m and $matches are not magic names, they're just the parameter name I gave when declaring my callback functions. Also, you don't have to pass an anonymous function, it could be a function name as a string, or something of the form array($object, $method), as with any callback in PHP, e.g.

    function stuffy_callback($things) {
        return do_stuff($things[1]) . "and" . do_stuff($things[2]);
    }
    $foo = preg_replace_callback('/([a-z]+) and ([a-z]+)/', 'stuffy_callback', 'fish and chips');
    

    As with any function, you can't access variables outside your callback (from the surrounding scope) by default. When using an anonymous function, you can use the use keyword to import the variables you need to access, as discussed in the PHP manual. e.g. if the old argument was

    'do_stuff(\\1, $foo)'
    

    then the new callback might look like

    function($m) use ($foo) { return do_stuff($m[1], $foo); }
    

    Gotchas

    • Use of preg_replace_callback is instead of the /e modifier on the regex, so you need to remove that flag from your "pattern" argument. So a pattern like /blah(.*)blah/mei would become /blah(.*)blah/mi.
    • The /e modifier used a variant of addslashes() internally on the arguments, so some replacements used stripslashes() to remove it; in most cases, you probably want to remove the call to stripslashes from your new callback.

    ScrollIntoView() causing the whole page to move

    Using Brilliant's idea, here's a solution that only (vertically) scrolls if the element is NOT currently visible. The idea is to get the bounding box of the viewport and the element to be displayed in browser-window coordinate space. Check if it's visible and if not, scroll by the required distance so the element is shown at the top or bottom of the viewport.

        function ensure_visible(element_id)
        {
            // adjust these two to match your HTML hierarchy
            var element_to_show  = document.getElementById(element_id);
            var scrolling_parent = element_to_show.parentElement;
    
            var top = parseInt(scrolling_parent.getBoundingClientRect().top);
            var bot = parseInt(scrolling_parent.getBoundingClientRect().bottom);
    
            var now_top = parseInt(element_to_show.getBoundingClientRect().top);
            var now_bot = parseInt(element_to_show.getBoundingClientRect().bottom);
    
            // console.log("Element: "+now_top+";"+(now_bot)+" Viewport:"+top+";"+(bot) );
    
            var scroll_by = 0;
            if(now_top < top)
                scroll_by = -(top - now_top);
            else if(now_bot > bot)
                scroll_by = now_bot - bot;
            if(scroll_by != 0)
            {
                scrolling_parent.scrollTop += scroll_by; // tr.offsetTop;
            }
        }
    

    Uncaught TypeError: .indexOf is not a function

    Basically indexOf() is a method belongs to string(array object also), But while calling the function you are passing a number, try to cast it to a string and pass it.

    document.getElementById("oset").innerHTML = timeD2C(timeofday + "");
    

    _x000D_
    _x000D_
     var timeofday = new Date().getHours() + (new Date().getMinutes()) / 60;_x000D_
    _x000D_
    _x000D_
    _x000D_
    _x000D_
     function timeD2C(time) { // Converts 11.5 (decimal) to 11:30 (colon)_x000D_
        var pos = time.indexOf('.');_x000D_
        var hrs = time.substr(1, pos - 1);_x000D_
        var min = (time.substr(pos, 2)) * 60;_x000D_
    _x000D_
        if (hrs > 11) {_x000D_
            hrs = (hrs - 12) + ":" + min + " PM";_x000D_
        } else {_x000D_
            hrs += ":" + min + " AM";_x000D_
        }_x000D_
        return hrs;_x000D_
    }_x000D_
    alert(timeD2C(timeofday+""));
    _x000D_
    _x000D_
    _x000D_


    And it is good to do the string conversion inside your function definition,

    function timeD2C(time) { 
      time = time + "";
      var pos = time.indexOf('.');
    

    So that the code flow won't break at times when devs forget to pass a string into this function.

    OVER clause in Oracle

    You can use it to transform some aggregate functions into analytic:

    SELECT  MAX(date)
    FROM    mytable
    

    will return 1 row with a single maximum,

    SELECT  MAX(date) OVER (ORDER BY id)
    FROM    mytable
    

    will return all rows with a running maximum.

    angularjs to output plain text instead of html

    Use this function like

     String.prototype.text=function(){
       return this ? String(this).replace(/<[^>]+>/gm, '') : '';
     }
    
      "<span>My text</span>".text()
      output:
      My text
    

    Fiddle

    Jquery: how to sleep or delay?

    How about .delay() ?

    http://api.jquery.com/delay/

    $("#test").animate({"top":"-=80px"},1500)
              .delay(1000)
              .animate({"opacity":"0"},500);
    

    Javascript Debugging line by line using Google Chrome

    ...How can I step through my javascript code line by line using Google Chromes developer tools without it going into javascript libraries?...


    For the record: At this time (Feb/2015) both Google Chrome and Firefox have exactly what you (and I) need to avoid going inside libraries and scripts, and go beyond the code that we are interested, It's called Black Boxing:

    enter image description here

    When you blackbox a source file, the debugger will not jump into that file when stepping through code you're debugging.

    More info:

    Javascript Equivalent to C# LINQ Select

    Yes, Array.map() or $.map() does the same thing.

    //array.map:
    var ids = this.fruits.map(function(v){
        return v.Id;
    });
    
    //jQuery.map:
    var ids2 = $.map(this.fruits, function (v){
        return v.Id;
    });
    
    console.log(ids, ids2);
    

    http://jsfiddle.net/NsCXJ/1/

    Since array.map isn't supported in older browsers, I suggest that you stick with the jQuery method.

    If you prefer the other one for some reason you could always add a polyfill for old browser support.

    You can always add custom methods to the array prototype as well:

    Array.prototype.select = function(expr){
        var arr = this;
        //do custom stuff
        return arr.map(expr); //or $.map(expr);
    };
    
    var ids = this.fruits.select(function(v){
        return v.Id;
    });
    

    An extended version that uses the function constructor if you pass a string. Something to play around with perhaps:

    Array.prototype.select = function(expr){
        var arr = this;
    
        switch(typeof expr){
    
            case 'function':
                return $.map(arr, expr);
                break;
    
            case 'string':
    
                try{
    
                    var func = new Function(expr.split('.')[0], 
                                           'return ' + expr + ';');
                    return $.map(arr, func);
    
                }catch(e){
    
                    return null;
                }
    
                break;
    
            default:
                throw new ReferenceError('expr not defined or not supported');
                break;
        }
    
    };
    
    console.log(fruits.select('x.Id'));
    

    http://jsfiddle.net/aL85j/

    Update:

    Since this has become such a popular answer, I'm adding similar my where() + firstOrDefault(). These could also be used with the string based function constructor approach (which is the fastest), but here is another approach using an object literal as filter:

    Array.prototype.where = function (filter) {
    
        var collection = this;
    
        switch(typeof filter) { 
    
            case 'function': 
                return $.grep(collection, filter); 
    
            case 'object':
                for(var property in filter) {
                  if(!filter.hasOwnProperty(property)) 
                      continue; // ignore inherited properties
    
                  collection = $.grep(collection, function (item) {
                      return item[property] === filter[property];
                  });
                }
                return collection.slice(0); // copy the array 
                                          // (in case of empty object filter)
    
            default: 
                throw new TypeError('func must be either a' +
                    'function or an object of properties and values to filter by'); 
        }
    };
    
    
    Array.prototype.firstOrDefault = function(func){
        return this.where(func)[0] || null;
    };
    

    Usage:

    var persons = [{ name: 'foo', age: 1 }, { name: 'bar', age: 2 }];
    
    // returns an array with one element:
    var result1 = persons.where({ age: 1, name: 'foo' });
    
    // returns the first matching item in the array, or null if no match
    var result2 = persons.firstOrDefault({ age: 1, name: 'foo' }); 
    

    Here is a jsperf test to compare the function constructor vs object literal speed. If you decide to use the former, keep in mind to quote strings correctly.

    My personal preference is to use the object literal based solutions when filtering 1-2 properties, and pass a callback function for more complex filtering.

    I'll end this with 2 general tips when adding methods to native object prototypes:

    1. Check for occurrence of existing methods before overwriting e.g.:

      if(!Array.prototype.where) { Array.prototype.where = ...

    2. If you don't need to support IE8 and below, define the methods using Object.defineProperty to make them non-enumerable. If someone used for..in on an array (which is wrong in the first place) they will iterate enumerable properties as well. Just a heads up.

    Good NumericUpDown equivalent in WPF?

    add a textbox and scrollbar

    in VB

    Private Sub Textbox1_ValueChanged(ByVal sender As System.Object, ByVal e As System.Windows.RoutedPropertyChangedEventArgs(Of System.Double)) Handles Textbox1.ValueChanged
         If e.OldValue > e.NewValue Then
             Textbox1.Text = (Textbox1.Text + 1)
         Else
             Textbox1.Text = (Textbox1.Text - 1)
         End If
    End Sub
    

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

    It's an indication that connection pooling is being used (which is a good thing).

    C++ callback using class member

    MyClass and YourClass could both be derived from SomeonesClass which has an abstract (virtual) Callback method. Your addHandler would accept objects of type SomeonesClass and MyClass and YourClass can override Callback to provide their specific implementation of callback behavior.

    Ruby: How to get the first character of a string

    Another option that hasn't been mentioned yet:

    > "Smith".slice(0)
    #=> "S"
    

    Put spacing between divs in a horizontal row?

    You can set left margins for li tags in percents and set the same negative left margin on parent:

    _x000D_
    _x000D_
    ul {margin-left:-5%;}_x000D_
    li {width:20%;margin-left:5%;float:left;}
    _x000D_
    <ul>_x000D_
      <li>A_x000D_
      <li>B_x000D_
      <li>C_x000D_
      <li>D_x000D_
    </ul>
    _x000D_
    _x000D_
    _x000D_

    http://jsfiddle.net/UZHbS/

    Python Sets vs Lists

    from datetime import datetime
    listA = range(10000000)
    setA = set(listA)
    tupA = tuple(listA)
    #Source Code
    
    def calc(data, type):
    start = datetime.now()
    if data in type:
    print ""
    end = datetime.now()
    print end-start
    
    calc(9999, listA)
    calc(9999, tupA)
    calc(9999, setA)
    

    Output after comparing 10 iterations for all 3 : Comparison

    How should I copy Strings in Java?

    Since strings are immutable, both versions are safe. The latter, however, is less efficient (it creates an extra object and in some cases copies the character data).

    With this in mind, the first version should be preferred.

    How do I create a Linked List Data Structure in Java?

    Its much better to use java.util.LinkedList, because it's probably much more optimized, than the one that you will write.

    How to create a floating action button (FAB) in android, using AppCompat v21?

    Try this library, it supports shadow, there is minSdkVersion=7 and also supports android:elevation attribute for API-21 implicitly.

    Original post is here.

    What is polymorphism, what is it for, and how is it used?

    Polymorphism is an ability of object which can be taken in many forms. For example in human class a man can act in many forms when we talk about relationships. EX: A man is a father to his son and he is husband to his wife and he is teacher to his students.

    Detect if Visual C++ Redistributable for Visual Studio 2012 is installed

    I needed the same thing, and although AFAIK this cannot be done programmatically, it worked for me.

    I just went to Start --> Uninstall a program, and scrolled down until I found the VC++ redistributable, which includes a version number. Googling the version number, told me it belongs to VS2012 SP1.

    What is the documents directory (NSDocumentDirectory)?

    Swift 3 and 4 as global var:

    var documentsDirectory: URL {
        return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last!
    }
    

    As FileManager extension:

    extension FileManager {
        static var documentsDirectory: URL {
            return `default`.urls(for: .documentDirectory, in: .userDomainMask).last!
        }
    
        var documentsDirectory: URL {
            return urls(for: .documentDirectory, in: .userDomainMask).last!
        }
    }
    

    Unity 2d jumping script

    Use Addforce() method of a rigidbody compenent, make sure rigidbody is attached to the object and gravity is enabled, something like this

    gameObj.rigidbody2D.AddForce(Vector3.up * 10 * Time.deltaTime); or 
    gameObj.rigidbody2D.AddForce(Vector3.up * 1000); 
    

    See which combination and what values matches your requirement and use accordingly. Hope it helps

    Stop UIWebView from "bouncing" vertically?

    I was looking at a project that makes it easy to create web apps as full fledged installable applications on the iPhone called QuickConnect, and found a solution that works, if you don't want your screen to be scrollable at all, which in my case I didn't.

    In the above mentioned project/blog post, they mention a javascript function you can add to turn off the bouncing, which essentially boils down to this:

        document.ontouchmove = function(event){
            event.preventDefault();
        }
    

    If you want to see more about how they implement it, simply download QuickConnect and check it out.... But basically all it does is call that javascript on page load... I tried just putting it in the head of my document, and it seems to work fine.

    When is a timestamp (auto) updated?

    Add a trigger in database:

    DELIMITER //
    CREATE TRIGGER update_user_password 
      BEFORE UPDATE ON users
      FOR EACH ROW
        BEGIN
          IF OLD.password <> NEW.password THEN
            SET NEW.password_changed_on = NOW();
          END IF;
        END //
    DELIMITER ;
    

    The password changed time will update only when password column is changed.

    Iterating over every property of an object in javascript using Prototype?

    You have to first convert your object literal to a Prototype Hash:

    // Store your object literal
    var obj = {foo: 1, bar: 2, barobj: {75: true, 76: false, 85: true}}
    
    // Iterate like so.  The $H() construct creates a prototype-extended Hash.
    $H(obj).each(function(pair){
      alert(pair.key);
      alert(pair.value);
    });
    

    python: [Errno 10054] An existing connection was forcibly closed by the remote host

    there are many causes such as

    • The network link between server and client may be temporarily going down.
    • running out of system resources.
    • sending malformed data.

    To examine the problem in detail, you can use Wireshark.

    or you can just re-request or re-connect again.

    "RuntimeError: Make sure the Graphviz executables are on your system's path" after installing Graphviz 2.38

    OSX Sierra, Python 2.7, Graphviz 2.38

    Using pip install graphviz and conda install graphviz BOTH resolves the problem.

    pip only gets path problem same as yours and conda only gets import error.

    How to make Java honor the DNS Caching Timeout?

    So I decided to look at the java source code because I found official docs a bit confusing. And what I found (for OpenJDK 11) mostly aligns with what others have written. What is important is the order of evaluation of properties.

    InetAddressCachePolicy.java (I'm omitting some boilerplate for readability):

    
    String tmpString = Security.getProperty("networkaddress.cache.ttl");
    if (tmpString != null) {
       tmp = Integer.valueOf(tmpString);
       return;
    }
    ...
    String tmpString = System.getProperty("sun.net.inetaddr.ttl");
    if (tmpString != null) {
       tmp = Integer.valueOf(tmpString);
       return;
    }
    ...
    if (tmp != null) {
      cachePolicy = tmp < 0 ? FOREVER : tmp;
      propertySet = true;
    } else {
      /* No properties defined for positive caching. If there is no
      * security manager then use the default positive cache value.
      */
      if (System.getSecurityManager() == null) {
        cachePolicy = 30;
      }
    }
    
    

    You can clearly see that the security property is evaluated first, system property second and if any of them is set cachePolicy value is set to that number or -1 (FOREVER) if they hold a value that is bellow -1. If nothing is set it defaults to 30 seconds. As it turns out for OpenJDK that is almost always the case because by default java.security does not set that value, only a negative one.

    #networkaddress.cache.ttl=-1 <- this line is commented out
    networkaddress.cache.negative.ttl=10
    

    BTW if the networkaddress.cache.negative.ttl is not set (removed from the file) the default inside the java class is 0. Documentation is wrong in this regard. This is what tripped me over.

    How to set a Default Route (To an Area) in MVC

    even it was answered already - this is the short syntax (ASP.net 3, 4, 5):

    routes.MapRoute("redirect all other requests", "{*url}",
        new {
            controller = "UnderConstruction",
            action = "Index"
            }).DataTokens = new RouteValueDictionary(new { area = "Shop" });
    

    img tag displays wrong orientation

    I think there are some issues in browser auto fix image orientation, for example, if I visit the picture directly, it shows the right orientation, but show wrong orientation in some exits html page.

    Why am I getting a NoClassDefFoundError in Java?

    NoClassDefFoundError can also occur when a static initializer tries to load a resource bundle that is not available in runtime, for example a properties file that the affected class tries to load from the META-INF directory, but isn’t there. If you don’t catch NoClassDefFoundError, sometimes you won’t be able to see the full stack trace; to overcome this you can temporarily use a catch clause for Throwable:

    try {
        // Statement(s) that cause(s) the affected class to be loaded
    } catch (Throwable t) {
        Logger.getLogger("<logger-name>").info("Loading my class went wrong", t);
    }
    

    Putting an if-elif-else statement on one line?

    People have already mentioned ternary expressions. Sometimes with a simple conditional assignment as your example, it is possible to use a mathematical expression to perform the conditional assignment. This may not make your code very readable, but it does get it on one fairly short line. Your example could be written like this:

    x = 2*(i>100) | 1*(i<100)
    

    The comparisons would be True or False, and when multiplying with numbers would then be either 1 or 0. One could use a + instead of an | in the middle.

    docker error - 'name is already in use by container'

    I'm just learning docker and this got me as well. I stopped the container with that name already and therefore I thought I could run a new container with that name.

    Not the case. Just because the container is stopped, doesn't mean it can't be started again, and it keeps all the same parameters that it was created with (including the name).

    when I ran docker ps -a that's when I saw all the dummy test containers I created while I was playing around.

    No problem, since I don't want those any more I just did docker rm containername at which point my new container was allowed to run with the old name.

    Ah, and now that I finish writing this answer, I see Slawosz's comment on Walt Howard's answer above suggesting the use of docker ps -a

    Angular2 - Input Field To Accept Only Numbers

    Use pattern attribute for input like below:

    <input type="text" pattern="[0-9]+" >
    

    Display PDF file inside my android application

    You can download the source from here(Display PDF file inside my android application)

    Add this dependency in your gradle file:

    compile 'com.github.barteksc:android-pdf-viewer:2.0.3'
    

    activity_main.xml

    <RelativeLayout android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#ffffff"
        xmlns:android="http://schemas.android.com/apk/res/android" >
    
        <TextView
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:background="@color/colorPrimaryDark"
            android:text="View PDF"
            android:textColor="#ffffff"
            android:id="@+id/tv_header"
            android:textSize="18dp"
            android:gravity="center"></TextView>
    
        <com.github.barteksc.pdfviewer.PDFView
            android:id="@+id/pdfView"
            android:layout_below="@+id/tv_header"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
    
    
        </RelativeLayout>
    

    MainActivity.java

    package pdfviewer.pdfviewer;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.util.Log;
    import com.github.barteksc.pdfviewer.PDFView;
    import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
    import com.github.barteksc.pdfviewer.listener.OnPageChangeListener;
    import com.github.barteksc.pdfviewer.scroll.DefaultScrollHandle;
    import com.shockwave.pdfium.PdfDocument;
    
    import java.util.List;
    
    public class MainActivity extends Activity implements OnPageChangeListener,OnLoadCompleteListener{
        private static final String TAG = MainActivity.class.getSimpleName();
        public static final String SAMPLE_FILE = "android_tutorial.pdf";
        PDFView pdfView;
        Integer pageNumber = 0;
        String pdfFileName;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
    
            pdfView= (PDFView)findViewById(R.id.pdfView);
            displayFromAsset(SAMPLE_FILE);
        }
    
        private void displayFromAsset(String assetFileName) {
            pdfFileName = assetFileName;
    
            pdfView.fromAsset(SAMPLE_FILE)
                    .defaultPage(pageNumber)
                    .enableSwipe(true)
    
                    .swipeHorizontal(false)
                    .onPageChange(this)
                    .enableAnnotationRendering(true)
                    .onLoad(this)
                    .scrollHandle(new DefaultScrollHandle(this))
                    .load();
        }
    
    
        @Override
        public void onPageChanged(int page, int pageCount) {
            pageNumber = page;
            setTitle(String.format("%s %s / %s", pdfFileName, page + 1, pageCount));
        }
    
    
        @Override
        public void loadComplete(int nbPages) {
            PdfDocument.Meta meta = pdfView.getDocumentMeta();
            printBookmarksTree(pdfView.getTableOfContents(), "-");
    
        }
    
        public void printBookmarksTree(List<PdfDocument.Bookmark> tree, String sep) {
            for (PdfDocument.Bookmark b : tree) {
    
                Log.e(TAG, String.format("%s %s, p %d", sep, b.getTitle(), b.getPageIdx()));
    
                if (b.hasChildren()) {
                    printBookmarksTree(b.getChildren(), sep + "-");
                }
            }
        }
    
    }
    

    Using Javascript: How to create a 'Go Back' link that takes the user to a link if there's no history for the tab or window?

    You should use window variable - window.referrer. This variable contains the last page the user visited if they got to the current page by clicking a link For example:

      function goBack() {
        if(document.referrer) {
          window.location.href = document.referrer;
    
          return;
        } 
    
        window.location.pathname = '/';
      }
    

    This code redirect user to previous page if this is exist and redirect user to homepage if there isn't previous url

    git rm - fatal: pathspec did not match any files

    I had a duplicate directory (~web/web) and it removed the nested duplicate when I ran rm -rf web while inside the first web folder.

    Creating a file only if it doesn't exist in Node.js

    This method is no longer recommended. fs.exists is deprecated. See comments.

    Here are some options:

    1) Have 2 "fs" calls. The first one is the "fs.exists" call, and the second is "fs.write / read, etc"

    //checks if the file exists. 
    //If it does, it just calls back.
    //If it doesn't, then the file is created.
    function checkForFile(fileName,callback)
    {
        fs.exists(fileName, function (exists) {
            if(exists)
            {
                callback();
            }else
            {
                fs.writeFile(fileName, {flag: 'wx'}, function (err, data) 
                { 
                    callback();
                })
            }
        });
    }
    
    function writeToFile()
    {
        checkForFile("file.dat",function()
        {
           //It is now safe to write/read to file.dat
           fs.readFile("file.dat", function (err,data) 
           {
              //do stuff
           });
        });
    }
    

    2) Or Create an empty file first:

    --- Sync:

    //If you want to force the file to be empty then you want to use the 'w' flag:
    
    var fd = fs.openSync(filepath, 'w');
    
    //That will truncate the file if it exists and create it if it doesn't.
    
    //Wrap it in an fs.closeSync call if you don't need the file descriptor it returns.
    
    fs.closeSync(fs.openSync(filepath, 'w'));
    

    --- ASync:

    var fs = require("fs");
    fs.open(path, "wx", function (err, fd) {
        // handle error
        fs.close(fd, function (err) {
            // handle error
        });
    });
    

    3) Or use "touch": https://github.com/isaacs/node-touch

    Reset push notification settings for app

    Technical Note TN2265: Troubleshooting Push Notifications

    The first time a push-enabled app registers for push notifications, iOS asks the user if they wish to receive notifications for that app. Once the user has responded to this alert it is not presented again unless the device is restored or the app has been uninstalled for at least a day.

    If you want to simulate a first-time run of your app, you can leave the app uninstalled for a day. You can achieve the latter without actually waiting a day by setting the system clock forward a day or more, turning the device off completely, then turning the device back on.

    Update: As noted in the comments below, this solution stopped working since iOS 5.1. I would encourage filing a bug with Apple so they can update their documentation. The current solution seems to be resetting the device's content and settings.

    Update: The tech note has been updated with new steps that work correctly as of iOS 7.

    1. Delete your app from the device.
    2. Turn the device off completely and turn it back on.
    3. Go to Settings > General > Date & Time and set the date ahead a day or more.
    4. Turn the device off completely again and turn it back on.

    UPDATE as of iOS 9

    Simply deleting and reinstalling the app will reset the notification status to notDetermined (meaning prompts will appear).

    Thanks to the answer by Gomfucius below: https://stackoverflow.com/a/33247900/704803

    Adding a Scrollable JTextArea (Java)

    1. Open design view
    2. Right click to textArea
    3. open surround with option
    4. select "...JScrollPane".

    How to copy data from one HDFS to another HDFS?

    distcp command use for copying from one cluster to another cluster in parallel. You have to set the path for namenode of src and path for namenode of dst, internally it use mapper.

    Example:

    $ hadoop distcp <src> <dst>
    

    there few options you can set for distcp

    -m for no. of mapper for copying data this will increase speed of copying.

    -atomic for auto commit the data.

    -update will only update data that is in old version.

    There are generic command for copying files in hadoop are -cp and -put but they are use only when the data volume is less.

    Carry Flag, Auxiliary Flag and Overflow Flag in Assembly

    Carry Flag

    The rules for turning on the carry flag in binary/integer math are two:

    1. The carry flag is set if the addition of two numbers causes a carry out of the most significant (leftmost) bits added. 1111 + 0001 = 0000 (carry flag is turned on)

    2. The carry (borrow) flag is also set if the subtraction of two numbers requires a borrow into the most significant (leftmost) bits subtracted. 0000 - 0001 = 1111 (carry flag is turned on) Otherwise, the carry flag is turned off (zero).

      • 0111 + 0001 = 1000 (carry flag is turned off [zero])
      • 1000 - 0001 = 0111 (carry flag is turned off [zero])

    In unsigned arithmetic, watch the carry flag to detect errors.

    In signed arithmetic, the carry flag tells you nothing interesting.

    Overflow Flag

    The rules for turning on the overflow flag in binary/integer math are two:

    1. If the sum of two numbers with the sign bits off yields a result number with the sign bit on, the "overflow" flag is turned on. 0100 + 0100 = 1000 (overflow flag is turned on)

    2. If the sum of two numbers with the sign bits on yields a result number with the sign bit off, the "overflow" flag is turned on. 1000 + 1000 = 0000 (overflow flag is turned on)

    Otherwise the "overflow" flag is turned off

    • 0100 + 0001 = 0101 (overflow flag is turned off)
    • 0110 + 1001 = 1111 (overflow flag turned off)
    • 1000 + 0001 = 1001 (overflow flag turned off)
    • 1100 + 1100 = 1000 (overflow flag is turned off)

    Note that you only need to look at the sign bits (leftmost) of the three numbers to decide if the overflow flag is turned on or off.

    If you are doing two's complement (signed) arithmetic, overflow flag on means the answer is wrong - you added two positive numbers and got a negative, or you added two negative numbers and got a positive.

    If you are doing unsigned arithmetic, the overflow flag means nothing and should be ignored.

    For more clarification please refer: http://teaching.idallen.com/dat2343/10f/notes/040_overflow.txt

    Listing all the folders subfolders and files in a directory using php

    In case you want to use directoryIterator

    Following function is a re-implementation of @Shef answer with directoryIterator

    function listFolderFiles($dir)
    {
        echo '<ol>';
        foreach (new DirectoryIterator($dir) as $fileInfo) {
            if (!$fileInfo->isDot()) {
                echo '<li>' . $fileInfo->getFilename();
                if ($fileInfo->isDir()) {
                    listFolderFiles($fileInfo->getPathname());
                }
                echo '</li>';
            }
        }
        echo '</ol>';
    }
    listFolderFiles('Main Dir');
    

    How permission can be checked at runtime without throwing SecurityException?

    Step 1 - add permission request

        String[] permissionArrays = new String[]{Manifest.permission.CAMERA, 
        Manifest.permission.WRITE_EXTERNAL_STORAGE};
        int REQUEST_CODE = 101;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                requestPermissions(permissionArrays, REQUEST_CODE );
            } else {
                 // if already permition granted
                // PUT YOUR ACTION (Like Open cemara etc..)
            }
        }
    

    Step 2 - Handle Permission result

         @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean openActivityOnce = true;
        boolean openDialogOnce = true;
        if (requestCode == REQUEST_CODE ) {
            for (int i = 0; i < grantResults.length; i++) {
                String permission = permissions[i];
    
                isPermitted = grantResults[i] == PackageManager.PERMISSION_GRANTED;
    
                if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                    // user rejected the permission
    
                }else {
                    //  user grant the permission
                    // you can perfome your action 
                }
            }
        }
    }
    

    How do I get a python program to do nothing?

    You could use a pass statement:

    if condition:
        pass
    

    Python 2.x documentation

    Python 3.x documentation

    However I doubt you want to do this, unless you just need to put something in as a placeholder until you come back and write the actual code for the if statement.

    If you have something like this:

    if condition:        # condition in your case being `num2 == num5`
        pass
    else:
        do_something()
    

    You can in general change it to this:

    if not condition:
        do_something()
    

    But in this specific case you could (and should) do this:

    if num2 != num5:        # != is the not-equal-to operator
        do_something()
    

    Day Name from Date in JS

    _x000D_
    _x000D_
    var dayName =['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
    var day = dayName[new Date().getDay()];
    console.log(day)
    _x000D_
    _x000D_
    _x000D_

    MySQL selecting yesterday's date

    While the chosen answer is correct and more concise, I'd argue for the structure noted in other answers:

    SELECT * FROM your_table
    WHERE UNIX_TIMESTAMP(DateVisited) >= UNIX_TIMESTAMP(CAST(NOW() - INTERVAL 1 DAY AS DATE))
      AND UNIX_TIMESTAMP(DateVisited) <= UNIX_TIMESTAMP(CAST(NOW() AS DATE));
    

    If you just need a bare date without timestamp you could also write it as the following:

    SELECT * FROM your_table
    WHERE DateVisited >= CAST(NOW() - INTERVAL 1 DAY AS DATE)
      AND DateVisited <= CAST(NOW() AS DATE);
    

    The reason for using CAST versus SUBDATE is CAST is ANSI SQL syntax. SUBDATE is a MySQL specific implementation of the date arithmetic component of CAST. Getting into the habit of using ANSI syntax can reduce headaches should you ever have to migrate to a different database. It's also good to be in the habit as a professional practice as you'll almost certainly work with other DBMS' in the future.

    None of the major DBMS systems are fully ANSI compliant, but most of them implement the broad set of ANSI syntax whereas nearly none of them outside of MySQL and its descendants (MariaDB, Percona, etc) will implement MySQL-specific syntax.

    MySQL: ALTER TABLE if column not exists

    I used this approach (Without using stored procedure):

    SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'tbl_name' AND COLUMN_NAME = 'column_name'

    If it didnt return any rows then the column doesn't exists then alter the table:

    ALTER TABLE tbl_name ADD COLUMN column_name TINYINT(1) NOT NULL DEFAULT 1

    Hope this helps.

    Project Links do not work on Wamp Server

    1. check wamp server icon is green or not if it is green then it is working if not then you have to follow these steps to do

      a. all the programs should be closed before running the wamp because most of the cases some softwares like skype takes the same port (80) which is using by wamp.

      b. you can change the port of skype : Tool-s->oprions->advanced->connection untick use port 80

    2. restart the wamp it will work.

    SECOND case

    1. when you click on the project in loalhost it does not show the localhost infront of the project name and because of that it looks like wamp is not working then you have to one thing on only

      . go to wamp index.php file and change $suppress_localhost = false; from $suppress_localhost = true; or try vice versa it will work

    Add an element to an array in Swift

    From page 143 of The Swift Programming Language:

    You can add a new item to the end of an array by calling the array’s append method

    Alternatively, add a new item to the end of an array with the addition assignment operator (+=)

    Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/us/jEUH0.l

    Making RGB color in Xcode

    The values are determined by the bit of the image. 8 bit 0 to 255

    16 bit...some ridiculous number..0 to 65,000 approx.

    32 bit are 0 to 1

    I use .004 with 32 bit images...this gives 1.02 as a result when multiplied by 255

    How to remove the character at a given index from a string in C?

    My way to remove all specified chars:

    void RemoveChars(char *s, char c)
    {
        int writer = 0, reader = 0;
    
        while (s[reader])
        {
            if (s[reader]!=c) 
            {   
                s[writer++] = s[reader];
            }
    
            reader++;       
        }
    
        s[writer]=0;
    }
    

    The first day of the current month in php using date_modify as DateTime object

    Ugly, (and doesn't use your method call above) but works:

    echo 'First day of the month: ' . date('m/d/y h:i a',(strtotime('this month',strtotime(date('m/01/y')))));