Programs & Examples On #Expression design

What is the difference between utf8mb4 and utf8 charsets in MySQL?

The utf8mb4 character set is useful because nowadays we need support for storing not only language characters but also symbols, newly introduced emojis, and so on.

A nice read on How to support full Unicode in MySQL databases by Mathias Bynens can also shed some light on this.

How to restart tomcat 6 in ubuntu

if you are using extracted tomcat then,

startup.sh and shutdown.sh are two script located in TOMCAT/bin/ to start and shutdown tomcat, You could use that

if tomcat is installed then

/etc/init.d/tomcat5.5 start
/etc/init.d/tomcat5.5 stop
/etc/init.d/tomcat5.5 restart

Change multiple files

If you are able to run a script, here is what I did for a similar situation:

Using a dictionary/hashMap (associative array) and variables for the sed command, we can loop through the array to replace several strings. Including a wildcard in the name_pattern will allow to replace in-place in files with a pattern (this could be something like name_pattern='File*.txt' ) in a specific directory (source_dir). All the changes are written in the logfile in the destin_dir

#!/bin/bash
source_dir=source_path
destin_dir=destin_path
logfile='sedOutput.txt'
name_pattern='File.txt'

echo "--Begin $(date)--" | tee -a $destin_dir/$logfile
echo "Source_DIR=$source_dir destin_DIR=$destin_dir "

declare -A pairs=( 
    ['WHAT1']='FOR1'
    ['OTHER_string_to replace']='string replaced'
)

for i in "${!pairs[@]}"; do
    j=${pairs[$i]}
    echo "[$i]=$j"
    replace_what=$i
    replace_for=$j
    echo " "
    echo "Replace: $replace_what for: $replace_for"
    find $source_dir -name $name_pattern | xargs sed -i "s/$replace_what/$replace_for/g" 
    find $source_dir -name $name_pattern | xargs -I{} grep -n "$replace_for" {} /dev/null | tee -a $destin_dir/$logfile
done

echo " "
echo "----End $(date)---" | tee -a $destin_dir/$logfile

First, the pairs array is declared, each pair is a replacement string, then WHAT1 will be replaced for FOR1 and OTHER_string_to replace will be replaced for string replaced in the file File.txt. In the loop the array is read, the first member of the pair is retrieved as replace_what=$i and the second as replace_for=$j. The find command searches in the directory the filename (that may contain a wildcard) and the sed -i command replaces in the same file(s) what was previously defined. Finally I added a grep redirected to the logfile to log the changes made in the file(s).

This worked for me in GNU Bash 4.3 sed 4.2.2 and based upon VasyaNovikov's answer for Loop over tuples in bash.

Setting up Vim for Python

In general, vim is a very powerful regular language editor (macros extend this but we'll ignore that for now). This is because vim's a thin layer on top of ed, and ed isn't much more than a line editor that speaks regex. Emacs has the advantage of being built on top of ELisp; lending it the ability to easily parse complex grammars and perform indentation tricks like the one you shared above.

To be honest, I've never been able to dive into the depths of emacs because it is simply delightful meditating within my vim cave. With that said, let's jump in.

Getting Started

Janus

For beginners, I highly recommend installing the readymade Janus plugin (fwiw, the name hails from a Star Trek episode featuring Janus Vim). If you want a quick shortcut to a vim IDE it's your best bang for your buck.

I've never used it much, but I've seen others use it happily and my current setup is borrowed heavily from an old Janus build.

Vim Pathogen

Otherwise, do some exploring on your own! I'd highly recommend installing vim pathogen if you want to see the universe of vim plugins.

It's a package manager of sorts. Once you install it, you can git clone packages to your ~/.vim/bundle directory and they're auto-installed. No more plugin installation, maintenance, or uninstall headaches!

You can run the following script from the GitHub page to install pathogen:

mkdir -p ~/.vim/autoload ~/.vim/bundle; \
curl -so ~/.vim/autoload/pathogen.vim \
    https://raw.github.com/tpope/vim-pathogen/HEAD/autoload/pathogen.vim

Helpful Links

Here are some links on extending vim I've found and enjoyed:

php artisan migrate throwing [PDO Exception] Could not find driver - Using Laravel

I got this error for the PostgreSQL and the solution is:

sudo apt-get install php7.1-pgsql

You only need to use your installed PHP version, mine is 7.1. This has fixed the issue for PostgreSQL.

how to add value to a tuple?

As other people have answered, tuples in python are immutable and the only way to 'modify' one is to create a new one with the appended elements included.

But the best solution is a list. When whatever function or method that requires a tuple needs to be called, create a tuple by using tuple(list).

ASP.NET Setting width of DataBound column in GridView

add HeaderStyle in your bound field:

    <asp:BoundField HeaderText="UserId"
                DataField="UserId" 
                SortExpression="UserId">

                <HeaderStyle Width="200px" />

</asp:BoundField>

ARM compilation error, VFP registers used by executable, not object file

I was facing the same issue. I was trying to build linux application for Cyclone V FPGA-SoC. I faced the problem as below:

Error: <application_name> uses VFP register arguments, main.o does not

I was using the toolchain arm-linux-gnueabihf-g++ provided by embedded software design tool of altera.

It is solved by exporting: mfloat-abi=hard to flags, then arm-linux-gnueabihf-g++ compiles without errors. Also include the flags in both CC & LD.

What is "Advanced" SQL?

Basics


  1. SELECTing columns from a table
  2. Aggregates Part 1: COUNT, SUM, MAX/MIN
  3. Aggregates Part 2: DISTINCT, GROUP BY, HAVING

Intermediate


  1. JOINs, ANSI-89 and ANSI-92 syntax
  2. UNION vs UNION ALL
  3. NULL handling: COALESCE & Native NULL handling
  4. Subqueries: IN, EXISTS, and inline views
  5. Subqueries: Correlated
  6. WITH syntax: Subquery Factoring/CTE
  7. Views

Advanced Topics


  • Functions, Stored Procedures, Packages
  • Pivoting data: CASE & PIVOT syntax
  • Hierarchical Queries
  • Cursors: Implicit and Explicit
  • Triggers
  • Dynamic SQL
  • Materialized Views
  • Query Optimization: Indexes
  • Query Optimization: Explain Plans
  • Query Optimization: Profiling
  • Data Modelling: Normal Forms, 1 through 3
  • Data Modelling: Primary & Foreign Keys
  • Data Modelling: Table Constraints
  • Data Modelling: Link/Corrollary Tables
  • Full Text Searching
  • XML
  • Isolation Levels
  • Entity Relationship Diagrams (ERDs), Logical and Physical
  • Transactions: COMMIT, ROLLBACK, Error Handling

Save file/open file dialog box, using Swing & Netbeans GUI editor

I think you face three problems:

  1. understanding the FileChooser
  2. writing/reading files
  3. understanding extensions and file formats

ad 1. Are you sure you've connected the FileChooser to a correct panel/container? I'd go for a simple tutorial on this matter and see if it works. That's the best way to learn - by making small but large enough steps forward. Breaking down an issue into such parts might be tricky sometimes ;)

ad. 2. After you save or open the file you should have methods to write or read the file. And again there are pretty neat examples on this matter and it's easy to understand topic.

ad. 3. There's a difference between a file having extension and file format. You can change the format of any file to anything you want but that doesn't affect it's contents. It might just render the file unreadable for the application associated with such extension. TXT files are easy - you read what you write. XLS, DOCX etc. require more work and usually framework is the best way to tackle these.

NameError: global name 'unicode' is not defined - in Python 3

One can replace unicode with u''.__class__ to handle the missing unicode class in Python 3. For both Python 2 and 3, you can use the construct

isinstance(unicode_or_str, u''.__class__)

or

type(unicode_or_str) == type(u'')

Depending on your further processing, consider the different outcome:

Python 3

>>> isinstance('text', u''.__class__)
True
>>> isinstance(u'text', u''.__class__)
True

Python 2

>>> isinstance(u'text', u''.__class__)
True
>>> isinstance('text', u''.__class__)
False

How can I make a CSS glass/blur effect work for an overlay?

This will do the blur overlay over the content:

.blur {
  display: block;
  bottom: 0;
  left: 0;
  position: fixed;
  right: 0;
  top: 0;
  -webkit-backdrop-filter: blur(15px);
  backdrop-filter: blur(15px);
  background-color: rgba(0, 0, 0, 0.5);
}

FileProvider - IllegalArgumentException: Failed to find configured root

If you are using internal cache then use.

<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <cache-path name="cache" path="/" />
</paths>

Program does not contain a static 'Main' method suitable for an entry point

Just in case someone is still getting the same error, even with all the help above: I had this problem, I tried all the solutions given here, and I just found out that my problem was actually another error from my error list (which was about a missing image set to be my splash screen. i just changed its path to the right one and then all started to work)

Zabbix server is not running: the information displayed may not be current

My problem was caused by having external ip in $ZBX_SERVER setting.

I changed it to localhost instead so that ip was resolved internally,

$sudo nano /etc/zabbix/web/zabbix.conf.php

Changed

$ZBX_SERVER = 'external ip was written here';

to

$ZBX_SERVER = 'localhost';

then

$sudo service zabbix-server restart

Zabbix 3.4 on Ubuntu 14.04.3 LTS

Error when creating a new text file with python?

If the file does not exists, open(name,'r+') will fail.

You can use open(name, 'w'), which creates the file if the file does not exist, but it will truncate the existing file.

Alternatively, you can use open(name, 'a'); this will create the file if the file does not exist, but will not truncate the existing file.

SQL Server convert select a column and convert it to a string

There is new method in SQL Server 2017:

SELECT STRING_AGG (column, ',') AS column FROM Table;

that will produce 1,3,5,9 for you

How to Check whether Session is Expired or not in asp.net

Use Session.Contents.Count:

if (Session.Contents.Count == 0)
{
    Response.Write(".NET session has Expired");
    Response.End();
}
else
{
    InitializeControls();
}

The code above assumes that you have at least one session variable created when the user first visits your site. If you don't have one then you are most likely not using a database for your app. For your case you can just manually assign a session variable using the example below.

protected void Page_Load(object sender, EventArgs e)
{
    Session["user_id"] = 1;
}

Best of luck to you!

Run jQuery function onclick

Using obtrusive JavaScript (i.e. inline code) as in your example, you can attach the click event handler to the div element with the onclick attribute like so:

 <div id="some-id" class="some-class" onclick="slideonlyone('sms_box');">
     ...
 </div>

However, the best practice is unobtrusive JavaScript which you can easily achieve by using jQuery's on() method or its shorthand click(). For example:

 $(document).ready( function() {
     $('.some-class').on('click', slideonlyone('sms_box'));
     // OR //
     $('.some-class').click(slideonlyone('sms_box'));
 });

Inside your handler function (e.g. slideonlyone() in this case) you can reference the element that triggered the event (e.g. the div in this case) with the $(this) object. For example, if you need its ID, you can access it with $(this).attr('id').


EDIT

After reading your comment to @fmsf below, I see you also need to dynamically reference the target element to be toggled. As @fmsf suggests, you can add this information to the div with a data-attribute like so:

<div id="some-id" class="some-class" data-target="sms_box">
    ...
</div>

To access the element's data-attribute you can use the attr() method as in @fmsf's example, but the best practice is to use jQuery's data() method like so:

 function slideonlyone() {
     var trigger_id = $(this).attr('id'); // This would be 'some-id' in our example
     var target_id  = $(this).data('target'); // This would be 'sms_box'
     ...
 }

Note how data-target is accessed with data('target'), without the data- prefix. Using data-attributes you can attach all sorts of information to an element and jQuery would automatically add them to the element's data object.

Is object empty?

here my solution

function isEmpty(value) {
    if(Object.prototype.toString.call(value) === '[object Array]') {
        return value.length == 0;
    } else if(value != null && typeof value === 'object') {
        return Object.getOwnPropertyNames(value).length  == 0;
    } else {
        return !(value || (value === 0));
    }
}

Chears

What is the purpose of flush() in Java streams?

When we give any command, the streams of that command are stored in the memory location called buffer(a temporary memory location) in our computer. When all the temporary memory location is full then we use flush(), which flushes all the streams of data and executes them completely and gives a new space to new streams in buffer temporary location. -Hope you will understand

How to test if a string contains one of the substrings in a list, in pandas?

One option is just to use the regex | character to try to match each of the substrings in the words in your Series s (still using str.contains).

You can construct the regex by joining the words in searchfor with |:

>>> searchfor = ['og', 'at']
>>> s[s.str.contains('|'.join(searchfor))]
0    cat
1    hat
2    dog
3    fog
dtype: object

As @AndyHayden noted in the comments below, take care if your substrings have special characters such as $ and ^ which you want to match literally. These characters have specific meanings in the context of regular expressions and will affect the matching.

You can make your list of substrings safer by escaping non-alphanumeric characters with re.escape:

>>> import re
>>> matches = ['$money', 'x^y']
>>> safe_matches = [re.escape(m) for m in matches]
>>> safe_matches
['\\$money', 'x\\^y']

The strings with in this new list will match each character literally when used with str.contains.

Difference between frontend, backend, and middleware in web development

Frontend refers to the client-side, whereas backend refers to the server-side of the application. Both are crucial to web development, but their roles, responsibilities and the environments they work in are totally different. Frontend is basically what users see whereas backend is how everything works

How does HTTP_USER_AGENT work?

The user agent string is a text that the browsers themselves send to the webserver to identify themselves, so that websites can send different content based on the browser or based on browser compatibility.

Mozilla is a browser rendering engine (the one at the core of Firefox) and the fact that Chrome and IE contain the string Mozilla/4 or /5 identifies them as being compatible with that rendering engine.

What is the difference between a mutable and immutable string in C#?

Strings are mutable because .NET use string pool behind the scene. It means :

string name = "My Country";
string name2 = "My Country";

Both name and name2 are referring to same memory location from string pool. Now suppose you want to change name2 to :

name2 = "My Loving Country";

It will look in to string pool for the string "My Loving Country", if found you will get the reference of it other wise new string "My Loving Country" will be created in string pool and name2 will get reference of it. But it this whole process "My Country" was not changed because other variable like name is still using it. And that is the reason why string are IMMUTABLE.

StringBuilder works in different manner and don't use string pool. When we create any instance of StringBuilder :

var address  = new StringBuilder(500);

It allocate memory chunk of size 500 bytes for this instance and all operation just modify this memory location and this memory not shared with any other object. And that is the reason why StringBuilder is MUTABLE.

I hope it will help.

How do I make an asynchronous GET request in PHP?

let me show you my way :)

needs nodejs installed on the server

(my server sends 1000 https get request takes only 2 seconds)

url.php :

<?
$urls = array_fill(0, 100, 'http://google.com/blank.html');

function execinbackground($cmd) { 
    if (substr(php_uname(), 0, 7) == "Windows"){ 
        pclose(popen("start /B ". $cmd, "r"));  
    } 
    else { 
        exec($cmd . " > /dev/null &");   
    } 
} 
fwite(fopen("urls.txt","w"),implode("\n",$urls);
execinbackground("nodejs urlscript.js urls.txt");
// { do your work while get requests being executed.. }
?>

urlscript.js >

var https = require('https');
var url = require('url');
var http = require('http');
var fs = require('fs');
var dosya = process.argv[2];
var logdosya = 'log.txt';
var count=0;
http.globalAgent.maxSockets = 300;
https.globalAgent.maxSockets = 300;

setTimeout(timeout,100000); // maximum execution time (in ms)

function trim(string) {
    return string.replace(/^\s*|\s*$/g, '')
}

fs.readFile(process.argv[2], 'utf8', function (err, data) {
    if (err) {
        throw err;
    }
    parcala(data);
});

function parcala(data) {
    var data = data.split("\n");
    count=''+data.length+'-'+data[1];
    data.forEach(function (d) {
        req(trim(d));
    });
    /*
    fs.unlink(dosya, function d() {
        console.log('<%s> file deleted', dosya);
    });
    */
}


function req(link) {
    var linkinfo = url.parse(link);
    if (linkinfo.protocol == 'https:') {
        var options = {
        host: linkinfo.host,
        port: 443,
        path: linkinfo.path,
        method: 'GET'
    };
https.get(options, function(res) {res.on('data', function(d) {});}).on('error', function(e) {console.error(e);});
    } else {
    var options = {
        host: linkinfo.host,
        port: 80,
        path: linkinfo.path,
        method: 'GET'
    };        
http.get(options, function(res) {res.on('data', function(d) {});}).on('error', function(e) {console.error(e);});
    }
}


process.on('exit', onExit);

function onExit() {
    log();
}

function timeout()
{
console.log("i am too far gone");process.exit();
}

function log() 
{
    var fd = fs.openSync(logdosya, 'a+');
    fs.writeSync(fd, dosya + '-'+count+'\n');
    fs.closeSync(fd);
}

Call a stored procedure with another in Oracle

Calling one procedure from another procedure:

One for a normal procedure:

CREATE OR REPLACE SP_1() AS 
BEGIN
/*  BODY */
END SP_1;

Calling procedure SP_1 from SP_2:

CREATE OR REPLACE SP_2() AS
BEGIN
/* CALL PROCEDURE SP_1 */
SP_1();
END SP_2;

Call a procedure with REFCURSOR or output cursor:

CREATE OR REPLACE SP_1
(
oCurSp1 OUT SYS_REFCURSOR
) AS
BEGIN
/*BODY */
END SP_1;

Call the procedure SP_1 which will return the REFCURSOR as an output parameter

CREATE OR REPLACE SP_2 
(
oCurSp2 OUT SYS_REFCURSOR
) AS `enter code here`
BEGIN
/* CALL PROCEDURE SP_1 WITH REF CURSOR AS OUTPUT PARAMETER */
SP_1(oCurSp2);
END SP_2;

HTML5 video won't play in Chrome only

Try this

<video autoplay loop id="video-background" muted plays-inline>
            <source src="https://player.vimeo.com/external/158148793.hd.mp4?s=8e8741dbee251d5c35a759718d4b0976fbf38b6f&profile_id=119&oauth2_token_id=57447761" type="video/mp4">
            </video>

Thanks

How to run a .jar in mac?

You don't need JDK to run Java based programs. JDK is for development which stands for Java Development Kit.

You need JRE which should be there in Mac.

Try: java -jar Myjar_file.jar

EDIT: According to this article, for Mac OS 10

The Java runtime is no longer installed automatically as part of the OS installation.

Then, you need to install JRE to your machine.

How to loop through file names returned by find?

You can store your find output in array if you wish to use the output later as:

array=($(find . -name "*.txt"))

Now to print the each element in new line, you can either use for loop iterating to all the elements of array, or you can use printf statement.

for i in ${array[@]};do echo $i; done

or

printf '%s\n' "${array[@]}"

You can also use:

for file in "`find . -name "*.txt"`"; do echo "$file"; done

This will print each filename in newline

To only print the find output in list form, you can use either of the following:

find . -name "*.txt" -print 2>/dev/null

or

find . -name "*.txt" -print | grep -v 'Permission denied'

This will remove error messages and only give the filename as output in new line.

If you wish to do something with the filenames, storing it in array is good, else there is no need to consume that space and you can directly print the output from find.

How to append text to a text file in C++?

You could use an fstream and open it with the std::ios::app flag. Have a look at the code below and it should clear your head.

...
fstream f("filename.ext", f.out | f.app);
f << "any";
f << "text";
f << "written";
f << "wll";
f << "be append";
...

You can find more information about the open modes here and about fstreams here.

In UML class diagrams, what are Boundary Classes, Control Classes, and Entity Classes?

Often used with/as a part of OOAD and business modeling. The definition by Neil is correct, but it is basically identical to MVC, but just abstracted for the business. The "Good summary" is well done so I will not copy it here as it is not my work, more detailed but inline with Neil's bullet points.

Good summary - Conceito: Entity-Control-Boundary Pattern

OOAD

How to select the nth row in a SQL database table?

But really, isn't all this really just parlor tricks for good database design in the first place? The few times I needed functionality like this it was for a simple one off query to make a quick report. For any real work, using tricks like these is inviting trouble. If selecting a particular row is needed then just have a column with a sequential value and be done with it.

UUID max character length

Most databases have a native UUID type these days to make working with them easier. If yours doesn't, they're just 128-bit numbers, so you can use BINARY(16), and if you need the text format frequently, e.g. for troubleshooting, then add a calculated column to generate it automatically from the binary column. There is no good reason to store the (much larger) text form.

Apache redirect to another port

Just use a Reverse Proxy in your apache configuration (directly):

ProxyPass /foo http://foo.example.com/bar
ProxyPassReverse /foo http://foo.example.com/bar

Look here for apache documentation of how to use the mod

Select Multiple Fields from List in Linq

You can select multiple fields using linq Select as shown above in various examples this will return as an Anonymous Type. If you want to avoid this anonymous type here is the simple trick.

var items = listObject.Select(f => new List<int>() { f.Item1, f.Item2 }).SelectMany(item => item).Distinct();

I think this solves your problem

Delete a row in Excel VBA

Better yet, use union to grab all the rows you want to delete, then delete them all at once. The rows need not be continuous.

dim rng as range
dim rDel as range

for each rng in {the range you're searching}
   if {Conditions to be met} = true then
      if not rDel is nothing then
         set rDel = union(rng,rDel)
      else
         set rDel = rng
      end if
   end if
 next
 
 rDel.entirerow.delete

That way you don't have to worry about sorting or things being at the bottom.

Converting Secret Key into a String and Vice Versa

To show how much fun it is to create some functions that are fail fast I've written the following 3 functions.

One creates an AES key, one encodes it and one decodes it back. These three methods can be used with Java 8 (without dependence of internal classes or outside dependencies):

public static SecretKey generateAESKey(int keysize)
        throws InvalidParameterException {
    try {
        if (Cipher.getMaxAllowedKeyLength("AES") < keysize) {
            // this may be an issue if unlimited crypto is not installed
            throw new InvalidParameterException("Key size of " + keysize
                    + " not supported in this runtime");
        }

        final KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(keysize);
        return keyGen.generateKey();
    } catch (final NoSuchAlgorithmException e) {
        // AES functionality is a requirement for any Java SE runtime
        throw new IllegalStateException(
                "AES should always be present in a Java SE runtime", e);
    }
}

public static SecretKey decodeBase64ToAESKey(final String encodedKey)
        throws IllegalArgumentException {
    try {
        // throws IllegalArgumentException - if src is not in valid Base64
        // scheme
        final byte[] keyData = Base64.getDecoder().decode(encodedKey);
        final int keysize = keyData.length * Byte.SIZE;

        // this should be checked by a SecretKeyFactory, but that doesn't exist for AES
        switch (keysize) {
        case 128:
        case 192:
        case 256:
            break;
        default:
            throw new IllegalArgumentException("Invalid key size for AES: " + keysize);
        }

        if (Cipher.getMaxAllowedKeyLength("AES") < keysize) {
            // this may be an issue if unlimited crypto is not installed
            throw new IllegalArgumentException("Key size of " + keysize
                    + " not supported in this runtime");
        }

        // throws IllegalArgumentException - if key is empty
        final SecretKeySpec aesKey = new SecretKeySpec(keyData, "AES");
        return aesKey;
    } catch (final NoSuchAlgorithmException e) {
        // AES functionality is a requirement for any Java SE runtime
        throw new IllegalStateException(
                "AES should always be present in a Java SE runtime", e);
    }
}

public static String encodeAESKeyToBase64(final SecretKey aesKey)
        throws IllegalArgumentException {
    if (!aesKey.getAlgorithm().equalsIgnoreCase("AES")) {
        throw new IllegalArgumentException("Not an AES key");
    }

    final byte[] keyData = aesKey.getEncoded();
    final String encodedKey = Base64.getEncoder().encodeToString(keyData);
    return encodedKey;
}

How to store phone numbers on MySQL databases?

You should never store values with format. Formatting should be done in the view depending on user preferences.

Searching for phone nunbers with mixed formatting is near impossible.

For this case I would split into fields and store as integer. Numbers are faster than texts and splitting them and putting index on them makes all kind of queries ran fast.

Leading 0 could be a problem but probably not. In Sweden all area codes start with 0 and that is removed if also a country code is dialed. But the 0 isn't really a part of the number, it's a indicator used to tell that I'm adding an area code. Same for country code, you add 00 to say that you use a county code.

Leading 0 shouldn't be stored, they should be added when needed. Say you store 00 in the database and you use a server that only works with + they you have to replace 00 with + for that application.

So, store numbers as numbers.

Javascript one line If...else...else if statement

Sure, you can do nested ternary operators but they are hard to read.

var variable = (condition) ? (true block) : ((condition2) ? (true block2) : (else block2))

Can a for loop increment/decrement by more than one?

for (var i = 0; i < 10; i = i + 2) {
    // code here
}?

Get $_POST from multiple checkboxes

<input type="checkbox" name="check_list[<? echo $row['Report ID'] ?>]" value="<? echo $row['Report ID'] ?>">

And after the post, you can loop through them:

   if(!empty($_POST['check_list'])){
     foreach($_POST['check_list'] as $report_id){
        echo "$report_id was checked! ";
     }
   }

Or get a certain value posted from previous page:

if(isset($_POST['check_list'][$report_id])){
  echo $report_id . " was checked!<br/>";
}

How to hide a div element depending on Model value? MVC

Try:

<div style="@(Model.booleanVariable ? "display:block" : "display:none")">Some links</div>

Use the "Display" style attribute with your bool model attribute to define the div's visibility.

Bootstrap 4 - Responsive cards in card-columns

If you are using Sass:

$card-column-sizes: (
    xs: 2,
    sm: 3,
    md: 4,
    lg: 5,
);

@each $breakpoint-size, $column-count in $card-column-sizes {
    @include media-breakpoint-up($breakpoint-size) {
      .card-columns {
        column-count: $column-count;
        column-gap: 1.25rem;

        .card {
          display: inline-block;
          width: 100%; // Don't let them exceed the column width
        }
      }
    }
}

Sublime Text 3 how to change the font size of the file sidebar?

Some limited flexibility is available if your using the Afterglow Theme.

https://github.com/YabataDesign/afterglow-theme

You can edit your user preferences in the following way.

Sublime Text -> Preferences -> Settings - User:

{
    "sidebar_size_14": true
}

https://github.com/YabataDesign/afterglow-theme#sidebar-size-options

Understanding the basics of Git and GitHub

  1. What is the difference between Git and GitHub?

    Git is a version control system; think of it as a series of snapshots (commits) of your code. You see a path of these snapshots, in which order they where created. You can make branches to experiment and come back to snapshots you took.

    GitHub, is a web-page on which you can publish your Git repositories and collaborate with other people.

  2. Is Git saving every repository locally (in the user's machine) and in GitHub?

    No, it's only local. You can decide to push (publish) some branches on GitHub.

  3. Can you use Git without GitHub? If yes, what would be the benefit for using GitHub?

    Yes, Git runs local if you don't use GitHub. An alternative to using GitHub could be running Git on files hosted on Dropbox, but GitHub is a more streamlined service as it was made especially for Git.

  4. How does Git compare to a backup system such as Time Machine?

    It's a different thing, Git lets you track changes and your development process. If you use Git with GitHub, it becomes effectively a backup. However usually you would not push all the time to GitHub, at which point you do not have a full backup if things go wrong. I use git in a folder that is synchronized with Dropbox.

  5. Is this a manual process, in other words if you don't commit you won't have a new version of the changes made?

    Yes, committing and pushing are both manual.

  6. If are not collaborating and you are already using a backup system why would you use Git?

    • If you encounter an error between commits you can use the command git diff to see the differences between the current code and the last working commit, helping you to locate your error.

    • You can also just go back to the last working commit.

    • If you want to try a change, but are not sure that it will work. You create a branch to test you code change. If it works fine, you merge it to the main branch. If it does not you just throw the branch away and go back to the main branch.

    • You did some debugging. Before you commit you always look at the changes from the last commit. You see your debug print statement that you forgot to delete.

Make sure you check gitimmersion.com.

How to use a DataAdapter with stored procedure and parameter

 SqlConnection con = new SqlConnection(@"Some Connection String");
 SqlDataAdapter da = new SqlDataAdapter("ParaEmp_Select",con);
            da.SelectCommand.CommandType = CommandType.StoredProcedure;
            da.SelectCommand.Parameters.Add("@Contactid", SqlDbType.Int).Value = 123;
            DataTable dt = new DataTable();
            da.Fill(dt);
            dataGridView1.DataSource = dt;

PHP display image BLOB from MySQL

This is what I use to display images from blob:

echo '<img src="data:image/jpeg;base64,'.base64_encode($image->load()) .'" />';

Could pandas use column as index?

You can change the index as explained already using set_index. You don't need to manually swap rows with columns, there is a transpose (data.T) method in pandas that does it for you:

> df = pd.DataFrame([['ABBOTSFORD', 427000, 448000],
                    ['ABERFELDIE', 534000, 600000]],
                    columns=['Locality', 2005, 2006])

> newdf = df.set_index('Locality').T
> newdf

Locality    ABBOTSFORD  ABERFELDIE
2005        427000      534000
2006        448000      600000

then you can fetch the dataframe column values and transform them to a list:

> newdf['ABBOTSFORD'].values.tolist()

[427000, 448000]

Importing CSV data using PHP/MySQL

i think the main things to remember about parsing csv is that it follows some simple rules:

a)it's a text file so easily opened b) each row is determined by a line end \n so split the string into lines first c) each row/line has columns determined by a comma so split each line by that to get an array of columns

have a read of this post to see what i am talking about

it's actually very easy to do once you have the hang of it and becomes very useful.

How can I take a screenshot with Selenium WebDriver?

C#

public Bitmap TakeScreenshot(By by) {
    // 1. Make screenshot of all screen
    var screenshotDriver = _selenium as ITakesScreenshot;
    Screenshot screenshot = screenshotDriver.GetScreenshot();
    var bmpScreen = new Bitmap(new MemoryStream(screenshot.AsByteArray));

    // 2. Get screenshot of specific element
    IWebElement element = FindElement(by);
    var cropArea = new Rectangle(element.Location, element.Size);
    return bmpScreen.Clone(cropArea, bmpScreen.PixelFormat);
}

How to add MVC5 to Visual Studio 2013?

Select web development tools when you install the visual studio 2013. Then it will work properly and show the asp.net web applicaton.

How to run JUnit tests with Gradle?

If you want to add a sourceSet for testing in addition to all the existing ones, within a module regardless of the active flavor:

sourceSets {
    test {
        java.srcDirs += [
                'src/customDir/test/kotlin'
        ]
        print(java.srcDirs)   // Clean
    }
}

Pay attention to the operator += and if you want to run integration tests change test to androidTest.

GL

How to configure static content cache per folder and extension in IIS7?

You can do it on a per file basis. Use the path attribute to include the filename

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <location path="YourFileNameHere.xml">
        <system.webServer>
            <staticContent>
                <clientCache cacheControlMode="DisableCache" />
            </staticContent>
        </system.webServer>
    </location>
</configuration>

What does \u003C mean?

It is a unicode char \u003C = <

Is it possible to set ENV variables for rails development environment in my code?

The way I am trying to do this in my question actually works!

# environment/development.rb

ENV['admin_password'] = "secret" 

I just had to restart the server. I thought running reload! in rails console would be enough but I also had to restart the web server.

I am picking my own answer because I feel this is a better place to put and set the ENV variables

Open a URL in a new tab (and not a new window)

Just omitting [strWindowFeatures] parameters will open a new tab, UNLESS the browser setting overrides (browser setting trumps JavaScript).

New window

var myWin = window.open(strUrl, strWindowName, [strWindowFeatures]);

New tab

var myWin = window.open(strUrl, strWindowName);

-- or --

var myWin = window.open(strUrl);

select records from postgres where timestamp is in certain range

Search till the seconds for the timestamp column in postgress

select * from "TableName" e
    where timestamp >= '2020-08-08T13:00:00' and timestamp < '2020-08-08T17:00:00';

pandas read_csv and filter columns with usecols

The solution lies in understanding these two keyword arguments:

  • names is only necessary when there is no header row in your file and you want to specify other arguments (such as usecols) using column names rather than integer indices.
  • usecols is supposed to provide a filter before reading the whole DataFrame into memory; if used properly, there should never be a need to delete columns after reading.

So because you have a header row, passing header=0 is sufficient and additionally passing names appears to be confusing pd.read_csv.

Removing names from the second call gives the desired output:

import pandas as pd
from StringIO import StringIO

csv = r"""dummy,date,loc,x
bar,20090101,a,1
bar,20090102,a,3
bar,20090103,a,5
bar,20090101,b,1
bar,20090102,b,3
bar,20090103,b,5"""

df = pd.read_csv(StringIO(csv),
        header=0,
        index_col=["date", "loc"], 
        usecols=["date", "loc", "x"],
        parse_dates=["date"])

Which gives us:

                x
date       loc
2009-01-01 a    1
2009-01-02 a    3
2009-01-03 a    5
2009-01-01 b    1
2009-01-02 b    3
2009-01-03 b    5

Laravel password validation rule

I have had a similar scenario in Laravel and solved it in the following way.

The password contains characters from at least three of the following five categories:

  • English uppercase characters (A – Z)
  • English lowercase characters (a – z)
  • Base 10 digits (0 – 9)
  • Non-alphanumeric (For example: !, $, #, or %)
  • Unicode characters

First, we need to create a regular expression and validate it.

Your regular expression would look like this:

^.*(?=.{3,})(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[\d\x])(?=.*[!$#%]).*$

I have tested and validated it on this site. Yet, perform your own in your own manner and adjust accordingly. This is only an example of regex, you can manipluated the way you want.

So your final Laravel code should be like this:

'password' => 'required|
               min:6|
               regex:/^.*(?=.{3,})(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[\d\x])(?=.*[!$#%]).*$/|
               confirmed',

Update As @NikK in the comment mentions, in Laravel 5.5 and newer the the password value should encapsulated in array Square brackets like

'password' => ['required', 
               'min:6', 
               'regex:/^.*(?=.{3,})(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[\d\x])(?=.*[!$#%]).*$/', 
               'confirmed']

I have not testing it on Laravel 5.5 so I am trusting @NikK hence I have moved to working with c#/.net these days and have no much time for Laravel.

Note:

  1. I have tested and validated it on both the regular expression site and a Laravel 5 test environment and it works.
  2. I have used min:6, this is optional but it is always a good practice to have a security policy that reflects different aspects, one of which is minimum password length.
  3. I suggest you to use password confirmed to ensure user typing correct password.
  4. Within the 6 characters our regex should contain at least 3 of a-z or A-Z and number and special character.
  5. Always test your code in a test environment before moving to production.
  6. Update: What I have done in this answer is just example of regex password

Some online references

Regarding your custom validation message for the regex rule in Laravel, here are a few links to look at:

C char array initialization

I'm not sure but I commonly initialize an array to "" in that case I don't need worry about the null end of the string.

main() {
    void something(char[]);
    char s[100] = "";

    something(s);
    printf("%s", s);
}

void something(char s[]) {
    // ... do something, pass the output to s
    // no need to add s[i] = '\0'; because all unused slot is already set to '\0'
}

Creating a segue programmatically

You have to link your code to the UIStoryboard that you're using. Make sure you go into YourViewController in your UIStoryboard, click on the border around it, and then set its identifier field to a NSString that you call in your code.

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" 
                                                     bundle:nil];
YourViewController *yourViewController = 
 (YourViewController *)
  [storyboard instantiateViewControllerWithIdentifier:@"yourViewControllerID"];
[self.navigationController pushViewController:yourViewController animated:YES];

Keep only first n characters in a string?

You are looking for JavaScript's String method substring

e.g.

'Hiya how are you'.substring(0,8);

Which returns the string starting at the first character and finishing before the 9th character - i.e. 'Hiya how'.

substring documentation

Quoting backslashes in Python string literals

Another way to end a string with a backslash is to end the string with a backslash followed by a space, and then call the .strip() function on the string.

I was trying to concatenate two string variables and have them separated by a backslash, so i used the following:

newString = string1 + "\ ".strip() + string2

Git on Windows: How do you set up a mergetool?

To follow-up on Charles Bailey's answer, here's my git setup that's using p4merge (free cross-platform 3way merge tool); tested on msys Git (Windows) install:

git config --global merge.tool p4merge
git config --global mergetool.p4merge.cmd 'p4merge.exe \"$BASE\" \"$LOCAL\" \"$REMOTE\" \"$MERGED\"'

or, from a windows cmd.exe shell, the second line becomes :

git config --global mergetool.p4merge.cmd "p4merge.exe \"$BASE\" \"$LOCAL\" \"$REMOTE\" \"$MERGED\""

The changes (relative to Charles Bailey):

  • added to global git config, i.e. valid for all git projects not just the current one
  • the custom tool config value resides in "mergetool.[tool].cmd", not "merge.[tool].cmd" (silly me, spent an hour troubleshooting why git kept complaining about non-existing tool)
  • added double quotes for all file names so that files with spaces can still be found by the merge tool (I tested this in msys Git from Powershell)
  • note that by default Perforce will add its installation dir to PATH, thus no need to specify full path to p4merge in the command

Download: http://www.perforce.com/product/components/perforce-visual-merge-and-diff-tools


EDIT (Feb 2014)

As pointed out by @Gregory Pakosz, latest msys git now "natively" supports p4merge (tested on 1.8.5.2.msysgit.0).

You can display list of supported tools by running:

git mergetool --tool-help

You should see p4merge in either available or valid list. If not, please update your git.

If p4merge was listed as available, it is in your PATH and you only have to set merge.tool:

git config --global merge.tool p4merge

If it was listed as valid, you have to define mergetool.p4merge.path in addition to merge.tool:

git config --global mergetool.p4merge.path c:/Users/my-login/AppData/Local/Perforce/p4merge.exe
  • The above is an example path when p4merge was installed for the current user, not system-wide (does not need admin rights or UAC elevation)
  • Although ~ should expand to current user's home directory (so in theory the path should be ~/AppData/Local/Perforce/p4merge.exe), this did not work for me
  • Even better would have been to take advantage of an environment variable (e.g. $LOCALAPPDATA/Perforce/p4merge.exe), git does not seem to be expanding environment variables for paths (if you know how to get this working, please let me know or update this answer)

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

You'll need to serialize to something: that is, pick binary, or xml (for default serializers) or write custom serialization code to serialize to some other text form.

Once you've picked that, your serialization will (normally) call a Stream that is writing to some kind of file.

So, with your code, if I were using XML Serialization:

var path = @"C:\Test\myserializationtest.xml";
using(FileStream fs = new FileStream(path, FileMode.Create))
{
    XmlSerializer xSer = new XmlSerializer(typeof(SomeClass));

    xSer.Serialize(fs, serializableObject);
}

Then, to deserialize:

using(FileStream fs = new FileStream(path, FileMode.Open)) //double check that...
{
    XmlSerializer _xSer = new XmlSerializer(typeof(SomeClass));

    var myObject = _xSer.Deserialize(fs);
}

NOTE: This code hasn't been compiled, let alone run- there may be some errors. Also, this assumes completely out-of-the-box serialization/deserialization. If you need custom behavior, you'll need to do additional work.

How to call a RESTful web service from Android?

Perhaps am late or maybe you've already used it before but there is another one called ksoap and its pretty amazing.. It also includes timeouts and can parse any SOAP based webservice efficiently. I also made a few changes to suit my parsing.. Look it up

How can one create an overlay in css?

You can use position:absolute to position an overlay inside of your div and then stretch it in all directions like so:

CSS updated *

.overlay {
    position:absolute;
    top:0;
    left:0;
    right:0;
    bottom:0;
    background-color:rgba(0, 0, 0, 0.85);
    background: url(data:;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAYAAABytg0kAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAABl0RVh0U29mdHdhcmUAUGFpbnQuTkVUIHYzLjUuNUmK/OAAAAATSURBVBhXY2RgYNgHxGAAYuwDAA78AjwwRoQYAAAAAElFTkSuQmCC) repeat scroll transparent\9; /* ie fallback png background image */
    z-index:9999;
    color:white;
}

You just need to make sure that your parent div has the position:relative property added to it and a lower z-index.


Made a demo that should work in all browsers, including IE7+, for a commenter below.

Demo

Removed the opacity property from the css and instead used an rGBA color to give the background, and only the background, an opacity level. This way the content that the overlay carries will not be affected. Since IE does not support rGBA i used an IE hack instead to give it an base64 encoded PNG background image that fills the overlay div instead, this way we can evade IEs opacity issue where it applies the opacity to the children elements as well.

Is there a C# case insensitive equals operator?

You can use

if (stringA.equals(StringB, StringComparison.CurrentCultureIgnoreCase))

How do I set specific environment variables when debugging in Visual Studio?

In Visual Studio 2008 and Visual Studio 2005 at least, you can specify changes to environment variables in the project settings.

Open your project. Go to Project -> Properties... Under Configuration Properties -> Debugging, edit the 'Environment' value to set environment variables.

For example, if you want to add the directory "c:\foo\bin" to the path when debugging your application, set the 'Environment' value to "PATH=%PATH%;c:\foo\bin".

Here's a screenshot of the settings dialog

How to limit text width

Try

<div style="max-width:200px; word-wrap:break-word;">Texttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt</div>

What exactly is an instance in Java?

An object and an instance are the same thing.

Personally I prefer to use the word "instance" when referring to a specific object of a specific type, for example "an instance of type Foo". But when talking about objects in general I would say "objects" rather than "instances".

A reference either refers to a specific object or else it can be a null reference.


They say that they have to create an instance to their application. What does it mean?

They probably mean you have to write something like this:

Foo foo = new Foo();

If you are unsure what type you should instantiate you should contact the developers of the application and ask for a more complete example.

SQL to add column and comment in table in single command

Add comments for two different columns of the EMPLOYEE table :

COMMENT ON EMPLOYEE
     (WORKDEPT IS 'see DEPARTMENT table for names',
     EDLEVEL IS 'highest grade level passed in school' )

How to prevent long words from breaking my div?

The solution I usually use for this problem is to set 2 different css rules for IE and other browsers:

word-wrap: break-word;

woks perfect in IE, but word-wrap is not a standard CSS property. It's a Microsoft specific property and doesn't work in Firefox.

For Firefox, the best thing to do using only CSS is to set the rule

overflow: hidden;

for the element that contains the text you want to wrap. It doesn't wrap the text, but hide the part of text that go over the limit of the container. It can be a nice solution if is not essential for you to display all the text (i.e. if the text is inside an <a> tag)

CMD (command prompt) can't go to the desktop

You need to use the change directory command 'cd' to change directory

cd C:\Users\MyName\Desktop

you can use cd \d to change the drive as well.

link for additional resources http://ss64.com/nt/cd.html

Writing a list to a file with Python

Serialize list into text file with comma sepparated value

mylist = dir()
with open('filename.txt','w') as f:
    f.write( ','.join( mylist ) )

What is the difference between loose coupling and tight coupling in the object oriented paradigm?

It's about classes dependency rate to another ones which is so low in loosely coupled and so high in tightly coupled. To be clear in the service orientation architecture, services are loosely coupled to each other against monolithic which classes dependency to each other is on purpose

R define dimensions of empty data frame

seq_along may help to find out how many rows in your data file and create a data.frame with the desired number of rows

    listdf <- data.frame(ID=seq_along(df),
                              var1=seq_along(df), var2=seq_along(df))

Use placeholders in yaml

With Yglu Structural Templating, your example can be written:

foo: !()
  !? $.propname: 
     type: number 
     default: !? $.default

bar:
  !apply .foo: 
    propname: "some_prop"
    default: "some default"

Disclaimer: I am the author or Yglu.

How to add number of days in postgresql datetime

This will give you the deadline :

select id,  
       title,
       created_at + interval '1' day * claim_window as deadline
from projects

Alternatively the function make_interval can be used:

select id,  
       title,
       created_at + make_interval(days => claim_window) as deadline
from projects

To get all projects where the deadline is over, use:

select *
from (
  select id, 
         created_at + interval '1' day * claim_window as deadline
  from projects
) t
where localtimestamp at time zone 'UTC' > deadline

Is there a good Valgrind substitute for Windows?

There is Pageheap.exe part of the debugging tools for Windows. It's free and is basically a custom memory allocator/deallocator.

See http://support.microsoft.com/kb/286470

JavaScript to get rows count of a HTML table

$('tableName').find('tr').length

NullInjectorError: No provider for AngularFirestore

import angularFirebaseStore 

in app.module.ts and set it as a provider like service

How to use Google Translate API in my Java application?

Generate your own API key here. Check out the documentation here.

You may need to set up a billing account when you try to enable the Google Cloud Translation API in your account.

Below is a quick start example which translates two English strings to Spanish:

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Arrays;

import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.translate.Translate;
import com.google.api.services.translate.model.TranslationsListResponse;
import com.google.api.services.translate.model.TranslationsResource;

public class QuickstartSample
{
    public static void main(String[] arguments) throws IOException, GeneralSecurityException
    {
        Translate t = new Translate.Builder(
                GoogleNetHttpTransport.newTrustedTransport()
                , GsonFactory.getDefaultInstance(), null)
                // Set your application name
                .setApplicationName("Stackoverflow-Example")
                .build();
        Translate.Translations.List list = t.new Translations().list(
                Arrays.asList(
                        // Pass in list of strings to be translated
                        "Hello World",
                        "How to use Google Translate from Java"),
                // Target language
                "ES");

        // TODO: Set your API-Key from https://console.developers.google.com/
        list.setKey("your-api-key");
        TranslationsListResponse response = list.execute();
        for (TranslationsResource translationsResource : response.getTranslations())
        {
            System.out.println(translationsResource.getTranslatedText());
        }
    }
}

Required maven dependencies for the code snippet:

<dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-translate</artifactId>
    <version>LATEST</version>
</dependency>

<dependency>
    <groupId>com.google.http-client</groupId>
    <artifactId>google-http-client-gson</artifactId>
    <version>LATEST</version>
</dependency>

How to convert string to datetime format in pandas python?

Approach: 1

Given original string format: 2019/03/04 00:08:48

you can use

updated_df = df['timestamp'].astype('datetime64[ns]')

The result will be in this datetime format: 2019-03-04 00:08:48

Approach: 2

updated_df = df.astype({'timestamp':'datetime64[ns]'})

How to reload apache configuration for a site without restarting apache?

It should be possible using the command

sudo /etc/init.d/apache2 reload

I hope that helps.

What's the difference between Perl's backticks, system, and exec?

The difference between 'exec' and 'system' is that exec replaces your current program with 'command' and NEVER returns to your program. system, on the other hand, forks and runs 'command' and returns you the exit status of 'command' when it is done running. The back tick runs 'command' and then returns a string representing its standard out (whatever it would have printed to the screen)

You can also use popen to run shell commands and I think that there is a shell module - 'use shell' that gives you transparent access to typical shell commands.

Hope that clarifies it for you.

Apache Tomcat Not Showing in Eclipse Server Runtime Environments

Help -> check for updates upon Eclipse update solved the issue

Is it possible to Turn page programmatically in UIPageViewController?

This code worked nicely for me, thanks.

This is what i did with it. Some methods for stepping forward or backwards and one for going directly to a particular page. Its for a 6 page document in portrait view. It will work ok if you paste it into the implementation of the RootController of the pageViewController template.

-(IBAction)pageGoto:(id)sender {

    //get page to go to
    NSUInteger pageToGoTo = 4;

    //get current index of current page
    DataViewController *theCurrentViewController = [self.pageViewController.viewControllers   objectAtIndex:0];
    NSUInteger retreivedIndex = [self.modelController indexOfViewController:theCurrentViewController];

    //get the page(s) to go to
    DataViewController *targetPageViewController = [self.modelController viewControllerAtIndex:(pageToGoTo - 1) storyboard:self.storyboard];

    DataViewController *secondPageViewController = [self.modelController viewControllerAtIndex:(pageToGoTo) storyboard:self.storyboard];

    //put it(or them if in landscape view) in an array
    NSArray *theViewControllers = nil;    
    theViewControllers = [NSArray arrayWithObjects:targetPageViewController, secondPageViewController, nil];


    //check which direction to animate page turn then turn page accordingly
    if (retreivedIndex < (pageToGoTo - 1) && retreivedIndex != (pageToGoTo - 1)){
        [self.pageViewController setViewControllers:theViewControllers direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:NULL];
    }

    if (retreivedIndex > (pageToGoTo - 1) && retreivedIndex != (pageToGoTo - 1)){
        [self.pageViewController setViewControllers:theViewControllers direction:UIPageViewControllerNavigationDirectionReverse animated:YES completion:NULL];
    }

}


-(IBAction)pageFoward:(id)sender {

    //get current index of current page
    DataViewController *theCurrentViewController = [self.pageViewController.viewControllers objectAtIndex:0];
    NSUInteger retreivedIndex = [self.modelController indexOfViewController:theCurrentViewController];

    //check that current page isn't first page
    if (retreivedIndex < 5){

        //get the page to go to
        DataViewController *targetPageViewController = [self.modelController viewControllerAtIndex:(retreivedIndex + 1) storyboard:self.storyboard];

        //put it(or them if in landscape view) in an array
        NSArray *theViewControllers = nil;    
        theViewControllers = [NSArray arrayWithObjects:targetPageViewController, nil];

        //add page view
        [self.pageViewController setViewControllers:theViewControllers direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:NULL];

    }

}


-(IBAction)pageBack:(id)sender {


    //get current index of current page
    DataViewController *theCurrentViewController = [self.pageViewController.viewControllers objectAtIndex:0];
    NSUInteger retreivedIndex = [self.modelController indexOfViewController:theCurrentViewController];

    //check that current page isn't first page
    if (retreivedIndex > 0){

    //get the page to go to
    DataViewController *targetPageViewController = [self.modelController viewControllerAtIndex:(retreivedIndex - 1) storyboard:self.storyboard];

    //put it(or them if in landscape view) in an array
    NSArray *theViewControllers = nil;    
    theViewControllers = [NSArray arrayWithObjects:targetPageViewController, nil];

    //add page view
    [self.pageViewController setViewControllers:theViewControllers direction:UIPageViewControllerNavigationDirectionReverse animated:YES completion:NULL];

    }

}

Can I give the col-md-1.5 in bootstrap?

This question is quite old, but I have made it that way (in TYPO3).

Firstly, I have made a own accessible css-class which I can choose on every content element manually.

Then, I have made a outer three column element with 11 columns (1 - 9 - 1), finally, I have modified the column width of the first and third column with CSS to 12.499999995%.

In Python, how do I split a string and keep the separators?

>>> re.split('(\W)', 'foo/bar spam\neggs')
['foo', '/', 'bar', ' ', 'spam', '\n', 'eggs']

How to start working with GTest and CMake

The solution involved putting the gtest source directory as a subdirectory of your project. I've included the working CMakeLists.txt below if it is helpful to anyone.

cmake_minimum_required(VERSION 2.6)
project(basic_test)

################################
# GTest
################################
ADD_SUBDIRECTORY (gtest-1.6.0)
enable_testing()
include_directories(${gtest_SOURCE_DIR}/include ${gtest_SOURCE_DIR})

################################
# Unit Tests
################################
# Add test cpp file
add_executable( runUnitTests testgtest.cpp )
# Link test executable against gtest & gtest_main
target_link_libraries(runUnitTests gtest gtest_main)
add_test( runUnitTests runUnitTests )

Server configuration by allow_url_fopen=0 in

Use this code in your php script (first lines)

ini_set('allow_url_fopen',1);

How to iterate over the file in python

Just use for x in f: ..., this gives you line after line, is much shorter and readable (partly because it automatically stops when the file ends) and also saves you the rstrip call because the trailing newline is already stipped.

The error is caused by the exit condition, which can never be true: Even if the file is exhausted, readline will return an empty string, not None. Also note that you could still run into trouble with empty lines, e.g. at the end of the file. Adding if line.strip() == "": continue makes the code ignore blank lines, which is propably a good thing anyway.

Matrix multiplication in OpenCV

You say that the matrices are the same dimensions, and yet you are trying to perform matrix multiplication on them. Multiplication of matrices with the same dimension is only possible if they are square. In your case, you get an assertion error, because the dimensions are not square. You have to be careful when multiplying matrices, as there are two possible meanings of multiply.

Matrix multiplication is where two matrices are multiplied directly. This operation multiplies matrix A of size [a x b] with matrix B of size [b x c] to produce matrix C of size [a x c]. In OpenCV it is achieved using the simple * operator:

C = A * B

Element-wise multiplication is where each pixel in the output matrix is formed by multiplying that pixel in matrix A by its corresponding entry in matrix B. The input matrices should be the same size, and the output will be the same size as well. This is achieved using the mul() function:

output = A.mul(B);

Convert int to ASCII and back in Python

ASCII to int:

ord('a')

gives 97

And back to a string:

  • in Python2: str(unichr(97))
  • in Python3: chr(97)

gives 'a'

How can I close a dropdown on click outside?

If you're doing this on iOS, use the touchstart event as well:

As of Angular 4, the HostListener decorate is the preferred way to do this

import { Component, OnInit, HostListener, ElementRef } from '@angular/core';
...
@Component({...})
export class MyComponent implement OnInit {

  constructor(private eRef: ElementRef){}

  @HostListener('document:click', ['$event'])
  @HostListener('document:touchstart', ['$event'])
  handleOutsideClick(event) {
    // Some kind of logic to exclude clicks in Component.
    // This example is borrowed Kamil's answer
    if (!this.eRef.nativeElement.contains(event.target) {
      doSomethingCool();
    }
  }

}

How do I store the select column in a variable?

This is how to assign a value to a variable:

SELECT @EmpID = Id
  FROM dbo.Employee

However, the above query is returning more than one value. You'll need to add a WHERE clause in order to return a single Id value.

rmagick gem install "Can't find Magick-config"

When building native Ruby gems, sometimes you'll get an error containing "ruby extconf.rb". This is often caused by missing development libraries for the gem you're installing, or even Ruby itself.

Do you have apt installed on your machine? If not, I'd recommend installing it, because it's a quick and easy way to get a lot of development libraries.

If you see people suggest installing "libmagick9-dev", that's an apt package that you'd install with:

$ sudo apt-get install libmagickwand-dev imagemagick

or on centOs:

$ yum install ImageMagick-devel

On Mac OS, you can use Homebrew:

$ brew install imagemagick

How do I convert a list into a string with spaces in Python?

So in order to achieve a desired output, we should first know how the function works.

The syntax for join() method as described in the python documentation is as follows:

string_name.join(iterable)

Things to be noted:

  • It returns a string concatenated with the elements of iterable. The separator between the elements being the string_name.
  • Any non-string value in the iterable will raise a TypeError

Now, to add white spaces, we just need to replace the string_name with a " " or a ' ' both of them will work and place the iterable that we want to concatenate.

So, our function will look something like this:

' '.join(my_list)

But, what if we want to add a particular number of white spaces in between our elements in the iterable ?

We need to add this:

str(number*" ").join(iterable)

here, the number will be a user input.

So, for example if number=4.

Then, the output of str(4*" ").join(my_list) will be how are you, so in between every word there are 4 white spaces.

Find an element in DOM based on an attribute value

FindByAttributeValue("Attribute-Name", "Attribute-Value");   

p.s. if you know exact element-type, you add 3rd parameter (i.e.div, a, p ...etc...):

FindByAttributeValue("Attribute-Name", "Attribute-Value", "div");   

but at first, define this function:

function FindByAttributeValue(attribute, value, element_type)    {
  element_type = element_type || "*";
  var All = document.getElementsByTagName(element_type);
  for (var i = 0; i < All.length; i++)       {
    if (All[i].getAttribute(attribute) == value) { return All[i]; }
  }
}

p.s. updated per comments recommendations.

MySQL: Fastest way to count number of rows

After speaking with my team-mates, Ricardo told us that the faster way is:

show table status like '<TABLE NAME>' \G

But you have to remember that the result may not be exact.

You can use it from command line too:

$ mysqlshow --status <DATABASE> <TABLE NAME>

More information: http://dev.mysql.com/doc/refman/5.7/en/show-table-status.html

And you can find a complete discussion at mysqlperformanceblog

Difference between opening a file in binary vs text

The most important difference to be aware of is that with a stream opened in text mode you get newline translation on non-*nix systems (it's also used for network communications, but this isn't supported by the standard library). In *nix newline is just ASCII linefeed, \n, both for internal and external representation of text. In Windows the external representation often uses a carriage return + linefeed pair, "CRLF" (ASCII codes 13 and 10), which is converted to a single \n on input, and conversely on output.


From the C99 standard (the N869 draft document), §7.19.2/2,

A text stream is an ordered sequence of characters composed into lines, each line consisting of zero or more characters plus a terminating new-line character. Whether the last line requires a terminating new-line character is implementation-defined. Characters may have to be added, altered, or deleted on input and output to conform to differing conventions for representing text in the host environment. Thus, there need not be a one- to-one correspondence between the characters in a stream and those in the external representation. Data read in from a text stream will necessarily compare equal to the data that were earlier written out to that stream only if: the data consist only of printing characters and the control characters horizontal tab and new-line; no new-line character is immediately preceded by space characters; and the last character is a new-line character. Whether space characters that are written out immediately before a new-line character appear when read in is implementation-defined.

And in §7.19.3/2

Binary files are not truncated, except as defined in 7.19.5.3. Whether a write on a text stream causes the associated file to be truncated beyond that point is implementation- defined.

About use of fseek, in §7.19.9.2/4:

For a text stream, either offset shall be zero, or offset shall be a value returned by an earlier successful call to the ftell function on a stream associated with the same file and whence shall be SEEK_SET.

About use of ftell, in §17.19.9.4:

The ftell function obtains the current value of the file position indicator for the stream pointed to by stream. For a binary stream, the value is the number of characters from the beginning of the file. For a text stream, its file position indicator contains unspecified information, usable by the fseek function for returning the file position indicator for the stream to its position at the time of the ftell call; the difference between two such return values is not necessarily a meaningful measure of the number of characters written or read.

I think that’s the most important, but there are some more details.

Can't use System.Windows.Forms

Adding System.Windows.Forms reference requires .NET Framework project type:

I was using .NET Core project type. This project type doesn't allow us to add assemblies into its project references. I had to move to .NET Framework project type before adding System.Windows.Forms assembly to my references as described in Kendall Frey answer.

Note: There is reference System_Windows_Forms available under COM tab (for both .NET Core and .NET Framework). It is not the right one. It has to be System.Windows.Forms under Assemblies tab.

Receiving login prompt using integrated windows authentication

This fixed it for me.

My Server and Client Pc is Windows 7 and are in same domain

  1. in iis7.5-enable the windows authentication for your Intranet(disable all other authentication.. also No need mention windows authentication in web.config file

  2. then go to the Client PC .. IE8 or 9- Tools-internet Options-Security-Local Intranet-Sites-advanced-Add your site(take off the "require server verfi..." ticketmark..no need

  3. IE8 or 9- Tools-internet Options-Security-Local Intranet-Custom level-userauthentication-logon-select automatic logon with current username and password

  4. save this settings..you are done.. No more prompting for username and password.

  5. Make sure , since your client pc is part of domain, you have to have a GPO for this settings,.. orelse this setting will revert back when user login into windows next time

How to embed new Youtube's live video permanent URL?

The embed URL for a channel's live stream is:

https://www.youtube.com/embed/live_stream?channel=CHANNEL_ID

You can find your CHANNEL_ID at https://www.youtube.com/account_advanced

Limit Get-ChildItem recursion depth

This is a function that outputs one line per item, with indentation according to depth level. It is probably much more readable.

function GetDirs($path = $pwd, [Byte]$ToDepth = 255, [Byte]$CurrentDepth = 0)
{
    $CurrentDepth++
    If ($CurrentDepth -le $ToDepth) {
        foreach ($item in Get-ChildItem $path)
        {
            if (Test-Path $item.FullName -PathType Container)
            {
                "." * $CurrentDepth + $item.FullName
                GetDirs $item.FullName -ToDepth $ToDepth -CurrentDepth $CurrentDepth
            }
        }
    }
}

It is based on a blog post, Practical PowerShell: Pruning File Trees and Extending Cmdlets.

CSS Margin: 0 is not setting to 0

Just use this code at the Start of the main CSS.

       * {
           margin: 0;
           padding: 0;
         }

The above code works in almost all Browsers.

Where are Docker images stored on the host machine?

check for the docker folder in /var/lib

the images are stored at below location:

/var/lib/docker/image/overlay2/imagedb/content

MongoDB distinct aggregation

SQL Query: (group by & count of distinct)

select city,count(distinct(emailId)) from TransactionDetails group by city;

Equivalent mongo query would look like this:

db.TransactionDetails.aggregate([ 
{$group:{_id:{"CITY" : "$cityName"},uniqueCount: {$addToSet: "$emailId"}}},
{$project:{"CITY":1,uniqueCustomerCount:{$size:"$uniqueCount"}} } 
]);

Filter rows which contain a certain string

The answer to the question was already posted by the @latemail in the comments above. You can use regular expressions for the second and subsequent arguments of filter like this:

dplyr::filter(df, !grepl("RTB",TrackingPixel))

Since you have not provided the original data, I will add a toy example using the mtcars data set. Imagine you are only interested in cars produced by Mazda or Toyota.

mtcars$type <- rownames(mtcars)
dplyr::filter(mtcars, grepl('Toyota|Mazda', type))

   mpg cyl  disp  hp drat    wt  qsec vs am gear carb           type
1 21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4      Mazda RX4
2 21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4  Mazda RX4 Wag
3 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1 Toyota Corolla
4 21.5   4 120.1  97 3.70 2.465 20.01  1  0    3    1  Toyota Corona

If you would like to do it the other way round, namely excluding Toyota and Mazda cars, the filter command looks like this:

dplyr::filter(mtcars, !grepl('Toyota|Mazda', type))

Escape double quote in VB string

Another example:

Dim myPath As String = """" & Path.Combine(part1, part2) & """"

Good luck!

ROW_NUMBER() in MySQL

This Work perfectly for me to create RowNumber when we have more than one column. In this case two column.

SELECT @row_num := IF(@prev_value= concat(`Fk_Business_Unit_Code`,`NetIQ_Job_Code`), @row_num+1, 1) AS RowNumber, 
    `Fk_Business_Unit_Code`,   
    `NetIQ_Job_Code`,  
    `Supervisor_Name`,  
    @prev_value := concat(`Fk_Business_Unit_Code`,`NetIQ_Job_Code`)  
FROM (SELECT DISTINCT `Fk_Business_Unit_Code`,`NetIQ_Job_Code`,`Supervisor_Name`         
      FROM Employee    
      ORDER BY `Fk_Business_Unit_Code`, `NetIQ_Job_Code`, `Supervisor_Name` DESC) z,  
(SELECT @row_num := 1) x,  
(SELECT @prev_value := '') y  
ORDER BY `Fk_Business_Unit_Code`, `NetIQ_Job_Code`,`Supervisor_Name` DESC

How To Accept a File POST

API Controller :

[HttpPost]
public HttpResponseMessage Post()
{
    var httpRequest = System.Web.HttpContext.Current.Request;

    if (System.Web.HttpContext.Current.Request.Files.Count < 1)
    {
        //TODO
    }
    else
    {

    try
    { 
        foreach (string file in httpRequest.Files)
        { 
            var postedFile = httpRequest.Files[file];
            BinaryReader binReader = new BinaryReader(postedFile.InputStream);
            byte[] byteArray = binReader.ReadBytes(postedFile.ContentLength);

        }

    }
    catch (System.Exception e)
    {
        //TODO
    }

    return Request.CreateResponse(HttpStatusCode.Created);
}

How do I find the distance between two points?

Let's not forget math.hypot:

dist = math.hypot(x2-x1, y2-y1)

Here's hypot as part of a snippet to compute the length of a path defined by a list of (x, y) tuples:

from math import hypot

pts = [
    (10,10),
    (10,11),
    (20,11),
    (20,10),
    (10,10),
    ]

# Py2 syntax - no longer allowed in Py3
# ptdiff = lambda (p1,p2): (p1[0]-p2[0], p1[1]-p2[1])
ptdiff = lambda p1, p2: (p1[0]-p2[0], p1[1]-p2[1])

diffs = (ptdiff(p1, p2) for p1, p2 in zip (pts, pts[1:]))
path = sum(hypot(*d) for d in  diffs)
print(path)

Failed to execute 'postMessage' on 'DOMWindow': https://www.youtube.com !== http://localhost:9000

Just wishing to avoid the console error, I solved this using a similar approach to Artur's earlier answer, following these steps:

  1. Downloaded the YouTube Iframe API (from https://www.youtube.com/iframe_api) to a local yt-api.js file.
  2. Removed the code which inserted the www-widgetapi.js script.
  3. Downloaded the www-widgetapi.js script (from https://s.ytimg.com/yts/jsbin/www-widgetapi-vfl7VfO1r/www-widgetapi.js) to a local www-widgetapi.js file.
  4. Replaced the targetOrigin argument in the postMessage call which was causing the error in the console, with a "*" (indicating no preference - see https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage).
  5. Appended the modified www-widgetapi.js script to the end of the yt-api.js script.

This is not the greatest solution (patched local script to maintain, losing control of where messages are sent) but it solved my issue.

Please see the security warning about removing the targetOrigin URI stated here before using this solution - https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

Patched yt-api.js example

Get an image extension from an uploaded file in Laravel

The Laravel way

Try this:

$foo = \File::extension($filename);

Pandas : compute mean or std (standard deviation) over entire dataframe

You could convert the dataframe to be a single column with stack (this changes the shape from 5x3 to 15x1) and then take the standard deviation:

df.stack().std()         # pandas default degrees of freedom is one

Alternatively, you can use values to convert from a pandas dataframe to a numpy array before taking the standard deviation:

df.values.std(ddof=1)    # numpy default degrees of freedom is zero

Unlike pandas, numpy will give the standard deviation of the entire array by default, so there is no need to reshape before taking the standard deviation.

A couple of additional notes:

  • The numpy approach here is a bit faster than the pandas one, which is generally true when you have the option to accomplish the same thing with either numpy or pandas. The speed difference will depend on the size of your data, but numpy was roughly 10x faster when I tested a few different sized dataframes on my laptop (numpy version 1.15.4 and pandas version 0.23.4).

  • The numpy and pandas approaches here will not give exactly the same answers, but will be extremely close (identical at several digits of precision). The discrepancy is due to slight differences in implementation behind the scenes that affect how the floating point values get rounded.

Can't connect to MySQL server on 'localhost' (10061) after Installation

  1. In Start Menu, search for "mysql". Among the results, you should see the "MySQL Installer - Community". Run it.

  2. MySQL Installer window will show up as shown below. Find "MySQL Server" under Product and click on "Reconfigure" link.

  3. The MySQL Installer will show up (same one you used for the first MySQL Server installation). Go through all the steps.

  4. After the MySQL Installer was finished, I started the MySQL service again. This time, the "Startup Message Log" on The MySQL Notifier was showing that the server started successfully:

https://www.howtosolutions.net/2017/08/fixing-mysql-10061-error-after-migration-of-database-files/

Getting list of pixel values from PIL

data = numpy.asarray(im)

Notice:In PIL, img is RGBA. In cv2, img is BGRA.

My robust solution:

def cv_from_pil_img(pil_img):
    assert pil_img.mode=="RGBA"
    return cv2.cvtColor(np.array(pil_img), cv2.COLOR_RGBA2BGRA)

How to open html file?

CODE:

import codecs

path="D:\\Users\\html\\abc.html" 
file=codecs.open(path,"rb")
file1=file.read()
file1=str(file1)

how does unix handle full path name with space and arguments?

If the normal ways don't work, trying substituting spaces with %20.

This worked for me when dealing with SSH and other domain-style commands like auto_smb.

How to clear all <div>s’ contents inside a parent <div>?

If all the divs inside that masterdiv needs to be cleared, it this.

$('#masterdiv div').html('');

else, you need to iterate on all the div children of #masterdiv, and check if the id starts with childdiv.

$('#masterdiv div').each(
    function(element){
        if(element.attr('id').substr(0, 8) == "childdiv")
        {
            element.html('');
        }
    }
 );

How to calculate difference between two dates in oracle 11g SQL

You can not use DATEDIFF but you can use this (if columns are not date type):

SELECT 
to_date('2008-08-05','YYYY-MM-DD')-to_date('2008-06-05','YYYY-MM-DD') 
AS DiffDate from dual

you can see the sample

http://sqlfiddle.com/#!4/d41d8/34609

Slicing of a NumPy 2d array, or how do I extract an mxm submatrix from an nxn array (n>m)?

With numpy, you can pass a slice for each component of the index - so, your x[0:2,0:2] example above works.

If you just want to evenly skip columns or rows, you can pass slices with three components (i.e. start, stop, step).

Again, for your example above:

>>> x[1:4:2, 1:4:2]
array([[ 5,  7],
       [13, 15]])

Which is basically: slice in the first dimension, with start at index 1, stop when index is equal or greater than 4, and add 2 to the index in each pass. The same for the second dimension. Again: this only works for constant steps.

The syntax you got to do something quite different internally - what x[[1,3]][:,[1,3]] actually does is create a new array including only rows 1 and 3 from the original array (done with the x[[1,3]] part), and then re-slice that - creating a third array - including only columns 1 and 3 of the previous array.

Cannot find name 'require' after upgrading to Angular4

I moved the tsconfig.json file into a new folder to restructure my project.

So it wasn't able to resolve the path to node_modules/@types folder inside typeRoots property of tsconfig.json

So just update the path from

"typeRoots": [
  "../node_modules/@types"
]

to

"typeRoots": [
  "../../node_modules/@types"
]

To just ensure that the path to node_modules is resolved from the new location of the tsconfig.json

JavaScript: undefined !== undefined?

The problem is that undefined compared to null using == gives true. The common check for undefined is therefore done like this:

typeof x == "undefined"

this ensures the type of the variable is really undefined.

Using jQuery to test if an input has focus

April 2015 Update

Since this question has been around a while, and some new conventions have come into play, I feel that I should mention the .live method has been depreciated.

In its place, the .on method has now been introduced.

Their documentation is quite useful in explaining how it works;

The .on() method attaches event handlers to the currently selected set of elements in the jQuery object. As of jQuery 1.7, the .on() method provides all functionality required for attaching event handlers. For help in converting from older jQuery event methods, see .bind(), .delegate(), and .live().

So, in order for you to target the 'input focused' event, you can use this in a script. Something like:

$('input').on("focus", function(){
   //do some stuff
});

This is quite robust and even allows you to use the TAB key as well.

Time stamp in the C programming language

Standard C99:

#include <time.h>

time_t t0 = time(0);
// ...
time_t t1 = time(0);
double datetime_diff_ms = difftime(t1, t0) * 1000.;

clock_t c0 = clock();
// ...
clock_t c1 = clock();
double runtime_diff_ms = (c1 - c0) * 1000. / CLOCKS_PER_SEC;

The precision of the types is implementation-defined, ie the datetime difference might only return full seconds.

How to check string length and then select substring in Sql Server

To conditionally check the length of the string, use CASE.

SELECT  CASE WHEN LEN(comments) <= 60 
             THEN comments
             ELSE LEFT(comments, 60) + '...'
        END  As Comments
FROM    myView

Assigning a function to a variable

when you perform y=x() you are actually assigning y to the result of calling the function object x and the function has a return value of None. Function calls in python are performed using (). To assign x to y so you can call y just like you would x you assign the function object x to y like y=x and call the function using y()

SQL update trigger only when column is modified

One should check if QtyToRepair is updated at first.

ALTER TRIGGER [dbo].[tr_SCHEDULE_Modified]
   ON [dbo].[SCHEDULE]
   AFTER UPDATE
AS 
BEGIN
SET NOCOUNT ON;
    IF UPDATE (QtyToRepair) 
    BEGIN
        UPDATE SCHEDULE 
        SET modified = GETDATE()
           , ModifiedUser = SUSER_NAME()
           , ModifiedHost = HOST_NAME()
        FROM SCHEDULE S INNER JOIN Inserted I 
            ON S.OrderNo = I.OrderNo and S.PartNumber =    I.PartNumber
        WHERE S.QtyToRepair <> I.QtyToRepair
    END
END

How can I import a large (14 GB) MySQL dump file into a new MySQL database?

On a recent project we had the challenge of working with and manipulating a large collection of data. Our client provided us with a 50 CSV files ranging from 30 MB to 350 MB in size and all in all containing approximately 20 million rows of data and 15 columns of data. Our end goal was to import and manipulate the data into a MySQL relational database to be used to power a front-end PHP script that we also developed. Now, working with a dataset this large or larger is not the simplest of tasks and in working on it we wanted to take a moment to share some of the things you should consider and know when working with large datasets like this.

  1. Analyze Your Dataset Pre-Import

    I can’t stress this first step enough! Make sure that you take the time to analyze the data you are working with before importing it at all. Getting an understand of what all of the data represents, what columns related to what and what type of manipulation you need to will end up saving you time in the long run.

  2. LOAD DATA INFILE is Your Friend

    Importing large data files like the ones we worked with (and larger ones) can be tough to do if you go ahead and try a regular CSV insert via a tool like PHPMyAdmin. Not only will it fail in many cases because your server won’t be able to handle a file upload as large as some of your data files due to upload size restrictions and server timeouts, but even if it does succeed, the process could take hours depending our your hardware. The SQL function LOAD DATA INFILE was created to handle these large datasets and will significantly reduce the time it takes to handle the import process. Of note, this can be executed through PHPMyAdmin, but you may still have file upload issues. In that case you can upload the files manually to your server and then execute from PHPMyAdmin (see their manual for more info) or execute the command via your SSH console (assuming you have your own server)

    LOAD DATA INFILE '/mylargefile.csv' INTO TABLE temp_data FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n'
    
  3. MYISAM vs InnoDB

    Large or small database it’s always good to take a little time to consider which database engine you are going to use for your project. The two main engines you are going to read about are MYISAM and InnoDB and each has their own benefits and drawbacks. In brief the things to consider (in general) are as follows:

    MYISAM

    • Lower Memory Usage
    • Allows for Full-Text Searching
    • Table Level Locking – Locks Entire Table on Write
    • Great for Read-Intensive Applications

    InnoDB

    • List item
    • Uses More Memory
    • No Full-Text Search Support
    • Faster Performance
    • Row Level Locking – Locks Single Row on Write
    • Great for Read/Write Intensive Applications
  4. Plan Your Design Carefully

    MySQL AnalyzeYour databases design/structure is going to be a large factor in how it performs. Take your time when it comes to planning out the different fields and analyze the data to figure out what the best field types, defaults and field length. You want to accommodate for the right amounts of data and try to avoid varchar columns and overly large data types when the data doesn’t warrant it. As an additional step after you are done with your database, you make want to see what MySQL suggests as field types for all of your different fields. You can do this by executing the following SQL command:

    ANALYZE TABLE my_big_table
    

    The result will be a description of each columns information along with a recommendation for what type of datatype it should be along with a proper length. Now you don’t necessarily need to follow the recommendations as they are based solely on existing data, but it may help put you on the right track and get you thinking

  5. To Index or Not to Index

    For a dataset as large as this it’s infinitely important to create proper indexes on your data based off of what you need to do with the data on the front-end, BUT if you plan to manipulate the data beforehand refrain from placing too many indexes on the data. Not only will it will make your SQL table larger, but it will also slow down certain operations like column additions, subtractions and additional indexing. With our dataset we needed to take the information we just imported and break it into several different tables to create a relational structure as well as take certain columns and split the information into additional columns. We placed an index on the bare minimum of columns that we knew would help us with the manipulation. All in all, we took 1 large table consisting of 20 million rows of data and split its information into 6 different tables with pieces of the main data in them along with newly created data based off the existing content. We did all of this by writing small PHP scripts to parse and move the data around.

  6. Finding a Balance

    A big part of working with large databases from a programming perspective is speed and efficiency. Getting all of the data into your database is great, but if the script you write to access the data is slow, what’s the point? When working with large datasets it’s extremely important that you take the time to understand all of the queries that your script is performing and to create indexes to help those queries where possible. One such way to analyze what your queries are doing is by executing the following SQL command:

    EXPLAIN SELECT some_field FROM my_big_table WHERE another_field='MyCustomField';
    

    By adding EXPLAIN to the start of your query MySQL will spit out information describing what indexes it tried to use, did use and how it used them. I labeled this point ‘Finding a balance’ because although indexes can help your script perform faster, they can just as easily make it run slower. You need to make sure you index what is needed and only what is needed. Every index consumes disk space and adds to the overhead of the table. Every time you make an edit to your table, you have to rebuild the index for that particular row and the more indexes you have on those rows, the longer it will take. It all comes down to making smart indexes, efficient SQL queries and most importantly benchmarking as you go to understand what each of your queries is doing and how long it’s taking to do it.

  7. Index On, Index Off

    As we worked on the database and front-end script, both the client and us started to notice little things that needed changing and that required us to make changes to the database. Some of these changes involved adding/removing columns and changing the column types. As we had already setup a number of indexes on the data, making any of these changes required the server to do some serious work to keep the indexes in place and handle any modifications. On our small VPS server, some of the changes were taking upwards of 6 hours to complete…certainly not helpful to us being able to do speedy development. The solution? Turn off indexes! Sometimes it’s better to turn the indexes off, make your changes and then turn the indexes back on….especially if you have a lot of different changes to make. With the indexes off, the changes took a matter of seconds to minutes versus hours. When we were happy with our changes we simply turned our indexes back on. This of course took quite some time to re-index everything, but it was at least able to re-index everything all at once, reducing the overall time needed to make these changes one by one. Here’s how to do it:

    • Disable Indexes: ALTER TABLE my_big_table DISABLE KEY
    • Enable Indexes: ALTER TABLE my_big_table ENABLE KEY
  8. Give MySQL a Tune-Up

    Don’t neglect your server when it comes to making your database and script run quickly. Your hardware needs just as much attention and tuning as your database and script does. In particular it’s important to look at your MySQL configuration file to see what changes you can make to better enhance its performance. A great little tool that we’ve come across is the MySQL Tuner http://mysqltuner.com/ . It’s a quick little Perl script that you can download right to your server and run via SSH to see what changes you might want to make to your configuration. Note that you should actively use your front-end script and database for several days before running the tuner so that the tuner has data to analyze. Running it on a fresh server will only provide minimal information and tuning options. We found it great to use the tuner script every few days for the two weeks to see what recommendations it would come up with and at the end we had significantly increased the databases performance.

  9. Don’t be Afraid to Ask

    Working with SQL can be challenging to begin with and working with extremely large datasets only makes it that much harder. Don’t be afraid to go to professionals who know what they are doing when it comes to large datasets. Ultimately you will end up with a superior product, quicker development and quicker front-end performance. When it comes to large databases sometimes it’s take a professionals experienced eyes to find all the little caveats that could be slowing your databases performance.

Gradle Build Android Project "Could not resolve all dependencies" error

I had this message in Android Studio 2.1.1 in the Gradle Build tab. I installed a lot of files from the SDK Manager but it did not help.

I needed to click the next tab "Gradle Sync". There was a link "Install Repository and sync project" which installed the "Android Support Repository".

How to control size of list-style-type disc in CSS?

I'm surprised that no one has mentioned the list-style-image property

ul {
    list-style-image: url('images/ico-list-bullet.png');
}

Making a WinForms TextBox behave like your browser's address bar

I created a new VB.Net Wpf project. I created one TextBox and used the following for the codebehind:

Class MainWindow 

    Sub New()

        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        AddHandler PreviewMouseLeftButtonDown, New MouseButtonEventHandler(AddressOf SelectivelyIgnoreMouseButton)
        AddHandler GotKeyboardFocus, New KeyboardFocusChangedEventHandler(AddressOf SelectAllText)
        AddHandler MouseDoubleClick, New MouseButtonEventHandler(AddressOf SelectAllText)
    End Sub

    Private Shared Sub SelectivelyIgnoreMouseButton(ByVal sender As Object, ByVal e As MouseButtonEventArgs)
        ' Find the TextBox
        Dim parent As DependencyObject = TryCast(e.OriginalSource, UIElement)
        While parent IsNot Nothing AndAlso Not (TypeOf parent Is TextBox)
            parent = VisualTreeHelper.GetParent(parent)
        End While

        If parent IsNot Nothing Then
            Dim textBox As Object = DirectCast(parent, TextBox)
            If Not textBox.IsKeyboardFocusWithin Then
                ' If the text box is not yet focussed, give it the focus and
                ' stop further processing of this click event.
                textBox.Focus()
                e.Handled = True
            End If
        End If
    End Sub

    Private Shared Sub SelectAllText(ByVal sender As Object, ByVal e As RoutedEventArgs)
        Dim textBox As Object = TryCast(e.OriginalSource, TextBox)
        If textBox IsNot Nothing Then
            textBox.SelectAll()
        End If
    End Sub

End Class

What is the minimum I have to do to create an RPM file?

Similarly, I needed to create an rpm with just a few files. Since these files were source controlled, and because it seemed silly, I didn't want to go through taring them up just to have rpm untar them. I came up with the following:

  1. Set up your environment:

    mkdir -p ~/rpm/{BUILD,RPMS}

    echo '%_topdir %(echo "$HOME")/rpm' > ~/.rpmmacros

  2. Create your spec file, foobar.spec, with the following contents:

    Summary: Foo to the Bar
    Name: foobar
    Version: 0.1
    Release: 1
    Group: Foo/Bar
    License: FooBarPL
    Source: %{expand:%%(pwd)}
    BuildRoot: %{_topdir}/BUILD/%{name}-%{version}-%{release}
    
    %description
    %{summary}
    
    %prep
    rm -rf $RPM_BUILD_ROOT
    mkdir -p $RPM_BUILD_ROOT/usr/bin
    mkdir -p $RPM_BUILD_ROOT/etc
    cd $RPM_BUILD_ROOT
    cp %{SOURCEURL0}/foobar ./usr/bin/
    cp %{SOURCEURL0}/foobar.conf ./etc/
    
    %clean
    rm -r -f "$RPM_BUILD_ROOT"
    
    %files
    %defattr(644,root,root)
    %config(noreplace) %{_sysconfdir}/foobar.conf
    %defattr(755,root,root)
    %{_bindir}/foobar
    
  3. Build your rpm: rpmbuild -bb foobar.spec

There's a little hackery there specifying the 'source' as your current directory, but it seemed far more elegant then the alternative, which was to, in my case, write a separate script to create a tarball, etc, etc.

Note: In my particular situation, my files were arranged in folders according to where they needed to go, like this:

./etc/foobar.conf
./usr/bin/foobar

and so the prep section became:

%prep
rm -rf $RPM_BUILD_ROOT
mkdir -p $RPM_BUILD_ROOT
cd $RPM_BUILD_ROOT
tar -cC %{SOURCEURL0} --exclude 'foobar.spec' -f - ./ | tar xf -

Which is a little cleaner.

Also, I happen to be on a RHEL5.6 with rpm versions 4.4.2.3, so your mileage may vary.

Redirect with CodeIgniter

redirect()

URL Helper


The redirect statement in code igniter sends the user to the specified web page using a redirect header statement.

This statement resides in the URL helper which is loaded in the following way:

$this->load->helper('url');

The redirect function loads a local URI specified in the first parameter of the function call and built using the options specified in your config file.

The second parameter allows the developer to use different HTTP commands to perform the redirect "location" or "refresh".

According to the Code Igniter documentation: "Location is faster, but on Windows servers it can sometimes be a problem."

Example:

if ($user_logged_in === FALSE)
{
     redirect('/account/login', 'refresh');
}

Can I dynamically add HTML within a div tag from C# on load event?

You want to put code in the master page code behind that inserts HTML into the contents of a page that is using that master page?

I would not search for the control via FindControl as this is a fragile solution that could easily be broken if the name of the control changed.

Your best bet is to declare an event in the master page that any child page could handle. The event could pass the HTML as an EventArg.

How to merge two json string in Python?

As of Python 3.5, you can merge two dicts with:

merged = {**dictA, **dictB}

(https://www.python.org/dev/peps/pep-0448/)

So:

jsonMerged = {**json.loads(jsonStringA), **json.loads(jsonStringB)}
asString = json.dumps(jsonMerged)

etc.

Android: How to detect double-tap?

Improvised dhruvi code

public abstract class DoubleClickListener implements View.OnClickListener {

private static final long DOUBLE_CLICK_TIME_DELTA = 300;//milliseconds

long lastClickTime = 0;
boolean tap = true;

@Override
public void onClick(View v) {
    long clickTime = System.currentTimeMillis();
    if (clickTime - lastClickTime < DOUBLE_CLICK_TIME_DELTA){
        onDoubleClick(v);
        tap = false;
    } else
        tap = true;

    v.postDelayed(new Runnable() {
        @Override
        public void run() {
            if(tap)
                onSingleClick();
        }
    },DOUBLE_CLICK_TIME_DELTA);

    lastClickTime = clickTime;
}

public abstract void onDoubleClick(View v);

public abstract void onSingleClick();
}

Can I use an HTML input type "date" to collect only a year?

You can do the following:

  1. Generate an Array of the years I'll be accepting,
  2. Use a select box.
  3. Use each item from your Array as an 'option' tag.

Example using PHP (you can do this in any language of your choice):

Server:

<?php $years = range(1900, strftime("%Y", time())); ?>

HTML

<select>
  <option>Select Year</option>
  <?php foreach($years as $year) : ?>
    <option value="<?php echo $year; ?>"><?php echo $year; ?></option>
  <?php endforeach; ?>
</select>

As an added benefit, this works has a browser compatibility of a 100% ;-)

How do you make an anchor link non-clickable or disabled?

Add a css class:

.disable_a_href{
    pointer-events: none;
}

Add this jquery:

$("#ThisLink").addClass("disable_a_href"); 

VBA to copy a file from one directory to another

This method is even easier if you're ok with fewer options:

FileCopy source, destination

Is it possible to declare two variables of different types in a for loop?

Also you could use like below in C++.

int j=3;
int i=2;
for (; i<n && j<n ; j=j+2, i=i+2){
  // your code
}

Get the last item in an array

Getting the last item of an array can be achieved by using the slice method with negative values.

You can read more about it here at the bottom.

var fileName = loc_array.slice(-1)[0];
if(fileName.toLowerCase() == "index.html")
{
  //your code...
}

Using pop() will change your array, which is not always a good idea.

mySQL :: insert into table, data from another table?

Answered by zerkms is the correct method. But, if someone looking to insert more extra column in the table then you can get it from the following:

INSERT INTO action_2_members (`campaign_id`, `mobile`, `email`, `vote`, `vote_date`, `current_time`)
SELECT `campaign_id`, `from_number`, '[email protected]', `received_msg`, `date_received`, 1502309889 FROM `received_txts` WHERE `campaign_id` = '8'

In the above query, there are 2 extra columns named email & current_time.

How to link html pages in same or different folders?

Answer below is what I created to link html contents from another shared drive to the html page I would send out to managers. Of course, the path is relative to your using, but in my case, I would just send them the html, and everything else that is updated from load runner dynamically would be updated for me. Saves tons of paper, and they can play with the numbers as they see fit instead of just a hard copy this way.

SRC="file://///shareddrive/shareddrive-folder/username/scripting/testReport\contents.html" NAME="contents_frame" title="Table of Contents"

Proper Linq where clauses

The second one would be more efficient as it just has one predicate to evaluate against each item in the collection where as in the first one, it's applying the first predicate to all items first and the result (which is narrowed down at this point) is used for the second predicate and so on. The results get narrowed down every pass but still it involves multiple passes.

Also the chaining (first method) will work only if you are ANDing your predicates. Something like this x.Age == 10 || x.Fat == true will not work with your first method.

Calling method using JavaScript prototype

Another way with ES5 is to explicitely traverse the prototype chain using Object.getPrototypeOf(this)

const speaker = {
  speak: () => console.log('the speaker has spoken')
}

const announcingSpeaker = Object.create(speaker, {
  speak: {
    value: function() {
      console.log('Attention please!')
      Object.getPrototypeOf(this).speak()
    }
  }
})

announcingSpeaker.speak()

Passing Arrays to Function in C++

The question has already been answered, but I thought I'd add an answer with more precise terminology and references to the C++ standard.

Two things are going on here, array parameters being adjusted to pointer parameters, and array arguments being converted to pointer arguments. These are two quite different mechanisms, the first is an adjustment to the actual type of the parameter, whereas the other is a standard conversion which introduces a temporary pointer to the first element.

Adjustments to your function declaration:

dcl.fct#5:

After determining the type of each parameter, any parameter of type “array of T” (...) is adjusted to be “pointer to T”.

So int arg[] is adjusted to be int* arg.

Conversion of your function argument:

conv.array#1

An lvalue or rvalue of type “array of N T” or “array of unknown bound of T” can be converted to a prvalue of type “pointer to T”. The temporary materialization conversion is applied. The result is a pointer to the first element of the array.

So in printarray(firstarray, 3);, the lvalue firstarray of type "array of 3 int" is converted to a prvalue (temporary) of type "pointer to int", pointing to the first element.

Float a DIV on top of another DIV

I know this post is little bit old but here is a potential solution for anyone who has the same problem:

First, I would change the CSS display for #popup to "none" instead of "hidden".

Second, I would change the HTML as follow:

<div id="overlay-back"></div>
<div id="popup">
    <div style="position: relative;">
        <img class="close-image" src="images/closebtn.png" />
        <span><img src="images/load_sign.png" width="400" height="566" /></span>
    </div>            
</div>

And for Style as follow:

.close-image
{
   display: block;
   float: right;
   cursor: pointer;
   z-index: 3;
   position: absolute;
   right: 0;
   top: 0;
}

I got this idea from this website (kessitek.com). A very good example on how to position elements,:

How to position a div on top of another div

I hope this helps,

Zag,

Copy/duplicate database without using mysqldump

Mysqldump isn't bad solution. Simplest way to duplicate database:

mysqldump -uusername -ppass dbname1 | mysql -uusername -ppass dbname2

Also, you can change storage engine by this way:

mysqldump -uusername -ppass dbname1 | sed 's/InnoDB/RocksDB/' | mysql -uusername -ppass dbname2

Calculate number of hours between 2 dates in PHP

In addition to @fyrye's very helpful answer this is an okayish workaround for the mentioned bug (this one), that DatePeriod substracts one hour when entering summertime, but doesn't add one hour when leaving summertime (and thus Europe/Berlin's March has its correct 743 hours but October has 744 instead of 745 hours):

Counting the hours of a month (or any timespan), considering DST-transitions in both directions

function getMonthHours(string $year, string $month, \DateTimeZone $timezone): int
{
    // or whatever start and end \DateTimeInterface objects you like
    $start = new \DateTimeImmutable($year . '-' . $month . '-01 00:00:00', $timezone);
    $end = new \DateTimeImmutable((new \DateTimeImmutable($year . '-' . $month . '-01 23:59:59', $timezone))->format('Y-m-t H:i:s'), $timezone);
    
    // count the hours just utilizing \DatePeriod, \DateInterval and iterator_count, hell yeah!
    $hours = iterator_count(new \DatePeriod($start, new \DateInterval('PT1H'), $end));
    
    // find transitions and check, if there is one that leads to a positive offset
    // that isn't added by \DatePeriod
    // this is the workaround for https://bugs.php.net/bug.php?id=75685
    $transitions = $timezone->getTransitions((int)$start->format('U'), (int)$end->format('U'));
    if (2 === count($transitions) && $transitions[0]['offset'] - $transitions[1]['offset'] > 0) {
        $hours += (round(($transitions[0]['offset'] - $transitions[1]['offset'])/3600));
    }
    
    return $hours;
}

$myTimezoneWithDST = new \DateTimeZone('Europe/Berlin');
var_dump(getMonthHours('2020', '01', $myTimezoneWithDST)); // 744
var_dump(getMonthHours('2020', '03', $myTimezoneWithDST)); // 743
var_dump(getMonthHours('2020', '10', $myTimezoneWithDST)); // 745, finally!

$myTimezoneWithoutDST = new \DateTimeZone('UTC');
var_dump(getMonthHours('2020', '01', $myTimezoneWithoutDST)); // 744
var_dump(getMonthHours('2020', '03', $myTimezoneWithoutDST)); // 744
var_dump(getMonthHours('2020', '10', $myTimezoneWithoutDST)); // 744

P.S. If you check a (longer) timespan, which leads to more than those two transitions, my workaround won't touch the counted hours to reduce the potential of funny side effects. In such cases, a more complicated solution must be implemented. One could iterate over all found transitions and compare the current with the last and check if it is one with DST true->false.

Twitter bootstrap remote modal shows same content every time

Tested on Bootstrap version 3.3.2

  $('#myModal').on('hide.bs.modal', function() {
    $(this).removeData();
  });

Nginx - Customizing 404 page

These answers are no longer recommended since try_files works faster than if in this context. Simply add try_files in your php location block to test if the file exists, otherwise return a 404.

location ~ \.php {
    try_files $uri =404;
    ...
}

How to correctly get image from 'Resources' folder in NetBeans

For me it worked like I had images in icons folder under src and I wrote below code.

new ImageIcon(getClass().getResource("/icons/rsz_measurment_01.png"));

Hibernate error - QuerySyntaxException: users is not mapped [from users]

If you are using xml configuration, you'll need something like the following in an applicationContext.xml file:

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean" lazy-init="default" autowire="default" dependency-check="default">
<property name="dataSource">
  <ref bean="dataSource" />
</property>
<property name="annotatedClasses">
  <list>
    <value>org.browsexml.timesheetjob.model.PositionCode</value>
  </list>

Declaring an HTMLElement Typescript

In JavaScript you declare variables or functions by using the keywords var, let or function. In TypeScript classes you declare class members or methods without these keywords followed by a colon and the type or interface of that class member.

It’s just syntax sugar, there is no difference between:

var el: HTMLElement = document.getElementById('content');

and:

var el = document.getElementById('content');

On the other hand, because you specify the type you get all the information of your HTMLElement object.

Centos/Linux setting logrotate to maximum file size for all logs

It specifies the size of the log file to trigger rotation. For example size 50M will trigger a log rotation once the file is 50MB or greater in size. You can use the suffix M for megabytes, k for kilobytes, and G for gigabytes. If no suffix is used, it will take it to mean bytes. You can check the example at the end. There are three directives available size, maxsize, and minsize. According to manpage:

minsize size
              Log  files  are  rotated when they grow bigger than size bytes,
              but not before the additionally specified time interval (daily,
              weekly,  monthly, or yearly).  The related size option is simi-
              lar except that it is mutually exclusive with the time interval
              options,  and  it causes log files to be rotated without regard
              for the last rotation time.  When minsize  is  used,  both  the
              size and timestamp of a log file are considered.

size size
              Log files are rotated only if they grow bigger then size bytes.
              If size is followed by k, the size is assumed to  be  in  kilo-
              bytes.  If the M is used, the size is in megabytes, and if G is
              used, the size is in gigabytes. So size 100,  size  100k,  size
              100M and size 100G are all valid.
maxsize size
              Log files are rotated when they grow bigger than size bytes even before
              the additionally specified time interval (daily, weekly, monthly, 
              or yearly).  The related size option is  similar  except  that  it 
              is mutually exclusive with the time interval options, and it causes
              log files to be rotated without regard for the last rotation time.  
              When maxsize is used, both the size and timestamp of a log file are                  
              considered.

Here is an example:

"/var/log/httpd/access.log" /var/log/httpd/error.log {
           rotate 5
           mail [email protected]
           size 100k
           sharedscripts
           postrotate
               /usr/bin/killall -HUP httpd
           endscript
       }

Here is an explanation for both files /var/log/httpd/access.log and /var/log/httpd/error.log. They are rotated whenever it grows over 100k in size, and the old logs files are mailed (uncompressed) to [email protected] after going through 5 rotations, rather than being removed. The sharedscripts means that the postrotate script will only be run once (after the old logs have been compressed), not once for each log which is rotated. Note that the double quotes around the first filename at the beginning of this section allows logrotate to rotate logs with spaces in the name. Normal shell quoting rules apply, with ,, and \ characters supported.

Edit In Place Content Editing

Since this is a common piece of functionality it's a good idea to write a directive for this. In fact, someone already did that and open sourced it. I used editablespan library in one of my projects and it worked perfectly, highly recommended.

Can I call an overloaded constructor from another constructor of the same class in C#?

In C# it is not possible to call another constructor from inside the method body. You can call a base constructor this way: foo(args):base() as pointed out yourself. You can also call another constructor in the same class: foo(args):this().

When you want to do something before calling a base constructor, it seems the construction of the base is class is dependant of some external things. If so, you should through arguments of the base constructor, not by setting properties of the base class or something like that

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

As defer attribute works only with scripts tag with src. Found a way to mimic defer for inline scripts. Use DOMContentLoaded event.

<script defer src="external-script.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
    // Your inline scripts which uses methods from external-scripts.
});
</script>

This is because, DOMContentLoaded event fires after defer attributed scripts are completely loaded.

Lookup City and State by Zip Google Geocode Api

I found a couple of ways to do this with web based APIs. I think the US Postal Service would be the most accurate, since Zip codes are their thing, but Ziptastic looks much easier.

Using the US Postal Service HTTP/XML API

According to this page on the US Postal Service website which documents their XML based web API, specifically Section 4.0 (page 22) of this PDF document, they have a URL where you can send an XML request containing a 5 digit Zip Code and they will respond with an XML document containing the corresponding City and State.

According to their documentation, here's what you would send:

http://SERVERNAME/ShippingAPITest.dll?API=CityStateLookup&XML=<CityStateLookupRequest%20USERID="xxxxxxx"><ZipCode ID= "0"><Zip5>90210</Zip5></ZipCode></CityStateLookupRequest>

And here's what you would receive back:

<?xml version="1.0"?> 
<CityStateLookupResponse> 
    <ZipCode ID="0"> 
        <Zip5>90210</Zip5> 
        <City>BEVERLY HILLS</City> 
        <State>CA</State> 
    </ZipCode> 
</CityStateLookupResponse>

USPS does require that you register with them before you can use the API, but, as far as I could tell, there is no charge for access. By the way, their API has some other features: you can do Address Standardization and Zip Code Lookup, as well as the whole suite of tracking, shipping, labels, etc.

Using the Ziptastic HTTP/JSON API (no longer supported)

Update: As of August 13, 2017, Ziptastic is now a paid API and can be found here

This is a pretty new service, but according to their documentation, it looks like all you need to do is send a GET request to http://ziptasticapi.com, like so:

GET http://ziptasticapi.com/48867

And they will return a JSON object along the lines of:

{"country": "US", "state": "MI", "city": "OWOSSO"}

Indeed, it works. You can test this from a command line by doing something like:

curl http://ziptasticapi.com/48867 

Linux bash: Multiple variable assignment

First thing that comes into my mind:

read -r a b c <<<$(echo 1 2 3) ; echo "$a|$b|$c"

output is, unsurprisingly

1|2|3

C#: calling a button event handler method without actually clicking the button

Inside first button event call second button(imagebutton) event:

imagebutton_Click((ImageButton)this.divXXX.FindControl("imagbutton"), EventArgs.Empty);

you can use the button state such as the imagebutton's commandArgument if you save something into it.

How to do an Integer.parseInt() for a decimal number?

One more solution is possible.

int number = Integer.parseInt(new DecimalFormat("#").format(decimalNumber))  

Example:

Integer.parseInt(new DecimalFormat("#").format(Double.parseDouble("010.021")))  

Output

10

Having a UITextField in a UITableViewCell

For next/return events on multiple UITextfield inside UITableViewCell in this method I had taken UITextField in storyboard.

@interface MyViewController () {
    NSInteger currentTxtRow;
}
@end
@property (strong, nonatomic) NSIndexPath   *currentIndex;//Current Selected Row

@implementation MyViewController


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CELL" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        UITextField *txtDetails = (UITextField *)[cell.contentView viewWithTag:100];
        txtDetails.delegate = self;

        txtDetails.placeholder = self.arrReciversDetails[indexPath.row];
        return cell;
}


#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {

    CGPoint point = [textField convertPoint:CGPointZero toView:self.tableView];
    self.currentIndex = [self.tableView indexPathForRowAtPoint:point];//Get Current UITableView row
    currentTxtRow = self.currentIndex.row;
    return YES;
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    currentTxtRow += 1;
    self.currentIndex = [NSIndexPath indexPathForRow:currentTxtRow inSection:0];

    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:self.currentIndex];
    UITextField *currentTxtfield = (UITextField *)[cell.contentView viewWithTag:100];
    if (currentTxtRow < 3) {//Currently I have 3 Cells each cell have 1 UITextfield
        [currentTxtfield becomeFirstResponder];
    } else {
        [self.view endEditing:YES];
        [currentTxtfield resignFirstResponder];
    }

}  

To grab the text from textfield-

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
      switch (self.currentIndex.row) {

            case 0:
                NSLog(@"%@",[NSString stringWithFormat:@"%@%@",textField.text,string]);//Take current word and previous text from textfield
                break;

            case 1:
                 NSLog(@"%@",[NSString stringWithFormat:@"%@%@",textField.text,string]);//Take current word and previous text from textfield
                break;

            case 2:
                 NSLog(@"%@",[NSString stringWithFormat:@"%@%@",textField.text,string]);//Take current word and previous text from textfield
                break;

            default:
                break;
        }
}

possible EventEmitter memory leak detected

I am getting this warning too when install aglio on my mac osx.

I use cmd fix it.

sudo npm install -g npm@next

https://github.com/npm/npm/issues/13806

Exit while loop by user hitting ENTER key

user_input=input("ENTER SOME POSITIVE INTEGER : ")
if((not user_input) or (int(user_input)<=0)):    
   print("ENTER SOME POSITIVE INTEGER GREATER THAN ZERO") #print some info
   import sys        #import
   sys.exit(0)       #exit program 
'''
#(not user_input) checks if user has pressed enter key without entering  
# number.
#(int(user_input)<=0) checks if user has entered any number less than or 
#equal to zero.
'''

Install opencv for Python 3.3

For Ubuntu - pip3 install opencv-python sudo apt-get install python3-opencv

Nth max salary in Oracle

These queries will also work:

Workaround 1)

SELECT ename, sal 
FROM Emp e1 WHERE n-1 = (SELECT COUNT(DISTINCT sal) 
                         FROM Emp e2 WHERE e2.sal > e1.sal)

Workaround 2) using row_num function.

SELECT * 
FROM ( 
   SELECT e.*, ROW_NUMBER() OVER (ORDER BY sal DESC) rn FROM Emp e 
) WHERE rn = n;

Workaround 3 ) using rownum pseudocolumn

Select MAX(SAL) 
from (
   Select * 
   from (
      Select * 
      from EMP 
      order by SAL Desc
   ) where rownum <= n
)

How to set upload_max_filesize in .htaccess?

If you are getting 500 - Internal server error that means you don't have permission to set these values by .htaccess. You have to contact your web server providers and ask to set AllowOverride Options for your host or to put these lines in their virtual host configuration file.

How to resolve cURL Error (7): couldn't connect to host?

you can also get this if you are trying to hit the same URL with multiple HTTP request at the same time.Many curl requests wont be able to connect and so return with error

How to normalize a histogram in MATLAB?

The area of abcd`s PDF is not one, which is impossible like pointed out in many comments. Assumptions done in many answers here

  1. Assume constant distance between consecutive edges.
  2. Probability under pdf should be 1. The normalization should be done as Normalization with probability, not as Normalization with pdf, in histogram() and hist().

Fig. 1 Output of hist() approach, Fig. 2 Output of histogram() approach

enter image description here enter image description here

The max amplitude differs between two approaches which proposes that there are some mistake in hist()'s approach because histogram()'s approach uses the standard normalization. I assume the mistake with hist()'s approach here is about the normalization as partially pdf, not completely as probability.

Code with hist() [deprecated]

Some remarks

  1. First check: sum(f)/N gives 1 if Nbins manually set.
  2. pdf requires the width of the bin (dx) in the graph g

Code

%http://stackoverflow.com/a/5321546/54964
N=10000;
Nbins=50;
[f,x]=hist(randn(N,1),Nbins); % create histogram from ND

%METHOD 4: Count Densities, not Sums!
figure(3)
dx=diff(x(1:2)); % width of bin
g=1/sqrt(2*pi)*exp(-0.5*x.^2) .* dx; % pdf of ND with dx
% 1.0000
bar(x, f/sum(f));hold on
plot(x,g,'r');hold off

Output is in Fig. 1.

Code with histogram()

Some remarks

  1. First check: a) sum(f) is 1 if Nbins adjusted with histogram()'s Normalization as probability, b) sum(f)/N is 1 if Nbins is manually set without normalization.
  2. pdf requires the width of the bin (dx) in the graph g

Code

%%METHOD 5: with histogram()
% http://stackoverflow.com/a/38809232/54964
N=10000;

figure(4);
h = histogram(randn(N,1), 'Normalization', 'probability') % hist() deprecated!
Nbins=h.NumBins;
edges=h.BinEdges; 
x=zeros(1,Nbins);
f=h.Values;
for counter=1:Nbins
    midPointShift=abs(edges(counter)-edges(counter+1))/2; % same constant for all
    x(counter)=edges(counter)+midPointShift;
end
dx=diff(x(1:2)); % constast for all
g=1/sqrt(2*pi)*exp(-0.5*x.^2) .* dx; % pdf of ND
% Use if Nbins manually set
%new_area=sum(f)/N % diff of consecutive edges constant
% Use if histogarm() Normalization probability
new_area=sum(f)
% 1.0000
% No bar() needed here with histogram() Normalization probability
hold on;
plot(x,g,'r');hold off

Output in Fig. 2 and expected output is met: area 1.0000.

Matlab: 2016a
System: Linux Ubuntu 16.04 64 bit
Linux kernel 4.6

How to overwrite styling in Twitter Bootstrap

You can just make sure your css file parses AFTER boostrap.css , like so:

<link href="css/bootstrap.css" rel="stylesheet">
<link href="css/myFile.css" rel="stylesheet">

psql: FATAL: Peer authentication failed for user "dev"

When you specify:

psql -U user

it connects via UNIX Socket, which by default uses peer authentication, unless specified in pg_hba.conf otherwise.

You can specify:

host    database             user             127.0.0.1/32       md5
host    database             user             ::1/128            md5

to get TCP/IP connection on loopback interface (both IPv4 and IPv6) for specified database and user.

After changes you have to restart postgres or reload it's configuration. Restart that should work in modern RHEL/Debian based distros:

service postgresql restart

Reload should work in following way:

pg_ctl reload

but the command may differ depending of PATH configuration - you may have to specify absolute path, which may be different, depending on way the postgres was installed.

Then you can use:

psql -h localhost -U user -d database

to login with that user to specified database over TCP/IP. md5 stands for encrypted password, while you can also specify password for plain text passwords during authorisation. These 2 options shouldn't be of a great matter as long as database server is only locally accessible, with no network access.

Important note: Definition order in pg_hba.conf matters - rules are read from top to bottom, like iptables, so you probably want to add proposed rules above the rule:

host    all             all             127.0.0.1/32            ident

How to get the size of a string in Python?

Python 3:

user225312's answer is correct:

A. To count number of characters in str object, you can use len() function:

>>> print(len('please anwser my question'))
25

B. To get memory size in bytes allocated to store str object, you can use sys.getsizeof() function

>>> from sys import getsizeof
>>> print(getsizeof('please anwser my question'))
50

Python 2:

It gets complicated for Python 2.

A. The len() function in Python 2 returns count of bytes allocated to store encoded characters in a str object.

Sometimes it will be equal to character count:

>>> print(len('abc'))
3

But sometimes, it won't:

>>> print(len('???'))  # String contains Cyrillic symbols
6

That's because str can use variable-length encoding internally. So, to count characters in str you should know which encoding your str object is using. Then you can convert it to unicode object and get character count:

>>> print(len('???'.decode('utf8'))) #String contains Cyrillic symbols 
3

B. The sys.getsizeof() function does the same thing as in Python 3 - it returns count of bytes allocated to store the whole string object

>>> print(getsizeof('???'))
27
>>> print(getsizeof('???'.decode('utf8')))
32

Get current location of user in Android without using GPS or internet

By getting the getLastKnownLocation you do not actually initiate a fix yourself.

Be aware that this could start the provider, but if the user has ever gotten a location before, I don't think it will. The docs aren't really too clear on this.

According to the docs getLastKnownLocation:

Returns a Location indicating the data from the last known location fix obtained from the given provider. This can be done without starting the provider.

Here is a quick snippet:

import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import java.util.List;

public class UtilLocation {
    public static Location getLastKnownLoaction(boolean enabledProvidersOnly, Context context){
        LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        Location utilLocation = null;
        List<String> providers = manager.getProviders(enabledProvidersOnly);
        for(String provider : providers){

            utilLocation = manager.getLastKnownLocation(provider);
            if(utilLocation != null) return utilLocation;
        }
        return null;
    }
}

You also have to add new permission to AndroidManifest.xml

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

Comparing two branches in Git?

git diff branch_1..branch_2

That will produce the diff between the tips of the two branches. If you'd prefer to find the diff from their common ancestor to test, you can use three dots instead of two:

git diff branch_1...branch_2

Babel command not found

Worked for me e.g.

./node_modules/.bin/babel --version
./node_modules/.bin/babel src/main.js

Case-insensitive search

I noticed that if the user enters a string of text but leaves the input without selecting any of the autocomplete options no value is set in the hidden input, even if the string coincides with one in the array. So, with help of the other answers I made this:

var $local_source = [{
        value: 1,
        label: "c++"
    }, {
        value: 2,
        label: "java"
    }, {
        value: 3,
        label: "php"
    }, {
        value: 4,
        label: "coldfusion"
    }, {
        value: 5,
        label: "javascript"
    }, {
        value: 6,
        label: "asp"
    }, {
        value: 7,
        label: "ruby"
    }];
    $('#search-fld').autocomplete({
        source: $local_source,
        select: function (event, ui) {
            $("#search-fld").val(ui.item.label); // display the selected text
            $("#search-fldID").val(ui.item.value); // save selected id to hidden input
            return false;
        },
        change: function( event, ui ) {

            var isInArray = false;

            $local_source.forEach(function(element, index){

                if ($("#search-fld").val().toUpperCase() == element.label.toUpperCase()) {
                    isInArray = true;
                    $("#search-fld").val(element.label); // display the selected text
                    $("#search-fldID").val(element.value); // save selected id to hidden input
                    console.log('inarray: '+isInArray+' label: '+element.label+' value: '+element.value);
                };

            });

            if(!isInArray){

                $("#search-fld").val(''); // display the selected text
                $( "#search-fldID" ).val( ui.item? ui.item.value : 0 );

            }
        } 

How can I reverse a list in Python?

You could always treat the list like a stack just popping the elements off the top of the stack from the back end of the list. That way you take advantage of first in last out characteristics of a stack. Of course you are consuming the 1st array. I do like this method in that it's pretty intuitive in that you see one list being consumed from the back end while the other is being built from the front end.

>>> l = [1,2,3,4,5,6]; nl=[]
>>> while l:
        nl.append(l.pop())  
>>> print nl
[6, 5, 4, 3, 2, 1]

How to split a string to 2 strings in C

char *line = strdup("user name"); // don't do char *line = "user name"; see Note

char *first_part = strtok(line, " "); //first_part points to "user"
char *sec_part = strtok(NULL, " ");   //sec_part points to "name"

Note: strtok modifies the string, so don't hand it a pointer to string literal.

mysql alphabetical order

i want to show records only starting with b

select name from user where name LIKE 'b%';

i am trying to sort MySQL data alphabeticaly

select name from user ORDER BY name;

i am trying to sort MySQL data in reverse alphabetic order

select name from user ORDER BY name desc;

How should I escape commas and speech marks in CSV files so they work in Excel?

Single quotes work fine too, even without escaping the double quotes, at least in Excel 2016:

'text with spaces, and a comma','more text with spaces','spaces and "quoted text" and more spaces','nospaces','NOSPACES1234'

Excel will put that in 5 columns (if you choose the single quote as "Text qualifier" in the "Text to columns" wizard)

Detect Browser Language in PHP

I've got this one, which sets a cookie. And as you can see, it first checks if the language is posted by the user. Because browser language not always tells about the user.

<?php   
    $lang = getenv("HTTP_ACCEPT_LANGUAGE");
    $set_lang = explode(',', $lang);
    if (isset($_POST['lang'])) 
        {
            $taal = $_POST['lang'];
            setcookie("lang", $taal);
            header('Location: /p/');
        }
    else 
        {
            setcookie("lang", $set_lang[0]);
            echo $set_lang[0];
            echo '<br>';
            echo $set_lang[1];
            header('Location: /p/');
        } 
?>

What exactly is Python's file.flush() doing?

There's typically two levels of buffering involved:

  1. Internal buffers
  2. Operating system buffers

The internal buffers are buffers created by the runtime/library/language that you're programming against and is meant to speed things up by avoiding system calls for every write. Instead, when you write to a file object, you write into its buffer, and whenever the buffer fills up, the data is written to the actual file using system calls.

However, due to the operating system buffers, this might not mean that the data is written to disk. It may just mean that the data is copied from the buffers maintained by your runtime into the buffers maintained by the operating system.

If you write something, and it ends up in the buffer (only), and the power is cut to your machine, that data is not on disk when the machine turns off.

So, in order to help with that you have the flush and fsync methods, on their respective objects.

The first, flush, will simply write out any data that lingers in a program buffer to the actual file. Typically this means that the data will be copied from the program buffer to the operating system buffer.

Specifically what this means is that if another process has that same file open for reading, it will be able to access the data you just flushed to the file. However, it does not necessarily mean it has been "permanently" stored on disk.

To do that, you need to call the os.fsync method which ensures all operating system buffers are synchronized with the storage devices they're for, in other words, that method will copy data from the operating system buffers to the disk.

Typically you don't need to bother with either method, but if you're in a scenario where paranoia about what actually ends up on disk is a good thing, you should make both calls as instructed.


Addendum in 2018.

Note that disks with cache mechanisms is now much more common than back in 2013, so now there are even more levels of caching and buffers involved. I assume these buffers will be handled by the sync/flush calls as well, but I don't really know.

How to get a user's client IP address in ASP.NET?

string IP = HttpContext.Current.Request.Params["HTTP_CLIENT_IP"] ?? HttpContext.Current.Request.UserHostAddress;

Opposite of append in jquery

The opposite of .append() is .prepend().

From the jQuery documentation for prepend…

The .prepend() method inserts the specified content as the first child of each element in the jQuery collection (To insert it as the last child, use .append()).

I realize this doesn’t answer the OP’s specific case. But it does answer the question heading. :) And it’s the first hit on Google for “jquery opposite append”.

Differences between C++ string == and compare()?

Internally, string::operator==() is using string::compare(). Please refer to: CPlusPlus - string::operator==()

I wrote a small application to compare the performance, and apparently if you compile and run your code on debug environment the string::compare() is slightly faster than string::operator==(). However if you compile and run your code in Release environment, both are pretty much the same.

FYI, I ran 1,000,000 iteration in order to come up with such conclusion.

In order to prove why in debug environment the string::compare is faster, I went to the assembly and here is the code:

DEBUG BUILD

string::operator==()

        if (str1 == str2)
00D42A34  lea         eax,[str2]  
00D42A37  push        eax  
00D42A38  lea         ecx,[str1]  
00D42A3B  push        ecx  
00D42A3C  call        std::operator==<char,std::char_traits<char>,std::allocator<char> > (0D23EECh)  
00D42A41  add         esp,8  
00D42A44  movzx       edx,al  
00D42A47  test        edx,edx  
00D42A49  je          Algorithm::PerformanceTest::stringComparison_usingEqualOperator1+0C4h (0D42A54h)  

string::compare()

            if (str1.compare(str2) == 0)
00D424D4  lea         eax,[str2]  
00D424D7  push        eax  
00D424D8  lea         ecx,[str1]  
00D424DB  call        std::basic_string<char,std::char_traits<char>,std::allocator<char> >::compare (0D23582h)  
00D424E0  test        eax,eax  
00D424E2  jne         Algorithm::PerformanceTest::stringComparison_usingCompare1+0BDh (0D424EDh)

You can see that in string::operator==(), it has to perform extra operations (add esp, 8 and movzx edx,al)

RELEASE BUILD

string::operator==()

        if (str1 == str2)
008533F0  cmp         dword ptr [ebp-14h],10h  
008533F4  lea         eax,[str2]  
008533F7  push        dword ptr [ebp-18h]  
008533FA  cmovae      eax,dword ptr [str2]  
008533FE  push        eax  
008533FF  push        dword ptr [ebp-30h]  
00853402  push        ecx  
00853403  lea         ecx,[str1]  
00853406  call        std::basic_string<char,std::char_traits<char>,std::allocator<char> >::compare (0853B80h)  

string::compare()

            if (str1.compare(str2) == 0)
    00853830  cmp         dword ptr [ebp-14h],10h  
    00853834  lea         eax,[str2]  
    00853837  push        dword ptr [ebp-18h]  
    0085383A  cmovae      eax,dword ptr [str2]  
    0085383E  push        eax  
    0085383F  push        dword ptr [ebp-30h]  
    00853842  push        ecx  
00853843  lea         ecx,[str1]  
00853846  call        std::basic_string<char,std::char_traits<char>,std::allocator<char> >::compare (0853B80h)

Both assembly code are very similar as the compiler perform optimization.

Finally, in my opinion, the performance gain is negligible, hence I would really leave it to the developer to decide on which one is the preferred one as both achieve the same outcome (especially when it is release build).

In C#, can a class inherit from another class and an interface?

I found the answer to the second part of my questions. Yes, a class can implement an interface that is in a different class as long that the interface is declared as public.

HQL "is null" And "!= null" on an Oracle column

No. You have to use is null and is not null in HQL.

How to update record using Entity Framework Core?

Microsoft Docs gives us two approaches.

Recommended HttpPost Edit code: Read and update

This is the same old way we used to do in previous versions of Entity Framework. and this is what Microsoft recommends for us.

Advantages

  • Prevents overposting
  • EFs automatic change tracking sets the Modified flag on the fields that are changed by form input.

Alternative HttpPost Edit code: Create and attach

an alternative is to attach an entity created by the model binder to the EF context and mark it as modified.

As mentioned in the other answer the read-first approach requires an extra database read, and can result in more complex code for handling concurrency conflicts.

Data truncated for column?

when i first tried to import csv into mysql , i got the same error , and then i figured out mysql table i created doesn't have the character length of the importing csv field , so if it's the first time importing csv

  1. its a good idea to give more character length .
  2. label all fields as varchar or text , don't blend int or other values.

then you are good to go.

Get File Path (ends with folder)

This might help you out:

Sub SelectFolder()
    Dim diaFolder As FileDialog
    Dim Fname As String

    Set diaFolder = Application.FileDialog(msoFileDialogFolderPicker)
    diaFolder.AllowMultiSelect = False
    diaFolder.Show

    Fname = diaFolder.SelectedItems(1)

    ActiveSheet.Range("B9") = Fname

End Sub

CSS for the "down arrow" on a <select> element?

You would need to create your own dropdown using hidden divs and a hidden input element to record which option was "selected". My guess is that @Jan Hancic's link he posted is probably what you're looking for.

C# Test if user has write access to a folder

IMHO the only 100% reliable way to test if you can write to a directory is to actually write to it and eventually catch exceptions.