Programs & Examples On #Eventvalidation

How to simulate POST request?

This should help if you need a publicly exposed website but you're on a dev pc. Also to answer (I can't comment yet): "How do I post to an internal only running development server with this? – stryba "

NGROK creates a secure public URL to a local webserver on your development machine (Permanent URLs available for a fee, temporary for free).
1) Run ngrok.exe to open command line (on desktop)
2) Type ngrok.exe http 80 to start a tunnel,
3) test by browsing to the displayed web address which will forward and display the local default 80 page on your dev pc

Then use some of the tools recommended above to POST to your ngrok site ('https://xxxxxx.ngrok.io') to test your local code.

https://ngrok.com/

error: the details of the application error from being viewed remotely

In my case I got this message because there's a special char (&) in my connectionstring, remove it then everything's good.

Cheers

asp.net: Invalid postback or callback argument

Ah its unfortunate. Since you add them essentially client side asp.net blows up. It is also unfortunate you'd have to turn off EventValidation as there are some important protections that helps (for instance evil injection into drop down boxes). The other alternative is to make your own composite control, which of course here seems a bit more than the effort involved. I'd prob turn off event validation too but be very careful that you don't trust any values from the page that could be used in a bad manner by simply changing them - like hidden keys, sql injection through combo boxes, etc.

PHP new line break in emails

EDIT: Maybe your class for sending emails has an option for HTML emails and then you can use <br />

1) Double-quotes

$output = "Good news! The item# $item_number  on which you placed a bid of \$ $bid_price is now available for purchase at your bid price.\nThe seller, $bid_user is making this offer.\n\nItem Title : $title\n\nAll the best,\n $bid_user\n$email\n";

If you use double-quotes then \n will work (there will be no newline in browser but see the source code in your browser - the \n characters will be replaced for newlines)

2) Single quotes doesn't have the effect as the double-quotes above:

$output = 'Good news! The item# $item_number  on which you placed a bid of \$ $bid_price is now available for purchase at your bid price.\nThe seller, $bid_user is making this offer.\n\nItem Title : $title\n\nAll the best,\n $bid_user\n$email\n';

all characters will be printed as is (even variables!)

3) Line breaks in HTML

$html_output = "Good news! The item# $item_number  on which you placed a bid of <br />$ $bid_price is now available for purchase at your bid price.<br />The seller, $bid_user is making this offer.<br /><br />Item Title : $title<br /><br />All the best,<br /> $bid_user<br />$email<br />";
  • There will be line breaks in your browser and variables will be replaced with their content.

Invalid postback or callback argument. Event validation is enabled using '<pages enableEventValidation="true"/>'

Ajax UpdatePanel makes it, and I think it's the easiest way, ignoring the Ajax postback overhead.

Git list of staged files

You can Try using :- git ls-files -s

What is the difference between 'java', 'javaw', and 'javaws'?

See Java tools documentation for:

  1. The java tool launches a Java application. It does this by starting a Java runtime environment, loading a specified class, and invoking that class's main method.
  2. The javaw command is identical to java, except that with javaw there is no associated console window. Use javaw when you don't want a command prompt window to appear.

The javaws command launches Java Web Start, which is the reference implementation of the Java Network Launching Protocol (JNLP). Java Web Start launches Java applications/applets hosted on a network.

If a JNLP file is specified, javaws will launch the Java application/applet specified in the JNLP file.

The javaws launcher has a set of options that are supported in the current release. However, the options may be removed in a future release.

See also JDK 9 Release Notes Deprecated APIs, Features, and Options:

Java Deployment Technologies are deprecated and will be removed in a future release
Java Applet and WebStart functionality, including the Applet API, the Java plug-in, the Java Applet Viewer, JNLP and Java Web Start, including the javaws tool, are all deprecated in JDK 9 and will be removed in a future release.

JavaScript TypeError: Cannot read property 'style' of null

For me my Script tag was outside the body element. Copied it just before closing the body tag. This worked

enter code here

<h1 id = 'title'>Black Jack</h1>
<h4> by Meg</h4>

<p id="text-area">Welcome to blackJack!</p>
<button id="new-button">New Game</button>
<button id="hitbtn">Hit!</button>
<button id="staybtn">Stay</button>

 <script src="script.js"></script>

Adding a splash screen to Flutter apps

Multiple ways you could do this, but the easiest one which I use is:

For Launch Icons I use the flutter library Flutter Launcher Icon

For the Custom Splash Screen I create different Screen resolutions and then add the splash images in the mipmap folder as per the resolution for Android.

The last part is adjusting the launch_background.xml in the drawable folder in res folder in Android.

Just change your code to look like below:

<?xml version="1.0" encoding="utf-8"?>
<!-- Modify this file to customize your launch splash screen -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- <item android:drawable="@android:color/white" />
    <item android:drawable="@drawable/<splashfilename>" />     --> -->

    <!-- You can insert your own image assets here -->
    <item>
        <bitmap
            android:gravity="center"
            android:src="@mipmap/<Your splash image name here as per the mipmap folder>"/>
    </item>
</layer-list>

Few devs I have seen add the splash as drawable, I tried this but somehow the build fails in Flutter 1.0.0 and Dart SDK 2.0+. Therefore I prefer to add the splash in bitmap section.

iOS Splash-screen creation is rather simpler.

In the Runner folder in iOS just update the LaunchImage.png files with your custom Splash screen images with same names as LaunchImage.png @2x, @3x, @4x.

Just an addition I feel its good to have a 4x image as well in the LaunchImage.imageset. Just update your code in Content.json with following lines, below 3x scale to add a 4x scale option:

{
      "idiom" : "universal",
      "filename" : "[email protected]",
      "scale" : "4x"
    }

Setting Action Bar title and subtitle

supportActionBar?.title = "Hola tio"
supportActionBar?.subtitle = "Vamos colega!"

How to list all properties of a PowerShell object

You can also use:

Get-WmiObject -Class "Win32_computersystem" | Select *

This will show the same result as Format-List * used in the other answers here.

How to create number input field in Flutter?

keyboardType: TextInputType.number would open a num pad on focus, I would clear the text field when the user enters/past anything else.

keyboardType: TextInputType.number,
onChanged: (String newVal) {
    if(!isNumber(newVal)) {
        editingController.clear();
    }
}

// Function to validate the number
bool isNumber(String value) {
    if(value == null) {
        return true;
    }
    final n = num.tryParse(value);
    return n!= null;
}

Switch case in C# - a constant value is expected

switch is very picky in the sense that the values in the switch must be a compile time constant. and also the value that's being compared must be a primitive (or string now). For this you should use an if statement.

The reason may go back to the way that C handles them in that it creates a jump table (because the values are compile time constants) and it tries to copy the same semantics by not allowing evaluated values in your cases.

Binding value to input in Angular JS

Some times there are problems with funtion/features that do not interact with the DOM

try to change the value sharply and then assign the $scope

document.getElementById ("textWidget") value = "<NewVal>";
$scope.widget.title = "<NewVal>";

Convert seconds to hh:mm:ss in Python

I can't believe any of the many answers gives what I'd consider the "one obvious way to do it" (and I'm not even Dutch...!-) -- up to just below 24 hours' worth of seconds (86399 seconds, specifically):

>>> import time
>>> time.strftime('%H:%M:%S', time.gmtime(12345))
'03:25:45'

Doing it in a Django template's more finicky, since the time filter supports a funky time-formatting syntax (inspired, I believe, from PHP), and also needs the datetime module, and a timezone implementation such as pytz, to prep the data. For example:

>>> from django import template as tt
>>> import pytz
>>> import datetime
>>> tt.Template('{{ x|time:"H:i:s" }}').render(
...     tt.Context({'x': datetime.datetime.fromtimestamp(12345, pytz.utc)}))
u'03:25:45'

Depending on your exact needs, it might be more convenient to define a custom filter for this formatting task in your app.

PHP mySQL - Insert new record into table with auto-increment on primary key

Use the DEFAULT keyword:

$query = "INSERT INTO myTable VALUES (DEFAULT,'Fname', 'Lname', 'Website')";

Also, you can specify the columns, (which is better practice):

$query = "INSERT INTO myTable
          (fname, lname, website)
          VALUES
          ('fname', 'lname', 'website')";

Reference:

How can I insert a line break into a <Text> component in React Native?

There are two options:

Option 1: Using Template Literals.

const Message = 'This is a message';

<Text>
{`
  Hi~
  ${Message}
`}
</Text>

Result:

Hi~
This is a message

Option 2: Use {'\n'} as line breaks.

<Text>

   Hello {'\n'}

   World!

</Text>

Result:

Hello
World!

how to loop through json array in jquery?

Try this:

var data = jQuery.parseJSON(response);
$.each(data, function(key, item) 
{
   console.log(item.com);
});

or

var data = $.parseJSON(response);

$(data).each(function(i,val)
 {
    $.each(val,function(key,val)
  {
          console.log(key + " : " + val);     
  });
});

How do I sort a dictionary by value?

from django.utils.datastructures import SortedDict

def sortedDictByKey(self,data):
    """Sorted dictionary order by key"""
    sortedDict = SortedDict()
    if data:
        if isinstance(data, dict):
            sortedKey = sorted(data.keys())
            for k in sortedKey:
                sortedDict[k] = data[k]
    return sortedDict

What's the difference between console.dir and console.log?

None of the 7 prior answers mentioned that console.dir supports extra arguments: depth, showHidden, and whether to use colors.

Of particular interest is depth, which (in theory) allows travering objects into more than the default 2 levels that console.log supports.

I wrote "in theory" because in practice when I had a Mongoose object and ran console.log(mongoose) and console.dir(mongoose, { depth: null }), the output was the same. What actually recursed deeply into the mongoose object was using util.inspect:

import * as util from 'util';
console.log(util.inspect(myObject, {showHidden: false, depth: null}));

How to declare 2D array in bash

You can simulate them for example with hashes, but need care about the leading zeroes and many other things. The next demonstration works, but it is far from optimal solution.

#!/bin/bash
declare -A matrix
num_rows=4
num_columns=5

for ((i=1;i<=num_rows;i++)) do
    for ((j=1;j<=num_columns;j++)) do
        matrix[$i,$j]=$RANDOM
    done
done

f1="%$((${#num_rows}+1))s"
f2=" %9s"

printf "$f1" ''
for ((i=1;i<=num_rows;i++)) do
    printf "$f2" $i
done
echo

for ((j=1;j<=num_columns;j++)) do
    printf "$f1" $j
    for ((i=1;i<=num_rows;i++)) do
        printf "$f2" ${matrix[$i,$j]}
    done
    echo
done

the above example creates a 4x5 matrix with random numbers and print it transposed, with the example result

           1         2         3         4
 1     18006     31193     16110     23297
 2     26229     19869      1140     19837
 3      8192      2181     25512      2318
 4      3269     25516     18701      7977
 5     31775     17358      4468     30345

The principle is: Creating one associative array where the index is an string like 3,4. The benefits:

  • it's possible to use for any-dimension arrays ;) like: 30,40,2 for 3 dimensional.
  • the syntax is close to "C" like arrays ${matrix[2,3]}

WPF Data Binding and Validation Rules Best Practices

You might be interested in the BookLibrary sample application of the WPF Application Framework (WAF). It shows how to use validation in WPF and how to control the Save button when validation errors exists.

React native ERROR Packager can't listen on port 8081

Take the terminal and type

fuser 8081/tcp

You will get a Process id which is using port 8081 Now kill the process

kill <pid>

PHP Warning: PHP Startup: ????????: Unable to initialize module

This is an old thread, but I stumbled across it when trying to solve a similar problem.

For me, I got this particular error relating to the php_wincache.dll. I was in the process of updating PHP from 5.5.38 to 5.6.31 on a Windows server. For some reason, not all of the DLL files updated with the newest versions. Most did, but some didn't.

So, if you get an error similar to this, make sure all the extensions are in place and updated.

Java Webservice Client (Best way)

What is the best approach to do this JAVA?

I would personally NOT use Axis 2, even for client side development only. Here is why I stay away from it:

  1. I don't like its architecture and hate its counter productive deployment model.
  2. I find it to be low quality project.
  3. I don't like its performances (see this benchmark against JAX-WS RI).
  4. It's always a nightmare to setup dependencies (I use Maven and I always have to fight with the gazillion of dependencies) (see #2)
  5. Axis sucked big time and Axis2 isn't better. No, this is not a personal opinion, there is a consensus.
  6. I suffered once, never again.

The only reason Axis is still around is IMO because it's used in Eclipse since ages. Thanks god, this has been fixed in Eclipse Helios and I hope Axis2 will finally die. There are just much better stacks.

I read about SAAJ, looks like that will be more granular level of approach?

To do what?

Is there any other way than using the WSDL2Java tool, to generate the code. Maybe wsimport in another option. What are the pros and cons?

Yes! Prefer a JAX-WS stack like CXF or JAX-WS RI (you might also read about Metro, Metro = JAX-WS RI + WSIT), they are just more elegant, simpler, easier to use. In your case, I would just use JAX-WS RI which is included in Java 6 and thus wsimport.

Can someone send the links for some good tutorials on these topics?

That's another pro, there are plenty of (good quality) tutorials for JAX-WS, see for example:

What are the options we need to use while generating the code using the WSDL2Java?

No options, use wsimport :)

See also

Related questions

How to detect chrome and safari browser (webkit)

you can use this minified jQuery snippet to detect if your user is viewing using a mobile device. If you need to test for a specific device I’ve included a collection of JavaScript snippets below which can be used to detect various mobile handheld devices such as iPad, iPhone, iPod, iDevice, Andriod, Blackberry, WebOs and Windows Phone.

/**
 * jQuery.browser.mobile (http://detectmobilebrowser.com/)
 * jQuery.browser.mobile will be true if the browser is a mobile device
 **/

    (function(a){jQuery.browser.mobile=/android.+mobile|avantgo|bada/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)/|plucker|pocket|psp|symbian|treo|up.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw-(n|u)|c55/|capi|ccwa|cdm-|cell|chtm|cldc|cmd-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc-s|devi|dica|dmob|do(c|p)o|ds(12|-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(-|_)|g1 u|g560|gene|gf-5|g-mo|go(.w|od)|gr(ad|un)|haie|hcit|hd-(m|p|t)|hei-|hi(pt|ta)|hp( i|ip)|hs-c|ht(c(-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i-(20|go|ma)|i230|iac( |-|/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |/)|klon|kpt |kwc-|kyo(c|k)|le(no|xi)|lg( g|/(k|l|u)|50|54|e-|e/|-[a-w])|libw|lynx|m1-w|m3ga|m50/|ma(te|ui|xo)|mc(01|21|ca)|m-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|-([1-8]|c))|phil|pire|pl(ay|uc)|pn-2|po(ck|rt|se)|prox|psio|pt-g|qa-a|qc(07|12|21|32|60|-[2-7]|i-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55/|sa(ge|ma|mm|ms|ny|va)|sc(01|h-|oo|p-)|sdk/|se(c(-|0|1)|47|mc|nd|ri)|sgh-|shar|sie(-|m)|sk-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h-|v-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl-|tdg-|tel(i|m)|tim-|t-mo|to(pl|sh)|ts(70|m-|m3|m5)|tx-9|up(.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(-|2|g)|yas-|your|zeto|zte-/i.test(a.substr(0,4))})(navigator.userAgent||navigator.vendor||window.opera);

Example Usage:

if(jQuery.browser.mobile)
{
console.log(‘You are using a mobile device!’);
}
else
{
console.log(‘You are not using a mobile device!’);
}

Detect iPad

var isiPad = /ipad/i.test(navigator.userAgent.toLowerCase());
if (isiPad)
{
…
}

Detect iPhone

var isiPhone = /iphone/i.test(navigator.userAgent.toLowerCase());
if (isiPhone)
{
…
}

Detect iPod

var isiPod = /ipod/i.test(navigator.userAgent.toLowerCase());
if (isiPod)
{
…
}

Detect iDevice

var isiDevice = /ipad|iphone|ipod/i.test(navigator.userAgent.toLowerCase());

if (isiDevice)
{
…
}

Detect Andriod

var isAndroid = /android/i.test(navigator.userAgent.toLowerCase());

if (isAndroid)
{
…
}

Detect Blackberry

var isBlackBerry = /blackberry/i.test(navigator.userAgent.toLowerCase());

if (isBlackBerry)
{
…
}

Detect WebOs

var isWebOS = /webos/i.test(navigator.userAgent.toLowerCase());

if (isWebOS)
{
…
}

Detect Windows Phone

var isWindowsPhone = /windows phone/i.test(navigator.userAgent.toLowerCase());

if (isWindowsPhone)
{
…
}

how can I copy a conditional formatting in Excel 2010 to other cells, which is based on a other cells content?

I had this problem too and couldn't solve it without using VBA.

In my case I had a table with numbers that I wanted to be formatted and a corresponding table next to it with the desired formatting values.

i.e. While column F contains the values I want to format, the desired formatting for each cell is captured in column Z, expressed as "RED", "AMBER" or "GREEN."

Quick solution below. Manually select the range to which to apply the conditional formatting and then run the macro.

   Sub ConditionalFormatting()
For Each Cell In Selection.Cells
With Cell
    'clean
    .FormatConditions.Delete

    'green rule
    .FormatConditions.Add Type:=xlExpression, Formula1:= _
        "=$Z" & Cell.Row & "=""GREEN"""
    .FormatConditions(.FormatConditions.Count).SetFirstPriority
    With .FormatConditions(1).Font
        .Color = -11489280
        .TintAndShade = 0
    End With
    .FormatConditions(1).StopIfTrue = False

    'amber rule
    .FormatConditions.Add Type:=xlExpression, Formula1:= _
        "=$Z" & Cell.Row & "=""AMBER"""
    .FormatConditions(.FormatConditions.Count).SetFirstPriority
    With .FormatConditions(1).Font
        .ThemeColor = xlThemeColorAccent6
        .TintAndShade = -0.249946592608417
    End With
    .FormatConditions(1).StopIfTrue = False

    'red rule
    .FormatConditions.Add Type:=xlExpression, Formula1:= _
        "=$Z" & Cell.Row & "=""RED"""
    .FormatConditions(.FormatConditions.Count).SetFirstPriority
    With .FormatConditions(1).Font
        .Color = -16776961
        .TintAndShade = 0
    End With
    .FormatConditions(1).StopIfTrue = False
End With

Next Cell

End Sub

Show ImageView programmatically

If you add to RelativeLayout, don't forget to set imageView's position. For instance:

RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(200, 200);
lp.addRule(RelativeLayout.CENTER_IN_PARENT); // A position in layout.
ImageView imageView = new ImageView(this); // initialize ImageView
imageView.setLayoutParams(lp);
// imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageView.setImageResource(R.drawable.photo);
RelativeLayout layout = (RelativeLayout) findViewById(R.id.layout);
layout.addView(imageView);

Jmeter - Run .jmx file through command line and get the summary report in a excel

Navigate to the jmeter/bin directory from command line and

jmeter -n -t <YourTestScript.jmx> -l <TestScriptsResults.jtl>

Npm Error - No matching version found for

Try removing "package-lock.json" and running "npm install && npm update", it'll install the latest version and clear all errors.

How to find prime numbers between 0 - 100?

            var n=100;
            var counter = 0;
            var primeNumbers = "Prime Numbers: ";
            for(var i=2; i<=n; ++i)
            {
                counter=0;
                for(var j=2; j<=n; ++j)
                {
                    if(i>=j && i%j == 0)
                    {
                        ++counter;
                    }

                }
                if(counter == 1)
                    {
                        primeNumbers = primeNumbers + i + "  ";
                    }

            }
            console.log(primeNumbers);

How would I get a cron job to run every 30 minutes?

crontab does not understand "intervals", it only understands "schedule"

valid hours: 0-23 -- valid minutes: 0-59

example #1

30 * * * * your_command

this means "run when the minute of each hour is 30" (would run at: 1:30, 2:30, 3:30, etc)

example #2

*/30 * * * * your_command

this means "run when the minute of each hour is evenly divisible by 30" (would run at: 1:30, 2:00, 2:30, 3:00, etc)

example #3

0,30 * * * * your_command

this means "run when the minute of each hour is 0 or 30" (would run at: 1:30, 2:00, 2:30, 3:00, etc)

it's another way to accomplish the same results as example #2

example #4

19 * * * * your_command

this means "run when the minute of each hour is 19" (would run at: 1:19, 2:19, 3:19, etc)

example #5

*/19 * * * * your_command

this means "run when the minute of each hour is evenly divisible by 19" (would run at: 1:19, 1:38, 1:57, 2:19, 2:38, 2:57 etc)

note: several refinements have been made to this post by various users including the author

Sorting 1 million 8-decimal-digit numbers with 1 MB of RAM

While receiving the stream do these steps.

1st set some reasonable chunk size

Pseudo Code idea:

  1. The first step would be to find all the duplicates and stick them in a dictionary with its count and remove them.
  2. The third step would be to place number that exist in sequence of their algorithmic steps and place them in counters special dictionaries with the first number and their step like n, n+1..., n+2, 2n, 2n+1, 2n+2...
  3. Begin to compress in chunks some reasonable ranges of number like every 1000 or ever 10000 the remaining numbers that appear less often to repeat.
  4. Uncompress that range if a number is found and add it to the range and leave it uncompressed for a while longer.
  5. Otherwise just add that number to a byte[chunkSize]

Continue the first 4 steps while receiving the stream. The final step would be to either fail if you exceeded memory or start outputting the result once all the data is collected by beginning to sort the ranges and spit out the results in order and uncompressing those in order that need to be uncompressed and sort them when you get to them.

javascript /jQuery - For Loop

.each() should work for you. http://api.jquery.com/jQuery.each/ or http://api.jquery.com/each/ or you could use .map.

var newArray = $(array).map(function(i) {
    return $('#event' + i, response).html();
});

Edit: I removed the adding of the prepended 0 since it is suggested to not use that.

If you must have it use

var newArray = $(array).map(function(i) {
    var number = '' + i;
    if (number.length == 1) {
        number = '0' + number;
    }   
    return $('#event' + number, response).html();
});

HTML - Display image after selecting filename

You can achieve this with the following code:

$("input").change(function(e) {

    for (var i = 0; i < e.originalEvent.srcElement.files.length; i++) {

        var file = e.originalEvent.srcElement.files[i];

        var img = document.createElement("img");
        var reader = new FileReader();
        reader.onloadend = function() {
             img.src = reader.result;
        }
        reader.readAsDataURL(file);
        $("input").after(img);
    }
});

Demo: http://jsfiddle.net/ugPDx/

Browser back button handling

You can also add hash when page is loading:

location.hash = "noBack";

Then just handle location hash change to add another hash:

$(window).on('hashchange', function() {
    location.hash = "noBack";
});

That makes hash always present and back button tries to remove hash at first. Hash is then added again by "hashchange" handler - so page would never actually can be changed to previous one.

How to Import Excel file into mysql Database from PHP

For >= 2nd row values insert into table-

$file = fopen($filename, "r");
//$sql_data = "SELECT * FROM prod_list_1 ";

$count = 0;                                         // add this line
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
    //print_r($emapData);
    //exit();
    $count++;                                      // add this line

    if($count>1){                                  // add this line
      $sql = "INSERT into prod_list_1(p_bench,p_name,p_price,p_reason) values ('$emapData[0]','$emapData[1]','$emapData[2]','$emapData[3]')";
      mysql_query($sql);
    }                                              // add this line
}

Simple PHP Pagination script

Some of the tutorials I found that are easy to understand are:

It makes way more sense to break up your list into page-sized chunks, and only query your database one chunk at a time. This drastically reduces server processing time and page load time, as well as gives your user smaller pieces of info to digest, so he doesn't choke on whatever crap you're trying to feed him. The act of doing this is called pagination.

A basic pagination routine seems long and scary at first, but once you close your eyes, take a deep breath, and look at each piece of the script individually, you will find it's actually pretty easy stuff

The script:

// find out how many rows are in the table 
$sql = "SELECT COUNT(*) FROM numbers";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
$r = mysql_fetch_row($result);
$numrows = $r[0];

// number of rows to show per page
$rowsperpage = 10;
// find out total pages
$totalpages = ceil($numrows / $rowsperpage);

// get the current page or set a default
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
   // cast var as int
   $currentpage = (int) $_GET['currentpage'];
} else {
   // default page num
   $currentpage = 1;
} // end if

// if current page is greater than total pages...
if ($currentpage > $totalpages) {
   // set current page to last page
   $currentpage = $totalpages;
} // end if
// if current page is less than first page...
if ($currentpage < 1) {
   // set current page to first page
   $currentpage = 1;
} // end if

// the offset of the list, based on current page 
$offset = ($currentpage - 1) * $rowsperpage;

// get the info from the db 
$sql = "SELECT id, number FROM numbers LIMIT $offset, $rowsperpage";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);

// while there are rows to be fetched...
while ($list = mysql_fetch_assoc($result)) {
   // echo data
   echo $list['id'] . " : " . $list['number'] . "<br />";
} // end while

/******  build the pagination links ******/
// range of num links to show
$range = 3;

// if not on page 1, don't show back links
if ($currentpage > 1) {
   // show << link to go back to page 1
   echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1'><<</a> ";
   // get previous page num
   $prevpage = $currentpage - 1;
   // show < link to go back to 1 page
   echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'><</a> ";
} // end if 

// loop to show links to range of pages around current page
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
   // if it's a valid page number...
   if (($x > 0) && ($x <= $totalpages)) {
      // if we're on current page...
      if ($x == $currentpage) {
         // 'highlight' it but don't make a link
         echo " [<b>$x</b>] ";
      // if not current page...
      } else {
         // make it a link
         echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> ";
      } // end else
   } // end if 
} // end for

// if not on last page, show forward and last page links        
if ($currentpage != $totalpages) {
   // get next page
   $nextpage = $currentpage + 1;
    // echo forward link for next page 
   echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage'>></a> ";
   // echo forward link for lastpage
   echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages'>>></a> ";
} // end if
/****** end build pagination links ******/
?>

This tutorial is intended for developers who wish to give their users the ability to step through a large number of database rows in manageable chunks instead of the whole lot in one go.

how to make a specific text on TextView BOLD

Your String resource

<resources>
   <string name="your_string_resource_name">This is normal text<![CDATA[<b> but this is bold </b>]]> and <![CDATA[<u> but this is underline text</u>]]></string>
</resources> 

your java class

yourtextView.setText(getString(R.string.your_string_resource_name));

How to get all files under a specific directory in MATLAB?

This is a handy function for getting filenames, with the specified format (usually .mat) in a root folder!

    function filenames = getFilenames(rootDir, format)
        % Get filenames with specified `format` in given `foler` 
        %
        % Parameters
        % ----------
        % - rootDir: char vector
        %   Target folder
        % - format: char vector = 'mat'
        %   File foramt

        % default values
        if ~exist('format', 'var')
            format = 'mat';
        end

        format = ['*.', format];
        filenames = dir(fullfile(rootDir, format));
        filenames = arrayfun(...
            @(x) fullfile(x.folder, x.name), ...
            filenames, ...
            'UniformOutput', false ...
        );
    end

In your case, you can use the following snippet :)

filenames = getFilenames('D:/dic/**');
for i = 1:numel(filenames)
    filename = filenames{i};
    % do your job!
end

Run Android studio emulator on AMD processor

On mine, I had to install ARM AEBI a7a System Image and Google APIs, and also installed MIPS which was only available for API 15, 16, and 17 (I didn't go below 15.) Took about 12 hours of tinkering, but it works now.

alternatively, you can use Genymotion as an emulator, however will most likely lose design abilities otherwise available with included emulators.

It works now. Pretty slow, but it works. Of course, once you have the emulator started, as long as you don't close it, it will be much faster.

You may need to restart Android studio, and I restarted my entire computer just for good measure.

Hope that helps.

How do I get the last inserted ID of a MySQL table in PHP?

With PDO:

$pdo->lastInsertId();

With Mysqli:

$mysqli->insert_id;

Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

Access localhost from the internet

use your ip address or a service like noip.com if you need something more practical. Then eventually configure your router properly so incoming connection will be forwarded to the machine with the server running.

How to access List elements

Learn python the hard way ex 34

try this

animals = ['bear' , 'python' , 'peacock', 'kangaroo' , 'whale' , 'platypus']

# print "The first (1st) animal is at 0 and is a bear." 

for i in range(len(animals)):
    print "The %d animal is at %d and is a %s" % (i+1 ,i, animals[i])

# "The animal at 0 is the 1st animal and is a bear."

for i in range(len(animals)):
    print "The animal at %d is the %d and is a %s " % (i, i+1, animals[i])

How can I programmatically freeze the top row of an Excel worksheet in Excel 2007 VBA?

To expand this question into the realm of use outside of Excel s own VBA, the ActiveWindow property must be addressed as a child of the Excel.Application object.

Example for creating an Excel workbook from Access:

Using the Excel.Application object in another Office application's VBA project will require you to add Microsoft Excel 15.0 Object library (or equivalent for your own version).

Option Explicit

Sub xls_Build__Report()
    Dim xlApp As Excel.Application, ws As Worksheet, wb As Workbook
    Dim fn As String

    Set xlApp = CreateObject("Excel.Application")
    xlApp.DisplayAlerts = False
    xlApp.Visible = True

    Set wb = xlApp.Workbooks.Add
    With wb
        .Sheets(1).Name = "Report"
        With .Sheets("Report")

            'report generation here

        End With

        'This is where the Freeze Pane is dealt with
        'Freezes top row
        With xlApp.ActiveWindow
            .SplitColumn = 0
            .SplitRow = 1
            .FreezePanes = True
        End With

        fn = CurrentProject.Path & "\Reports\Report_" & Format(Date, "yyyymmdd") & ".xlsx"
        If CBool(Len(Dir(fn, vbNormal))) Then Kill fn
        .SaveAs FileName:=fn, FileFormat:=xlOpenXMLWorkbook
    End With

Close_and_Quit:
    wb.Close False
    xlApp.Quit
End Sub

The core process is really just a reiteration of previously submitted answers but I thought it was important to demonstrate how to deal with ActiveWindow when you are not within Excel's own VBA. While the code here is VBA, it should be directly transcribable to other languages and platforms.

Quoting backslashes in Python string literals

What Harley said, except the last point - it's not actually necessary to change the '/'s into '\'s before calling open. Windows is quite happy to accept paths with forward slashes.

infile = open('c:/folder/subfolder/file.txt')

The only time you're likely to need the string normpathed is if you're passing to to another program via the shell (using os.system or the subprocess module).

ES6 Class Multiple inheritance

From the page es6-features.org/#ClassInheritanceFromExpressions, it is possible to write an aggregation function to allow multiple inheritance:

class Rectangle extends aggregation(Shape, Colored, ZCoord) {}

var aggregation = (baseClass, ...mixins) => {
    let base = class _Combined extends baseClass {
        constructor (...args) {
            super(...args)
            mixins.forEach((mixin) => {
                mixin.prototype.initializer.call(this)
            })
        }
    }
    let copyProps = (target, source) => {
        Object.getOwnPropertyNames(source)
            .concat(Object.getOwnPropertySymbols(source))
            .forEach((prop) => {
            if (prop.match(/^(?:constructor|prototype|arguments|caller|name|bind|call|apply|toString|length)$/))
                return
            Object.defineProperty(target, prop, Object.getOwnPropertyDescriptor(source, prop))
        })
    }
    mixins.forEach((mixin) => {
        copyProps(base.prototype, mixin.prototype)
        copyProps(base, mixin)
    })
    return base
}

But that is already provided in libraries like aggregation.

Python vs Cpython

A programming language implementation is a system for executing computer programs.

There are two general approaches to programming language implementation:

  • Interpretation: An interpreter takes as input a program in some language, and performs the actions written in that language on some machine.
  • Compilation: A compiler takes as input a program in some language, and translates that program into some other language, which may serve as input to another interpreter or another compiler.

Python is an interpreted high-level programming language created by Guido van Rossum in 1991.

CPython is reference version of the Python computing language, which is written in C created by Guido van Rossum too.

Other list of Python Implementations

Source

Best way to include CSS? Why use @import?

There is almost no reason to use @import as it loads every single imported CSS file separately and can slow your site down significantly. If you are interested in the optimal way to deal with CSS(when it comes to page speed), this is how you should deal with all your CSS code:

  • Open all your CSS files and copy the code of every single file
  • Paste all the code in between a single STYLE tag in the HTML header of your page
  • Never use CSS @import or separate CSS files to deliver CSS unless you have a large amount of code or there is a specific need to.

More detailed information here: http://www.giftofspeed.com/optimize-css-delivery/

The reason the above works best is because it creates less requests for the browser to deal with and it can immediately start rendering the CSS instead of downloading separate files.

how to convert a string to date in mysql?

STR_TO_DATE('12/31/2011', '%m/%d/%Y')

Passing by reference in C

Because there is no pass-by-reference in the above code. Using pointers (such as void func(int* p)) is pass-by-address. This is pass-by-reference in C++ (won't work in C):

void func(int& ref) {ref = 4;}

...
int a;
func(a);
// a is 4 now

How to get the number of days of difference between two dates on mysql?

I prefer TIMESTAMPDIFF because you can easily change the unit if need be.

Replace values in list using Python

Here's another way:

>>> L = range (11)
>>> map(lambda x: x if x%2 else None, L)
[None, 1, None, 3, None, 5, None, 7, None, 9, None]

Initializing a two dimensional std::vector

Let's say you want to initialize 2D vector, m*n, with initial value to be 0

we could do this

#include<iostream>
int main(){ 
    int m = 2, n = 5;

    vector<vector<int>> vec(m, vector<int> (n, 0));

    return 0;
}

How to execute a Windows command on a remote PC?

psexec \\RemoteComputer cmd.exe

or use ssh or TeamViewer or RemoteDesktop!

Copy data from one existing row to another existing row in SQL?

UPDATE c11
SET
    c11.completed= c6.completed,
    c11.complete_date = c6.complete_date,
-- rest of columns to be copied
FROM courses c11 inner join courses c6 on
    c11.userID = c6.userID 
    and c11.courseID = 11 and c6.courseID = 6
     -- and any other checks

I have always viewed the From clause of an update, like one of a normal select. Actually if you want to check what will be updated before running the update, you can take replace the update parts with a select c11.*. See my comments on the lame duck's answer.

What's the difference between utf8_general_ci and utf8_unicode_ci?

I wanted to know what is the performance difference between using utf8_general_ci and utf8_unicode_ci, but I did not find any benchmarks listed on the internet, so I decided to create benchmarks myself.

I created a very simple table with 500,000 rows:

CREATE TABLE test(
  ID INT(11) DEFAULT NULL,
  Description VARCHAR(20) DEFAULT NULL
)
ENGINE = INNODB
CHARACTER SET utf8
COLLATE utf8_general_ci;

Then I filled it with random data by running this stored procedure:

CREATE PROCEDURE randomizer()
BEGIN
  DECLARE i INT DEFAULT 0;
  DECLARE random CHAR(20) ;
  theloop: loop
    SET random = CONV(FLOOR(RAND() * 99999999999999), 20, 36);
    INSERT INTO test VALUES (i+1, random);
    SET i=i+1;
    IF i = 500000 THEN
      LEAVE theloop;
    END IF;
  END LOOP theloop;
END

Then I created the following stored procedures to benchmark simple SELECT, SELECT with LIKE, and sorting (SELECT with ORDER BY):

CREATE PROCEDURE benchmark_simple_select()
BEGIN
  DECLARE i INT DEFAULT 0;
  theloop: loop
    SELECT *
    FROM test
    WHERE Description = 'test' COLLATE utf8_general_ci;
    SET i = i + 1;
    IF i = 30 THEN
      LEAVE theloop;
    END IF;
  END LOOP theloop;
END;

CREATE PROCEDURE benchmark_select_like()
BEGIN
  DECLARE i INT DEFAULT 0;
  theloop: loop
    SELECT *
    FROM test
    WHERE Description LIKE '%test' COLLATE utf8_general_ci;
    SET i = i + 1;
    IF i = 30 THEN
      LEAVE theloop;
    END IF;
  END LOOP theloop;
END;

CREATE PROCEDURE benchmark_order_by()
BEGIN
  DECLARE i INT DEFAULT 0;
  theloop: loop
    SELECT *
    FROM test
    WHERE ID > FLOOR(1 + RAND() * (400000 - 1))
    ORDER BY Description COLLATE utf8_general_ci LIMIT 1000;
    SET i = i + 1;
    IF i = 10 THEN
      LEAVE theloop;
    END IF;
  END LOOP theloop;
END;

In the stored procedures above utf8_general_ci collation is used, but of course during the tests I used both utf8_general_ci and utf8_unicode_ci.

I called each stored procedure 5 times for each collation (5 times for utf8_general_ci and 5 times for utf8_unicode_ci) and then calculated the average values.

My results are:

benchmark_simple_select()

  • with utf8_general_ci: 9,957 ms
  • with utf8_unicode_ci: 10,271 ms

In this benchmark using utf8_unicode_ci is slower than utf8_general_ci by 3.2%.

benchmark_select_like()

  • with utf8_general_ci: 11,441 ms
  • with utf8_unicode_ci: 12,811 ms

In this benchmark using utf8_unicode_ci is slower than utf8_general_ci by 12%.

benchmark_order_by()

  • with utf8_general_ci: 11,944 ms
  • with utf8_unicode_ci: 12,887 ms

In this benchmark using utf8_unicode_ci is slower than utf8_general_ci by 7.9%.

How can I get current date in Android?

This is the code i used:

             Date date = new Date();  // to get the date
             SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy"); // getting date in this format
             String formattedDate = df.format(date.getTime());
             text.setText(formattedDate);

Regular expression replace in C#

You can do it this with two replace's

//let stw be "John Smith $100,000.00 M"

sb_trim = Regex.Replace(stw, @"\s+\$|\s+(?=\w+$)", ",");
//sb_trim becomes "John Smith,100,000.00,M"

sb_trim = Regex.Replace(sb_trim, @"(?<=\d),(?=\d)|[.]0+(?=,)", "");
//sb_trim becomes "John Smith,100000,M"

sw.WriteLine(sb_trim);

How to search a Git repository by commit message?

Though a bit late, there is :/ which is the dedicated notation to specify a commit (or revision) based on the commit message, just prefix the search string with :/, e.g.:

git show :/keyword(s)

Here <keywords> can be a single word, or a complex regex pattern consisting of whitespaces, so please make sure to quote/escape when necessary, e.g.:

git log -1 -p ":/a few words"

Alternatively, a start point can be specified, to find the closest commit reachable from a specific point, e.g.:

git show 'HEAD^{/fix nasty bug}'

See: git revisions manual.

python and sys.argv

BTW you can pass the error message directly to sys.exit:

if len(sys.argv) < 2:
    sys.exit('Usage: %s database-name' % sys.argv[0])

if not os.path.exists(sys.argv[1]):
    sys.exit('ERROR: Database %s was not found!' % sys.argv[1])

Maven artifact and groupId naming

Consider following as for building basic first Maven application:

groupId

  • com.companyname.project

artifactId

  • project

version

  • 0.0.1

What does 'Unsupported major.minor version 52.0' mean, and how do I fix it?

Your code was compiled with Java 8.

Either compile your code with an older JDK (compliance level) or run it on a Java 8 JRE.

Hope this helps...

CSS hide scroll bar, but have element scrollable

I combined a couple of different answers in SO into the following snippet, which should work on all, if not most, modern browsers I believe. All you have to do is add the CSS class .disable-scrollbars onto the element you wish to apply this to.

.disable-scrollbars::-webkit-scrollbar {
    width: 0px;
    background: transparent; /* Chrome/Safari/Webkit */
}

.disable-scrollbars {
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none;  /* IE 10+ */
}

And if you want to use SCSS/SASS:

.disable-scrollbars {
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none;  /* IE 10+ */
  &::-webkit-scrollbar {
    width: 0px;
    background: transparent; /* Chrome/Safari/Webkit */
  }
}

wget/curl large file from google drive

Get the shareable link and open it in incognito (very important). It will say that it cannot scan.

Open inspector and track network traffic. Click the button "Download anyway".

Copy the url of the last request made. This is your link. Use it in wget.

What is the difference between tree depth and height?

According to Cormen et al. Introduction to Algorithms (Appendix B.5.3), the depth of a node X in a tree T is defined as the length of the simple path (number of edges) from the root node of T to X. The height of a node Y is the number of edges on the longest downward simple path from Y to a leaf. The height of a tree is defined as the height of its root node.

Note that a simple path is a path without repeat vertices.

The height of a tree is equal to the max depth of a tree. The depth of a node and the height of a node are not necessarily equal. See Figure B.6 of the 3rd Edition of Cormen et al. for an illustration of these concepts.

I have sometimes seen problems asking one to count nodes (vertices) instead of edges, so ask for clarification if you're not sure you should count nodes or edges during an exam or a job interview.

enable cors in .htaccess

This is what worked for me:

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

How to check if a specified key exists in a given S3 bucket using Java

Update:

It seems there's a new API to check just that. See another answer in this page: https://stackoverflow.com/a/36653034/435605

Original post:

Use errorCode.equals("NoSuchKey")

try {
    AmazonS3 s3 = new AmazonS3Client(new ClasspathPropertiesFileCredentialsProvider());
    String bucketName = getBucketName();
    s3.createBucket(bucketName);
    S3Object object = s3.getObject(bucketName, getKey());
} catch (AmazonServiceException e) {
    String errorCode = e.getErrorCode();
    if (!errorCode.equals("NoSuchKey")) {
        throw e;
    }
    Logger.getLogger(getClass()).debug("No such key!!!", e);
}

Note about the exception: I know exceptions should not be used for flow control. The problem is that Amazon didn't provide any api to check this flow - just documentation about the exception.

Laravel Eloquent Join vs Inner Join?

Probably not what you want to hear, but a "feeds" table would be a great middleman for this sort of transaction, giving you a denormalized way of pivoting to all these data with a polymorphic relationship.

You could build it like this:

<?php

Schema::create('feeds', function($table) {
    $table->increments('id');
    $table->timestamps();
    $table->unsignedInteger('user_id');
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    $table->morphs('target'); 
});

Build the feed model like so:

<?php

class Feed extends Eloquent
{
    protected $fillable = ['user_id', 'target_type', 'target_id'];

    public function user()
    {
        return $this->belongsTo('User');
    }

    public function target()
    {
        return $this->morphTo();
    }
}

Then keep it up to date with something like:

<?php

Vote::created(function(Vote $vote) {
    $target_type = 'Vote';
    $target_id   = $vote->id;
    $user_id     = $vote->user_id;

    Feed::create(compact('target_type', 'target_id', 'user_id'));
});

You could make the above much more generic/robust—this is just for demonstration purposes.

At this point, your feed items are really easy to retrieve all at once:

<?php

Feed::whereIn('user_id', $my_friend_ids)
    ->with('user', 'target')
    ->orderBy('created_at', 'desc')
    ->get();

Limitations of SQL Server Express

There are a number of limitations, notably:

  • Constrained to a single CPU (in 2012, this limitation has been changed to "The lesser of one socket or four cores", so multi-threading is possible)
  • 1GB RAM (Same in 2008/2012)
  • 4GB database size (raised to 10GB in SQL 2008 R2 and SQL 2012) per database

http://www.dotnetspider.com/tutorials/SqlServer-Tutorial-158.aspx http://www.microsoft.com/sqlserver/2008/en/us/editions.aspx

With regards to the number of databases, this MSDN article says there's no limit:

The 4 GB database size limit applies only to data files and not to log files. However, there are no limits to the number of databases that can be attached to the server.

However, as mentioned in the comments and above, the database size limit was raised to 10GB in 2008 R2 and 2012. Also, this 10GB limit only applies to relational data, and Filestream data does not count towards this limit (http://msdn.microsoft.com/en-us/library/bb895334.aspx).

Converting Go struct to JSON

Related issue:

I was having trouble converting struct to JSON, sending it as response from Golang, then, later catch the same in JavaScript via Ajax.

Wasted a lot of time, so posting solution here.

In Go:

// web server

type Foo struct {
    Number int    `json:"number"`
    Title  string `json:"title"`
}

foo_marshalled, err := json.Marshal(Foo{Number: 1, Title: "test"})
fmt.Fprint(w, string(foo_marshalled)) // write response to ResponseWriter (w)

In JavaScript:

// web call & receive in "data", thru Ajax/ other

var Foo = JSON.parse(data);
console.log("number: " + Foo.number);
console.log("title: " + Foo.title);

Access maven properties defined in the pom

This can be done with standard java properties in combination with the maven-resource-plugin with enabled filtering on properties.

For more info see http://maven.apache.org/plugins/maven-resources-plugin/examples/filter.html

This will work for standard maven project as for plugin projects

How to put individual tags for a scatter plot

Perhaps use plt.annotate:

import numpy as np
import matplotlib.pyplot as plt

N = 10
data = np.random.random((N, 4))
labels = ['point{0}'.format(i) for i in range(N)]

plt.subplots_adjust(bottom = 0.1)
plt.scatter(
    data[:, 0], data[:, 1], marker='o', c=data[:, 2], s=data[:, 3] * 1500,
    cmap=plt.get_cmap('Spectral'))

for label, x, y in zip(labels, data[:, 0], data[:, 1]):
    plt.annotate(
        label,
        xy=(x, y), xytext=(-20, 20),
        textcoords='offset points', ha='right', va='bottom',
        bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),
        arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))

plt.show()

enter image description here

find vs find_by vs where

There is a difference between find and find_by in that find will return an error if not found, whereas find_by will return null.

Sometimes it is easier to read if you have a method like find_by email: "haha", as opposed to .where(email: some_params).first.

PHP, Get tomorrows date from date

here's working function

function plus_one_day($date){
 $date2 = formatDate4db($date);
 $date1 = str_replace('-', '/', $date2);
 $tomorrow = date('Y-m-d',strtotime($date1 . "+1 days"));
 return $tomorrow; }

How to save a spark DataFrame as csv on disk?

Writing dataframe to disk as csv is similar read from csv. If you want your result as one file, you can use coalesce.

df.coalesce(1)
      .write
      .option("header","true")
      .option("sep",",")
      .mode("overwrite")
      .csv("output/path")

If your result is an array you should use language specific solution, not spark dataframe api. Because all these kind of results return driver machine.

how to access the command line for xampp on windows

In the version 3.2.4 of the XAMPP Control Panel, there is button that can open a command line prompt (red rectangle in the next figure)

enter image description here

After pressing the button, you will see the command prompt window.

enter image description here

From this window you can navigate through the different folders and start the different services available.

Get the selected option id with jQuery

You can get it using the :selected selector, like this:

$("#my_select").change(function() {
  var id = $(this).children(":selected").attr("id");
});

Bootstrap 3 Carousel fading to new slide instead of sliding to new slide

you can use transition in css3:

_x000D_
_x000D_
.carousel-fade .carousel-inner .item {_x000D_
  -webkit-transition-property: opacity;_x000D_
  transition-property: opacity;_x000D_
}_x000D_
.carousel-fade .carousel-inner .item,_x000D_
.carousel-fade .carousel-inner .active.left,_x000D_
.carousel-fade .carousel-inner .active.right {_x000D_
  opacity: 0;_x000D_
}_x000D_
.carousel-fade .carousel-inner .active,_x000D_
.carousel-fade .carousel-inner .next.left,_x000D_
.carousel-fade .carousel-inner .prev.right {_x000D_
  opacity: 1;_x000D_
}_x000D_
.carousel-fade .carousel-inner .next,_x000D_
.carousel-fade .carousel-inner .prev,_x000D_
.carousel-fade .carousel-inner .active.left,_x000D_
.carousel-fade .carousel-inner .active.right {_x000D_
  left: 0;_x000D_
  -webkit-transform: translate3d(0, 0, 0);_x000D_
          transform: translate3d(0, 0, 0);_x000D_
}_x000D_
.carousel-fade .carousel-control {_x000D_
  z-index: 2;_x000D_
}
_x000D_
_x000D_
_x000D_

"Python version 2.7 required, which was not found in the registry" error when attempting to install netCDF4 on Windows 8

This error can occur if you are installing a package with a different bitness than your Python version. To see whether your Python installation is 32- or 64-bit, see here.

Some superpacks (e.g. for Scipy) available on SourceForge or python.org are for 32-bit systems and some are for 64-bit systems. See this answer. In Windows, uninstalling the 32-bit and installing the 64-bit version (or vice versa if your installation is 32-bit) can solve the problem.

What's the difference between :: (double colon) and -> (arrow) in PHP?

Yes, I just hit my first 'PHP Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM'. My bad, I had a $instance::method() that should have been $instance->method(). Silly me.

The odd thing is that this still works just fine on my local machine (running PHP 5.3.8) - nothing, not even a warning with error_reporting = E_ALL - but not at all on the test server, there it just explodes with a syntax error and a white screen in the browser. Since PHP logging was turned off at the test machine, and the hosting company was too busy to turn it on, it was not too obvious.

So, word of warning: apparently, some PHP installations will let you use a $instance::method(), while others don't.

If anybody can expand on why that is, please do.

How do I convert a date/time to epoch time (unix time/seconds since 1970) in Perl?

Get Date::Manip from CPAN, then:

use Date::Manip;
$string = '18-Sep-2008 20:09'; # or a wide range of other date formats
$unix_time = UnixDate( ParseDate($string), "%s" );

edit:

Date::Manip is big and slow, but very flexible in parsing, and it's pure perl. Use it if you're in a hurry when you're writing code, and you know you won't be in a hurry when you're running it.

e.g. Use it to parse command line options once on start-up, but don't use it parsing large amounts of data on a busy web server.

See the authors comments.

(Thanks to the author of the first comment below)

Best approach to real time http streaming to HTML5 video client

Take a look at this solution. As I know, Flashphoner allows to play Live audio+video stream in the pure HTML5 page.

They use MPEG1 and G.711 codecs for playback. The hack is rendering decoded video to HTML5 canvas element and playing decoded audio via HTML5 audio context.

How to take input in an array + PYTHON?

You want this - enter N and then take N number of elements.I am considering your input case is just like this

5
2 3 6 6 5

have this in this way in python 3.x (for python 2.x use raw_input() instead if input())

Python 3

n = int(input())
arr = input()   # takes the whole line of n numbers
l = list(map(int,arr.split(' '))) # split those numbers with space( becomes ['2','3','6','6','5']) and then map every element into int (becomes [2,3,6,6,5])

Python 2

n = int(raw_input())
arr = raw_input()   # takes the whole line of n numbers
l = list(map(int,arr.split(' '))) # split those numbers with space( becomes ['2','3','6','6','5']) and then map every element into int (becomes [2,3,6,6,5])

Bash Templating: How to build configuration files from templates with Bash?

If you want to use Jinja2 templates, see this project: j2cli.

It supports:

  • Templates from JSON, INI, YAML files and input streams
  • Templating from environment variables

How to replace values at specific indexes of a python list?

You can use operator.setitem.

from operator import setitem
a = [5, 4, 3, 2, 1, 0]
ell = [0, 1, 3, 5]
m = [0, 0, 0, 0]
for b, c in zip(ell, m):
    setitem(a, b, c)
>>> a
[0, 0, 3, 0, 1, 0]

Is it any more readable or efficient than your solution? I am not sure!

Error message 'Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.'

I had an issue with automap. In the bin folder, the file automap.4net.dll was there, but for some reason the automap.xml and automap.dll weren't. Copying them to the bin directory solved the issue.

Android: ListView elements with multiple clickable buttons

This is sort of an appendage @znq's answer...

There are many cases where you want to know the row position for a clicked item AND you want to know which view in the row was tapped. This is going to be a lot more important in tablet UIs.

You can do this with the following custom adapter:

private static class CustomCursorAdapter extends CursorAdapter {

    protected ListView mListView;

    protected static class RowViewHolder {
        public TextView mTitle;
        public TextView mText;
    }

    public CustomCursorAdapter(Activity activity) {
        super();
        mListView = activity.getListView();
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        // do what you need to do
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        View view = View.inflate(context, R.layout.row_layout, null);

        RowViewHolder holder = new RowViewHolder();
        holder.mTitle = (TextView) view.findViewById(R.id.Title);
        holder.mText = (TextView) view.findViewById(R.id.Text);

        holder.mTitle.setOnClickListener(mOnTitleClickListener);
        holder.mText.setOnClickListener(mOnTextClickListener);

        view.setTag(holder);

        return view;
    }

    private OnClickListener mOnTitleClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            final int position = mListView.getPositionForView((View) v.getParent());
            Log.v(TAG, "Title clicked, row %d", position);
        }
    };

    private OnClickListener mOnTextClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            final int position = mListView.getPositionForView((View) v.getParent());
            Log.v(TAG, "Text clicked, row %d", position);
        }
    };
}

setting an environment variable in virtualenv

In case you're using virtualenvwrapper (I highly recommend doing so), you can define different hooks (preactivate, postactivate, predeactivate, postdeactivate) using the scripts with the same names in $VIRTUAL_ENV/bin/. You need the postactivate hook.

$ workon myvenv

$ cat $VIRTUAL_ENV/bin/postactivate
#!/bin/bash
# This hook is run after this virtualenv is activated.
export DJANGO_DEBUG=True
export S3_KEY=mykey
export S3_SECRET=mysecret

$ echo $DJANGO_DEBUG
True

If you want to keep this configuration in your project directory, simply create a symlink from your project directory to $VIRTUAL_ENV/bin/postactivate.

$ rm $VIRTUAL_ENV/bin/postactivate
$ ln -s .env/postactivate $VIRTUAL_ENV/bin/postactivate

You could even automate the creation of the symlinks each time you use mkvirtualenv.

Cleaning up on deactivate

Remember that this wont clean up after itself. When you deactivate the virtualenv, the environment variable will persist. To clean up symmetrically you can add to $VIRTUAL_ENV/bin/predeactivate.

$ cat $VIRTUAL_ENV/bin/predeactivate
#!/bin/bash
# This hook is run before this virtualenv is deactivated.
unset DJANGO_DEBUG

$ deactivate

$ echo $DJANGO_DEBUG

Remember that if using this for environment variables that might already be set in your environment then the unset will result in them being completely unset on leaving the virtualenv. So if that is at all probable you could record the previous value somewhere temporary then read it back in on deactivate.

Setup:

$ cat $VIRTUAL_ENV/bin/postactivate
#!/bin/bash
# This hook is run after this virtualenv is activated.
if [[ -n $SOME_VAR ]]
then
    export SOME_VAR_BACKUP=$SOME_VAR
fi
export SOME_VAR=apple

$ cat $VIRTUAL_ENV/bin/predeactivate
#!/bin/bash
# This hook is run before this virtualenv is deactivated.
if [[ -n $SOME_VAR_BACKUP ]]
then
    export SOME_VAR=$SOME_VAR_BACKUP
    unset SOME_VAR_BACKUP
else
    unset SOME_VAR
fi

Test:

$ echo $SOME_VAR
banana

$ workon myenv

$ echo $SOME_VAR
apple

$ deactivate

$ echo $SOME_VAR
banana

JPA entity without id

I guess your entity_property has a composite key (entity_id, name) where entity_id is a foreign key to entity. If so, you can map it as follows:

@Embeddable
public class EntityPropertyPK {
    @Column(name = "name")
    private String name;

    @ManyToOne
    @JoinColumn(name = "entity_id")
    private Entity entity;

    ...
}

@Entity 
@Table(name="entity_property") 
public class EntityProperty { 
    @EmbeddedId
    private EntityPropertyPK id;

    @Column(name = "value")
    private String value; 

    ...
}

How do I write good/correct package __init__.py files

__all__ is very good - it helps guide import statements without automatically importing modules http://docs.python.org/tutorial/modules.html#importing-from-a-package

using __all__ and import * is redundant, only __all__ is needed

I think one of the most powerful reasons to use import * in an __init__.py to import packages is to be able to refactor a script that has grown into multiple scripts without breaking an existing application. But if you're designing a package from the start. I think it's best to leave __init__.py files empty.

for example:

foo.py - contains classes related to foo such as fooFactory, tallFoo, shortFoo

then the app grows and now it's a whole folder

foo/
    __init__.py
    foofactories.py
    tallFoos.py
    shortfoos.py
    mediumfoos.py
    santaslittlehelperfoo.py
    superawsomefoo.py
    anotherfoo.py

then the init script can say

__all__ = ['foofactories', 'tallFoos', 'shortfoos', 'medumfoos',
           'santaslittlehelperfoo', 'superawsomefoo', 'anotherfoo']
# deprecated to keep older scripts who import this from breaking
from foo.foofactories import fooFactory
from foo.tallfoos import tallFoo
from foo.shortfoos import shortFoo

so that a script written to do the following does not break during the change:

from foo import fooFactory, tallFoo, shortFoo

Default SecurityProtocol in .NET 4.5

If you can use .NET 4.7.1 or newer, it will use TLS 1.2 as the minimum protocol based on the operating system capabilities. Per Microsoft recommendation :

To ensure .NET Framework applications remain secure, the TLS version should not be hardcoded. .NET Framework applications should use the TLS version the operating system (OS) supports.

Sum all values in every column of a data.frame in R

For the sake of completion:

 apply(people[,-1], 2, function(x) sum(x))
#Height Weight 
#   199    425 

How to output only captured groups with sed?

Give up and use Perl

Since sed does not cut it, let's just throw the towel and use Perl, at least it is LSB while grep GNU extensions are not :-)

  • Print the entire matching part, no matching groups or lookbehind needed:

    cat <<EOS | perl -lane 'print m/\d+/g'
    a1 b2
    a34 b56
    EOS
    

    Output:

    12
    3456
    
  • Single match per line, often structured data fields:

    cat <<EOS | perl -lape 's/.*?a(\d+).*/$1/g'
    a1 b2
    a34 b56
    EOS
    

    Output:

    1
    34
    

    With lookbehind:

    cat <<EOS | perl -lane 'print m/(?<=a)(\d+)/'
    a1 b2
    a34 b56
    EOS
    
  • Multiple fields:

    cat <<EOS | perl -lape 's/.*?a(\d+).*?b(\d+).*/$1 $2/g'
    a1 c0 b2 c0
    a34 c0 b56 c0
    EOS
    

    Output:

    1 2
    34 56
    
  • Multiple matches per line, often unstructured data:

    cat <<EOS | perl -lape 's/.*?a(\d+)|.*/$1 /g'
    a1 b2
    a34 b56 a78 b90
    EOS
    

    Output:

    1 
    34 78
    

    With lookbehind:

    cat EOS<< | perl -lane 'print m/(?<=a)(\d+)/g'
    a1 b2
    a34 b56 a78 b90
    EOS
    

    Output:

    1
    3478
    

Best way to compare 2 XML documents in Java

skaffman seems to be giving a good answer.

another way is probably to format the XML using a commmand line utility like xmlstarlet(http://xmlstar.sourceforge.net/) and then format both the strings and then use any diff utility(library) to diff the resulting output files. I don't know if this is a good solution when issues are with namespaces.

jQuery Selector: Id Ends With?

It's safer to add the underscore or $ to the term you're searching for so it's less likely to match other elements which end in the same ID:

$("element[id$=_txtTitle]")

(where element is the type of element you're trying to find - eg div, input etc.

(Note, you're suggesting your IDs tend to have $ signs in them, but I think .NET 2 now tends to use underscores in the ID instead, so my example uses an underscore).

get next sequence value from database using hibernate

To get the new id, all you have to do is flush the entity manager. See getNext() method below:

@Entity
@SequenceGenerator(name = "sequence", sequenceName = "mySequence")
public class SequenceFetcher
{
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequence")
    private long id;

    public long getId() {
        return id;
    }

    public static long getNext(EntityManager em) {
        SequenceFetcher sf = new SequenceFetcher();
        em.persist(sf);
        em.flush();
        return sf.getId();
    }
}

SSL InsecurePlatform error when using Requests package

Requests 2.6 introduced this warning for users of python prior to 2.7.9 with only stock SSL modules available.

Assuming you can't upgrade to a newer version of python, this will install more up-to-date python SSL libraries:

pip install --upgrade ndg-httpsclient 

HOWEVER, this may fail on some systems without the build-dependencies for pyOpenSSL. On debian systems, running this before the pip command above should be enough for pyOpenSSL to build:

apt-get install python-dev libffi-dev libssl-dev

How do I convert datetime to ISO 8601 in PHP

Object Oriented

This is the recommended way.

$datetime = new DateTime('2010-12-30 23:21:46');

echo $datetime->format(DateTime::ATOM); // Updated ISO8601

Procedural

For older versions of PHP, or if you are more comfortable with procedural code.

echo date(DATE_ISO8601, strtotime('2010-12-30 23:21:46'));

Start / Stop a Windows Service from a non-Administrator user account

Windows Service runs using a local system account.It can start automatically as the user logs into the system or it can be started manually.However, a windows service say BST can be run using a particular user account on the machine.This can be done as follows:start services.msc and go to the properties of your windows service,BST.From there you can give the login parameters of the required user.Service then runs with that user account and no other user can run that service.

How to center a WPF app on screen?

What about the SystemParameters class in PresentationFramework? It has a WorkArea property that seems to be what you are looking for.

But, why won't setting the Window.WindowStartupLocation work? CenterScreen is one of the enum values. Do you have to tweak the centering?

What's the best practice for primary keys in tables?

I follow a few rules:

  1. Primary keys should be as small as necessary. Prefer a numeric type because numeric types are stored in a much more compact format than character formats. This is because most primary keys will be foreign keys in another table as well as used in multiple indexes. The smaller your key, the smaller the index, the less pages in the cache you will use.
  2. Primary keys should never change. Updating a primary key should always be out of the question. This is because it is most likely to be used in multiple indexes and used as a foreign key. Updating a single primary key could cause of ripple effect of changes.
  3. Do NOT use "your problem primary key" as your logic model primary key. For example passport number, social security number, or employee contract number as these "primary key" can change for real world situations.

On surrogate vs natural key, I refer to the rules above. If the natural key is small and will never change it can be used as a primary key. If the natural key is large or likely to change I use surrogate keys. If there is no primary key I still make a surrogate key because experience shows you will always add tables to your schema and wish you'd put a primary key in place.

How do I copy an object in Java?

Add Cloneable and below code to your class

public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

Use this clonedObject = (YourClass) yourClassObject.clone();

How to destroy a JavaScript object?

Structure your code so that all your temporary objects are located inside closures instead of global namespace / global object properties and go out of scope when you've done with them. GC will take care of the rest.

Sending event when AngularJS finished loading

may be i can help you by this example

In the custom fancybox I show contents with interpolated values.

in the service, in the "open" fancybox method, i do

open: function(html, $compile) {
        var el = angular.element(html);
     var compiledEl = $compile(el);
        $.fancybox.open(el); 
      }

the $compile returns compiled data. you can check the compiled data

How add "or" in switch statements?

Case-statements automatically fall through if you don't specify otherwise (by writing break). Therefor you can write

switch(myvar)
{
   case 2:
   case 5:
   {
      //your code
   break;
   }

// etc... }

Add new line in text file with Windows batch file

Suppose you want to insert a particular line of text (not an empty line):

@echo off
FOR /F %%C IN ('FIND /C /V "" ^<%origfile%') DO SET totallines=%%C
set /a totallines+=1

@echo off
<%origfile% (FOR /L %%i IN (1,1,%totallines%) DO (
  SETLOCAL EnableDelayedExpansion
  SET /p L=
  IF %%i==%insertat% ECHO(!TL!
  ECHO(!L!
  ENDLOCAL
)
) >%tempfile%

COPY /Y %tempfile% %origfile% >NUL

DEL %tempfile%

How to check if an appSettings key exists?

If the key you are looking for isn't present in the config file, you won't be able to convert it to a string with .ToString() because the value will be null and you'll get an "Object reference not set to an instance of an object" error. It's best to first see if the value exists before trying to get the string representation.

if (!String.IsNullOrEmpty(ConfigurationManager.AppSettings["myKey"]))
{
    String myKey = ConfigurationManager.AppSettings["myKey"].ToString();
}

Or, as Code Monkey suggested:

if (ConfigurationSettings.AppSettings["myKey"] != null)
{
// Now do your magic..
}

How to convert Milliseconds to "X mins, x seconds" in Java?

I think the best way is:

String.format("%d min, %d sec", 
    TimeUnit.MILLISECONDS.toSeconds(length)/60,
    TimeUnit.MILLISECONDS.toSeconds(length) % 60 );

Maven and adding JARs to system scope

Try this configuration. It worked for me:

<plugin>
    <artifactId>maven-war-plugin</artifactId>
    <version>2.4</version>
    <configuration>
        <warSourceDirectory>mywebRoot</warSourceDirectory>
        <warSourceExcludes>source\**,build\**,dist\**,WEB-INF\lib\*,
            WEB-INF\classes\**,build.*
        </warSourceExcludes>
        <webXml>myproject/source/deploiement/web.xml</webXml>
        <webResources>
            <resource>
                <directory>mywebRoot/WEB-INF/lib</directory>
                <targetPath>WEB-INF/lib</targetPath>
                <includes>
                        <include>mySystemJar1.jar.jar</include>
                         <include>mySystemJar2.jar</include>
                   </includes>
            </resource>
        </webResources>
    </configuration>
</plugin>

C# find biggest number

You can use the Math.Max method to return the maximum of two numbers, e.g. for int:

int maximum = Math.Max(number1, Math.Max(number2, number3))

There ist also the Max() method from LINQ which you can use on any IEnumerable.

INNER JOIN same table

Perhaps this should be the select (if I understand the question correctly)

select user.user_fname, user.user_lname, parent.user_fname, parent.user_lname
... As before

How to create nested directories using Mkdir in Golang?

os.Mkdir is used to create a single directory. To create a folder path, instead try using:

os.MkdirAll(folderPath, os.ModePerm)

Go documentation

func MkdirAll(path string, perm FileMode) error

MkdirAll creates a directory named path, along with any necessary parents, and returns nil, or else returns an error. The permission bits perm are used for all directories that MkdirAll creates. If path is already a directory, MkdirAll does nothing and returns nil.

Edit:

Updated to correctly use os.ModePerm instead.
For concatenation of file paths, use package path/filepath as described in @Chris' answer.

What are the various "Build action" settings in Visual Studio project properties and what do they do?

How about this page from Microsoft Connect (explaining the DesignData and DesignDataWithDesignTimeCreatableTypes) types. Quoting:

The following describes the two Build Actions for Sample Data files.

Sample data .xaml files must be assigned one of the below Build Actions:

DesignData: Sample data types will be created as faux types. Use this Build Action when the sample data types are not creatable or have read-only properties that you want to defined sample data values for.

DesignDataWithDesignTimeCreatableTypes: Sample data types will be created using the types defined in the sample data file. Use this Build Action when the sample data types are creatable using their default empty constructor.

Not so incredibly exhaustive, but it at least gives a hint. This MSDN walkthrough also gives some ideas. I don't know whether these Build Actions are applicable for non-Silverlight projects also.

How do I create JavaScript array (JSON format) dynamically?

var student = [];
var obj = {
    'first_name': name,
    'last_name': name,
    'age': age,
}
student.push(obj);

Html: Difference between cell spacing and cell padding

Cell spacing and margin is the space between cells.

Cell padding is space inside cells, between the cell border (even if invisible) and the cell content, such as text.

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 get rid of blank pages in PDF exported from SSRS

In addition to the margins, the most common issue by far, I have also seen two additional possibilities:

  1. Using + to concatenate text. You should use & instead.
  2. Text overflowing the width of the specified textbox. So if your textbox only holds 30 characters and you try to cram 300 in there, you might end up with extra pages.

How do I use Access-Control-Allow-Origin? Does it just go in between the html head tags?

<?php header("Access-Control-Allow-Origin: http://example.com"); ?>

This command disables only first console warning info

console

Result: console result

How can I use Html.Action?

Another case is http redirection. If your page redirects http requests to https, then may be your partial view tries to redirect by itself.

It causes same problem again. For this problem, you can reorganize your .net error pages or iis error pages configuration.

Just make sure you are redirecting requests to right error or not found page and make sure this error page contains non problematic partial. If your page supports only https, do not forward requests to error page without using https, if error page contains partial, this partials tries to redirect seperately from requested url, it causes problem.

Java - Check if input is a positive integer, negative integer, natural number and so on.

If you really have to avoid operators then use Math.signum()

Returns the signum function of the argument; zero if the argument is zero, 1.0 if the argument is greater than zero, -1.0 if the argument is less than zero.

EDIT : As per the comments, this works for only double and float values. For integer values you can use the method:

Integer.signum(int i)

Make scrollbars only visible when a Div is hovered over?

.div::-webkit-scrollbar-thumb {
    background: transparent;
}

.div:hover::-webkit-scrollbar-thumb {
    background: red;
}

How to make a div 100% height of the browser window

This is what worked for me:

_x000D_
_x000D_
<div style="position:fixed; top:0px; left:0px; bottom:0px; right:0px; background: red;"> </div>
_x000D_
_x000D_
_x000D_

Use position:fixed instead of position:absolute, that way even if you scroll down the division will expand to the end of the screen.

What is the difference between a string and a byte string?

From What is Unicode:

Fundamentally, computers just deal with numbers. They store letters and other characters by assigning a number for each one.

......

Unicode provides a unique number for every character, no matter what the platform, no matter what the program, no matter what the language.

So when a computer represents a string, it finds characters stored in the computer of the string through their unique Unicode number and these figures are stored in memory. But you can't directly write the string to disk or transmit the string on network through their unique Unicode number because these figures are just simple decimal number. You should encode the string to byte string, such as UTF-8. UTF-8 is a character encoding capable of encoding all possible characters and it stores characters as bytes (it looks like this). So the encoded string can be used everywhere because UTF-8 is nearly supported everywhere. When you open a text file encoded in UTF-8 from other systems, your computer will decode it and display characters in it through their unique Unicode number. When a browser receive string data encoded UTF-8 from network, it will decode the data to string (assume the browser in UTF-8 encoding) and display the string.

In python3, you can transform string and byte string to each other:

>>> print('??'.encode('utf-8'))
b'\xe4\xb8\xad\xe6\x96\x87'
>>> print(b'\xe4\xb8\xad\xe6\x96\x87'.decode('utf-8'))
?? 

In a word, string is for displaying to humans to read on a computer and byte string is for storing to disk and data transmission.

NotificationCenter issue on Swift 3

Notifications appear to have changed again (October 2016).

// Register to receive notification

NotificationCenter.default.addObserver(self, selector: #selector(yourClass.yourMethod), name: NSNotification.Name(rawValue: "yourNotificatioName"), object: nil)

// Post notification

NotificationCenter.default.post(name: NSNotification.Name(rawValue: "yourNotificationName"), object: nil)

Open Jquery modal dialog on click event

Try this

    $(function() {

$('#clickMe').click(function(event) {
    var mytext = $('#myText').val();


    $('<div id="dialog">'+mytext+'</div>').appendTo('body');        
    event.preventDefault();

        $("#dialog").dialog({                   
            width: 600,
            modal: true,
            close: function(event, ui) {
                $("#dialog").remove();
                }
            });
    }); //close click
});

And in HTML

<h3 id="clickMe">Open dialog</h3>
<textarea cols="0" rows="0" id="myText" style="display:none">Some hidden text display none</textarea>

Error : ORA-01704: string literal too long

To solve this issue on my side, I had to use a combo of what was already proposed there

DECLARE
  chunk1 CLOB; chunk2 CLOB; chunk3 CLOB;
BEGIN
  chunk1 := 'very long literal part 1';
  chunk2 := 'very long literal part 2';
  chunk3 := 'very long literal part 3';

  INSERT INTO table (MY_CLOB)
  SELECT ( chunk1 || chunk2 || chunk3 ) FROM dual;
END;

Hope this helps.

Delete the 'first' record from a table in SQL Server, without a WHERE condition

No, AFAIK, it's not possible to do it portably.

There's no defined "first" record anyway - on different SQL engines it's perfectly possible that "SELECT * FROM table" might return the results in a different order each time.

Converting Milliseconds to Minutes and Seconds?

I don't think Java 1.5 support concurrent TimeUnit. Otherwise, I would suggest for TimeUnit. Below is based on pure math approach.

stopWatch.stop();
long milliseconds = stopWatch.getTime();

int seconds = (int) ((milliseconds / 1000) % 60);
int minutes = (int) ((milliseconds / 1000) / 60);

How to render a PDF file in Android

To add a little light to this, I would have to go with the pdf.js solution from Mozilla. Here is the link to an already well written implementation of this: https://bitbucket.org/butelo/pdfviewer/.

Here are the edits that I added in my Android Activity:

private String getInternalPDFURL(String interalPDFName){
    return "file:///android_asset/pdfviewer/index.html?pdf=" + interalPDFName + ".pdf";
}

Here are the edits I made in pdffile.js:

var url = '../' + getPDFURL();

function getPDFURL(){
    var query = window.location.search.substring(1);
    var vars = query.split("=");
    var pdfPage = vars[1];
    return pdfPage;
}

Why is Spring's ApplicationContext.getBean considered bad?

The motivation is to write code that doesn't depend explicitly on Spring. That way, if you choose to switch containers, you don't have to rewrite any code.

Think of the container as something is invisible to your code, magically providing for its needs, without being asked.

Dependency injection is a counterpoint to the "service locator" pattern. If you are going to lookup dependencies by name, you might as well get rid of the DI container and use something like JNDI.

Where's javax.servlet?

The normal procedure with Eclipse and Java EE webapplications is to install a servlet container (Tomcat, Jetty, etc) or application server (Glassfish (which is bundled in the "Sun Java EE" download), JBoss AS, WebSphere, Weblogic, etc) and integrate it in Eclipse using a (builtin) plugin in the Servers view.

During the creation wizard of a new Dynamic Web Project, you can then pick the integrated server from the list. If you happen to have an existing Dynamic Web Project without a server or want to change the associated one, then you need to modify it in the Targeted Rutimes section of the project's properties.

Either way, Eclipse will automatically place the necessary server-specific libraries in the project's classpath (buildpath).

You should absolutely in no way extract and copy server-specific libraries into /WEB-INF/lib or even worse the JRE/lib yourself, to "fix" the compilation errors in Eclipse. It would make your webapplication tied to a specific server and thus completely unportable.

How do I center list items inside a UL element?

A more modern way is to use flexbox:

_x000D_
_x000D_
ul{_x000D_
  list-style-type:none;_x000D_
  display:flex;_x000D_
  justify-content: center;_x000D_
_x000D_
}_x000D_
ul li{_x000D_
  display: list-item;_x000D_
  background: black;_x000D_
  padding: 5px 10px;_x000D_
  color:white;_x000D_
  margin: 0 3px;_x000D_
}_x000D_
div{_x000D_
  background: wheat;_x000D_
}
_x000D_
<div>_x000D_
<ul>_x000D_
  <li>One</li>_x000D_
  <li>Two</li>_x000D_
  <li>Three</li>_x000D_
</ul>  _x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

Does MS SQL Server's "between" include the range boundaries?

I've always used this:

WHERE myDate BETWEEN startDate AND (endDate+1)

how to configure hibernate config file for sql server

We also need to mention default schema for SQSERVER: dbo

<property name="hibernate.default_schema">dbo</property>

Tested with hibernate 4

XMLHttpRequest status 0 (responseText is empty)

My problem similar to this was solved by checking my html code. I was having an onclick handler in my form submit button to a method. like this : onclick="sendFalconRequestWithHeaders()". This method in turn calls ajax just like yours, and does what I want. But not as expected, my browser was returning nothing.

Learned From someone's hardwork, I have returned false in this handler, and solved. Let me mention that before arriving to this post, I have spent a whole 3-day weekend and a half day in office writing code implementing CORS filters, jetty config, other jersey and embedded jetty related stuff - just to fix this., revolving all my understanding around cross domain ajax requests and standards stuff. It was ridiculous how simple mistakes in javascript make you dumb.

To be true, I have tried signed.applets.codebase_principal_support = true and written isLocalHost() **if**. may be this method needs to be implemented by us, firefox says there is no such Now I have to clean my code to submit git patch cleanly. Thanks to that someone.

Collection that allows only unique items in .NET?

How about just an extension method on HashSet?

public static void AddOrThrow<T>(this HashSet<T> hash, T item)
{
    if (!hash.Add(item))
        throw new ValueExistingException();
}

.htaccess, order allow, deny, deny from all: confused?

This is a quite confusing way of using Apache configuration directives.

Technically, the first bit is equivalent to

Allow From All

This is because Order Deny,Allow makes the Deny directive evaluated before the Allow Directives. In this case, Deny and Allow conflict with each other, but Allow, being the last evaluated will match any user, and access will be granted.

Now, just to make things clear, this kind of configuration is BAD and should be avoided at all cost, because it borders undefined behaviour.

The Limit sections define which HTTP methods have access to the directory containing the .htaccess file.

Here, GET and POST methods are allowed access, and PUT and DELETE methods are denied access. Here's a link explaining what the various HTTP methods are: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html

However, it's more than often useless to use these limitations as long as you don't have custom CGI scripts or Apache modules that directly handle the non-standard methods (PUT and DELETE), since by default, Apache does not handle them at all.

It must also be noted that a few other methods exist that can also be handled by Limit, namely CONNECT, OPTIONS, PATCH, PROPFIND, PROPPATCH, MKCOL, COPY, MOVE, LOCK, and UNLOCK.

The last bit is also most certainly useless, since any correctly configured Apache installation contains the following piece of configuration (for Apache 2.2 and earlier):

#
# The following lines prevent .htaccess and .htpasswd files from being 
# viewed by Web clients. 
#
<Files ~ "^\.ht">
    Order allow,deny
    Deny from all
    Satisfy all
</Files>

which forbids access to any file beginning by ".ht".

The equivalent Apache 2.4 configuration should look like:

<Files ~ "^\.ht">
    Require all denied
</Files>

Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger

Had the same problem, it was indeed caused by weblogic stupidly using its own opensaml implementation. To solve it, you have to tell it to load classes from WEB-INF/lib for this package in weblogic.xml:

    <prefer-application-packages>
        <package-name>org.opensaml.*</package-name>
    </prefer-application-packages>

maybe <prefer-web-inf-classes>true</prefer-web-inf-classes> would work too.

What does 'git remote add upstream' help achieve?

The wiki is talking from a forked repo point of view. You have access to pull and push from origin, which will be your fork of the main diaspora repo. To pull in changes from this main repo, you add a remote, "upstream" in your local repo, pointing to this original and pull from it.

So "origin" is a clone of your fork repo, from which you push and pull. "Upstream" is a name for the main repo, from where you pull and keep a clone of your fork updated, but you don't have push access to it.

How to use timer in C?

You can use a time_t struct and clock() function from time.h.

Store the start time in a time_t struct by using clock() and check the elapsed time by comparing the difference between stored time and current time.

How to generate a random String in Java

You can also use UUID class from java.util package, which returns random uuid of 32bit characters String.

java.util.UUID.randomUUID().toString()

http://java.sun.com/j2se/1.5.0/docs/api/java/util/UUID.html

How do I set GIT_SSL_NO_VERIFY for specific repos only?

If you are on a Windows machine and have the Git installed, you can try the below steps:

  1. Go to the folder of Git installation, ex: C:\Program Files (x86)\Git\etc
  2. Edit the file: gitconfig
  3. Under the [http] section, add the line: sslVerify = false

    [http]
      sslVerify = false
    

Reading column names alone in a csv file

I am just mentioning how to get all the column names from a csv file. I am using pandas library.

First we read the file.

import pandas as pd
file = pd.read_csv('details.csv')

Then, in order to just get all the column names as a list from input file use:-

columns = list(file.head(0))

Remove warning messages in PHP

You could suppress the warning using error_reporting but the much better way is to fix your script in the first place.

If you don't know how, edit your question and show us the line in question and the warning that is displayed.

How do I load an org.w3c.dom.Document from XML in a string?

Whoa there!

There's a potentially serious problem with this code, because it ignores the character encoding specified in the String (which is UTF-8 by default). When you call String.getBytes() the platform default encoding is used to encode Unicode characters to bytes. So, the parser may think it's getting UTF-8 data when in fact it's getting EBCDIC or something… not pretty!

Instead, use the parse method that takes an InputSource, which can be constructed with a Reader, like this:

import java.io.StringReader;
import org.xml.sax.InputSource;
…
        return builder.parse(new InputSource(new StringReader(xml)));

It may not seem like a big deal, but ignorance of character encoding issues leads to insidious code rot akin to y2k.

Vertically aligning a checkbox

The most effective solution that I found is to define the parent element with display:flex and align-items:center

LIVE DEMO

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <style>
      .myclass{
        display:flex;
        align-items:center;
        background-color:grey;
        color:#fff;
        height:50px;
      }
    </style>
  </head>
  <body>
    <div class="myclass">
      <input type="checkbox">
      <label>do you love Ananas?
      </label>
    </div>
  </body>
</html>

OUTPUT:

enter image description here

Convert HTML to PDF in .NET

Last Updated: October 2020

This is the list of options for HTML to PDF conversion in .NET that I have put together (some free some paid)

If none of the options above help you you can always search the NuGet packages:
https://www.nuget.org/packages?q=html+pdf

How to clear variables in ipython?

I tried

%reset -f

and cleared all the variables and contents without prompt. -f does the force action on the given command without prompting for yes/no.

Wish this helps.. :)

How do I show the changes which have been staged?

If your intentions are to push-target a remote repo branch and your first pass at a commit change log were incomplete, you can correct the commit statement before pushing like this.

Locally

... make some changes ...

git diff # look at unstaged changes

git commit -am"partial description of changes"

... recall more changes unmentioned in commit ...

git diff origin/master # look at staged but not pushed changes

... amend staged commit statement ...

git commit --amend -m"i missed mentioning these changes ...."

git push

Difference between map and collect in Ruby?

I did a benchmark test to try and answer this question, then found this post so here are my findings (which differ slightly from the other answers)

Here is the benchmark code:

require 'benchmark'

h = { abc: 'hello', 'another_key' => 123, 4567 => 'third' }
a = 1..10
many = 500_000

Benchmark.bm do |b|
  GC.start

  b.report("hash keys collect") do
    many.times do
      h.keys.collect(&:to_s)
    end
  end

  GC.start

  b.report("hash keys map") do
    many.times do
      h.keys.map(&:to_s)
    end
  end

  GC.start

  b.report("array collect") do
    many.times do
      a.collect(&:to_s)
    end
  end

  GC.start

  b.report("array map") do
    many.times do
      a.map(&:to_s)
    end
  end
end

And the results I got were:

                   user     system      total        real
hash keys collect  0.540000   0.000000   0.540000 (  0.570994)
hash keys map      0.500000   0.010000   0.510000 (  0.517126)
array collect      1.670000   0.020000   1.690000 (  1.731233)
array map          1.680000   0.020000   1.700000 (  1.744398) 

Perhaps an alias isn't free?

What is the correct value for the disabled attribute?

From MDN by setAttribute():

To set the value of a Boolean attribute, such as disabled, you can specify any value. An empty string or the name of the attribute are recommended values. All that matters is that if the attribute is present at all, regardless of its actual value, its value is considered to be true. The absence of the attribute means its value is false. By setting the value of the disabled attribute to the empty string (""), we are setting disabled to true, which results in the button being disabled.

Link to MDN

Solution

  • I mean that in XHTML Strict is right disabled="disabled",
  • and in HTML5 is only disabled, like <input name="myinput" disabled>
  • In javascript, I set the value to true via e.disabled = true;
    or to "" via setAttribute( "disabled", "" );

Test in Chrome

var f = document.querySelectorAll( "label.disabled input" );
for( var i = 0; i < f.length; i++ )
{
    // Reference
    var e = f[ i ];

    // Actions
    e.setAttribute( "disabled", false|null|undefined|""|0|"disabled" );
    /*
        <input disabled="false"|"null"|"undefined"|empty|"0"|"disabled">
        e.getAttribute( "disabled" ) === "false"|"null"|"undefined"|""|"0"|"disabled"
        e.disabled === true
    */
    
    e.removeAttribute( "disabled" );
    /*
        <input>
        e.getAttribute( "disabled" ) === null
        e.disabled === false
    */

    e.disabled = false|null|undefined|""|0;
    /*
        <input>
        e.getAttribute( "disabled" ) === null|null|null|null|null
        e.disabled === false
    */

    e.disabled = true|" "|"disabled"|1;
    /*
        <input disabled>
        e.getAttribute( "disabled" ) === ""|""|""|""
        e.disabled === true
    */
}

Date difference in minutes in Python

there is also a sneak way with pandas:

pd.to_timedelta(x) - pd.to_timedelta(y)

Android: Getting a file URI from a content URI?

you can get filename by uri with simple way

Retrieving file information

fun get_filename_by_uri(uri : Uri) : String{
    contentResolver.query(uri, null, null, null, null).use { cursor ->
        cursor?.let {
            val nameIndex = it.getColumnIndex(OpenableColumns.DISPLAY_NAME)
            it.moveToFirst()
            return it.getString(nameIndex)
        }
    }
    return ""
}

and easy to read it by using

contentResolver.openInputStream(uri)

Angular2 *ngFor in select list, set active based on string from object

This should work

<option *ngFor="let title of titleArray" 
    [value]="title.Value" 
    [attr.selected]="passenger.Title==title.Text ? true : null">
  {{title.Text}}
</option>

I'm not sure the attr. part is necessary.

Angular expression if array contains

Somewhere in your initialisation put this code.

Array.prototype.contains = function contains(obj) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] === obj) {
            return true;
        }
    }
    return false;
};

Then, you can use it this way:

<li ng-class="{approved: selectedForApproval.contains(jobSet)}"></li>

How to add 'ON DELETE CASCADE' in ALTER TABLE statement

If you want to change a foreign key without dropping it you can do:

ALTER TABLE child_table_name  WITH CHECK ADD FOREIGN KEY(child_column_name)
REFERENCES parent_table_name (parent_column_name) ON DELETE CASCADE

How to manipulate arrays. Find the average. Beginner Java

-while(int i=0; i < data.length; i++) 
+for(int i=0; i < data.length; i++) 

Find length (size) of an array in jquery

Integer has no method length. Try string

var testvar={};
testvar[1]="2";
alert(testvar[1].length);

Error in finding last used cell in Excel with VBA

I would add to the answer given by Siddarth Rout to say that the CountA call can be skipped by having Find return a Range object, instead of a row number, and then test the returned Range object to see if it is Nothing (blank worksheet).

Also, I would have my version of any LastRow procedure return a zero for a blank worksheet, then I can know it is blank.

Add a column in a table in HIVE QL

You cannot add a column with a default value in Hive. You have the right syntax for adding the column ALTER TABLE test1 ADD COLUMNS (access_count1 int);, you just need to get rid of default sum(max_count). No changes to that files backing your table will happen as a result of adding the column. Hive handles the "missing" data by interpreting NULL as the value for every cell in that column.

So now your have the problem of needing to populate the column. Unfortunately in Hive you essentially need to rewrite the whole table, this time with the column populated. It may be easier to rerun your original query with the new column. Or you could add the column to the table you have now, then select all of its columns plus value for the new column.

You also have the option to always COALESCE the column to your desired default and leave it NULL for now. This option fails when you want NULL to have a meaning distinct from your desired default. It also requires you to depend on always remembering to COALESCE.

If you are very confident in your abilities to deal with the files backing Hive, you could also directly alter them to add your default. In general I would recommend against this because most of the time it will be slower and more dangerous. There might be some case where it makes sense though, so I've included this option for completeness.

Does Python support short-circuiting?

Yep, both and and or operators short-circuit -- see the docs.

Get the client IP address using PHP

The simplest way to get the visitor’s/client’s IP address is using the $_SERVER['REMOTE_ADDR'] or $_SERVER['REMOTE_HOST'] variables.

However, sometimes this does not return the correct IP address of the visitor, so we can use some other server variables to get the IP address.

The below both functions are equivalent with the difference only in how and from where the values are retrieved.

getenv() is used to get the value of an environment variable in PHP.

// Function to get the client IP address
function get_client_ip() {
    $ipaddress = '';
    if (getenv('HTTP_CLIENT_IP'))
        $ipaddress = getenv('HTTP_CLIENT_IP');
    else if(getenv('HTTP_X_FORWARDED_FOR'))
        $ipaddress = getenv('HTTP_X_FORWARDED_FOR');
    else if(getenv('HTTP_X_FORWARDED'))
        $ipaddress = getenv('HTTP_X_FORWARDED');
    else if(getenv('HTTP_FORWARDED_FOR'))
        $ipaddress = getenv('HTTP_FORWARDED_FOR');
    else if(getenv('HTTP_FORWARDED'))
       $ipaddress = getenv('HTTP_FORWARDED');
    else if(getenv('REMOTE_ADDR'))
        $ipaddress = getenv('REMOTE_ADDR');
    else
        $ipaddress = 'UNKNOWN';
    return $ipaddress;
}

$_SERVER is an array that contains server variables created by the web server.

// Function to get the client IP address
function get_client_ip() {
    $ipaddress = '';
    if (isset($_SERVER['HTTP_CLIENT_IP']))
        $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
    else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
        $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
    else if(isset($_SERVER['HTTP_X_FORWARDED']))
        $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
    else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
        $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
    else if(isset($_SERVER['HTTP_FORWARDED']))
        $ipaddress = $_SERVER['HTTP_FORWARDED'];
    else if(isset($_SERVER['REMOTE_ADDR']))
        $ipaddress = $_SERVER['REMOTE_ADDR'];
    else
        $ipaddress = 'UNKNOWN';
    return $ipaddress;
}

How to get the input from the Tkinter Text Widget?

To get Tkinter input from the text box in python 3 the complete student level program used by me is as under:

#Imports all (*) classes,
#atributes, and methods of tkinter into the
#current workspace

from tkinter import *

#***********************************
#Creates an instance of the class tkinter.Tk.
#This creates what is called the "root" window. By conventon,
#the root window in Tkinter is usually called "root",
#but you are free to call it by any other name.

root = Tk()
root.title('how to get text from textbox')


#**********************************
mystring = StringVar()

####define the function that the signup button will do
def getvalue():
##    print(mystring.get())
#*************************************

Label(root, text="Text to get").grid(row=0, sticky=W)  #label
Entry(root, textvariable = mystring).grid(row=0, column=1, sticky=E) #entry textbox

WSignUp = Button(root, text="print text", command=getvalue).grid(row=3, column=0, sticky=W) #button


############################################
# executes the mainloop (that is, the event loop) method of the root
# object. The mainloop method is what keeps the root window visible.
# If you remove the line, the window created will disappear
# immediately as the script stops running. This will happen so fast
# that you will not even see the window appearing on your screen.
# Keeping the mainloop running also lets you keep the
# program running until you press the close buton
root.mainloop()

UIGestureRecognizer on UIImageView

For Blocks lover you can use ALActionBlocks to add action of gestures in block

__weak ALViewController *wSelf = self;
imageView.userInteractionEnabled = YES;
UITapGestureRecognizer *gr = [[UITapGestureRecognizer alloc] initWithBlock:^(UITapGestureRecognizer *weakGR) {
    NSLog(@"pan %@", NSStringFromCGPoint([weakGR locationInView:wSelf.view]));
}];
[self.imageView addGestureRecognizer:gr];

Creating Duplicate Table From Existing Table

Use this query to create the new table with the values from existing table

CREATE TABLE New_Table_name AS SELECT * FROM Existing_table_Name; 

Now you can get all the values from existing table into newly created table.

Parser Error: '_Default' is not allowed here because it does not extend class 'System.Web.UI.Page' & MasterType declaration

Look for this:

ANY page in your project that has a missing, or different Namespace...

If you have ANY page in your project with <NO Namespace> , OR a

DIFFERENT Namespace than Default.aspx, you will get this

"Cannot load Default.aspx", or this: "Default.aspx does not belong here".

ALSO: If you have a Redirect to a page in your Solution/Project and the page which is to be Redirected To has a bad namespace -- you may not get a compiler error, until you try and run. If the Redirect is removed or commented-out, the error goes away...

BTW -- What the hell do these error messages mean? Is this MS.Access, with the "misdirection" -- ??

DGK

How to set up Spark on Windows?

You can download spark from here:

http://spark.apache.org/downloads.html

I recommend you this version: Hadoop 2 (HDP2, CDH5)

Since version 1.0.0 there are .cmd scripts to run spark in windows.

Unpack it using 7zip or similar.

To start you can execute /bin/spark-shell.cmd --master local[2]

To configure your instance, you can follow this link: http://spark.apache.org/docs/latest/

How to get ° character in a string in python?

This is the most coder-friendly version of specifying a unicode character:

degree_sign= u'\N{DEGREE SIGN}'

Note: must be a capital N in the \N construct to avoid confusion with the '\n' newline character. The character name inside the curly braces can be any case.

It's easier to remember the name of a character than its unicode index. It's also more readable, ergo debugging-friendly. The character substitution happens at compile time: the .py[co] file will contain a constant for u'°':

>>> import dis
>>> c= compile('u"\N{DEGREE SIGN}"', '', 'eval')
>>> dis.dis(c)
  1           0 LOAD_CONST               0 (u'\xb0')
              3 RETURN_VALUE
>>> c.co_consts
(u'\xb0',)
>>> c= compile('u"\N{DEGREE SIGN}-\N{EMPTY SET}"', '', 'eval')
>>> c.co_consts
(u'\xb0-\u2205',)
>>> print c.co_consts[0]
°-Ø

How to make a promise from setTimeout

This is not an answer to the original question. But, as an original question is not a real-world problem it should not be a problem. I tried to explain to a friend what are promises in JavaScript and the difference between promise and callback.

Code below serves as an explanation:

//very basic callback example using setTimeout
//function a is asynchronous function
//function b used as a callback
function a (callback){
    setTimeout (function(){
       console.log ('using callback:'); 
       let mockResponseData = '{"data": "something for callback"}'; 
       if (callback){
          callback (mockResponseData);
       }
    }, 2000);

} 

function b (dataJson) {
   let dataObject = JSON.parse (dataJson);
   console.log (dataObject.data);   
}

a (b);

//rewriting above code using Promise
//function c is asynchronous function
function c () {
   return new Promise(function (resolve, reject) {
     setTimeout (function(){
       console.log ('using promise:'); 
       let mockResponseData = '{"data": "something for promise"}'; 
       resolve(mockResponseData); 
    }, 2000);      
   }); 

}

c().then (b);

JsFiddle

Is there a way to ignore a single FindBugs warning?

As others Mentioned, you can use the @SuppressFBWarnings Annotation. If you don't want or can't add another Dependency to your code, you can add the Annotation to your Code yourself, Findbugs dosn't care in which Package the Annotation is.

@Retention(RetentionPolicy.CLASS)
public @interface SuppressFBWarnings {
    /**
     * The set of FindBugs warnings that are to be suppressed in
     * annotated element. The value can be a bug category, kind or pattern.
     *
     */
    String[] value() default {};

    /**
     * Optional documentation of the reason why the warning is suppressed
     */
    String justification() default "";
}

Source: https://sourceforge.net/p/findbugs/feature-requests/298/#5e88

Calling constructors in c++ without new

In append to JaredPar answer

1-usual ctor, 2nd-function-like-ctor with temporary object.

Compile this source somewhere here http://melpon.org/wandbox/ with different compilers

// turn off rvo for clang, gcc with '-fno-elide-constructors'

#include <stdio.h>
class Thing {
public:
    Thing(const char*){puts(__FUNCTION__ );}
    Thing(const Thing&){puts(__FUNCTION__ );}   
    ~Thing(){puts(__FUNCTION__);}
};
int main(int /*argc*/, const char** /*argv*/) {
    Thing myThing = Thing("asdf");
}

And you will see the result.

From ISO/IEC 14882 2003-10-15

8.5, part 12

Your 1st,2nd construction are called direct-initialization

12.1, part 13

A functional notation type conversion (5.2.3) can be used to create new objects of its type. [Note: The syntax looks like an explicit call of the constructor. ] ... An object created in this way is unnamed. [Note: 12.2 describes the lifetime of temporary objects. ] [Note: explicit constructor calls do not yield lvalues, see 3.10. ]


Where to read about RVO:

12 Special member functions / 12.8 Copying class objects/ Part 15

When certain criteria are met, an implementation is allowed to omit the copy construction of a class object, even if the copy constructor and/or destructor for the object have side effects.

Turn off it with compiler flag from comment to view such copy-behavior)

Test method is inconclusive: Test wasn't run. Error?

In my case, I referenced 2 projects from my unittestproject. Both referenced projects used a dll with the same name, but with a different version.

I did not notice this in Visual Studio. I noticed the error in the Eventviewer.

To solve this, I used bindingRedirect in the app.config of the unittestproject to fix the dll-version.

How to clear Flutter's Build cache?

you can run flutter clean command

Adding a newline into a string in C#

Based on your replies to everyone else, something like this is what you're looking for.

string file = @"C:\file.txt";
string strToProcess = "fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@";
string[] lines = strToProcess.Split(new char[] { '@' }, StringSplitOptions.RemoveEmptyEntries);

using (StreamWriter writer = new StreamWriter(file))
{
    foreach (string line in lines)
    {
        writer.WriteLine(line + "@");
    }
}

Java - Create a new String instance with specified length and filled with specific character. Best solution?

In Java 11, you have repeat:

String s = " ";
s = s.repeat(1);

(Although at the time of writing still subject to change)

Yahoo Finance API

IMHO the best place to find this information is: http://code.google.com/p/yahoo-finance-managed/

I used to use the "gummy-stuff" too but then I found this page which is far more organized and full of easy to use examples. I am using it now to get the data in CSV files and use the files in my C++/Qt project.

Pure CSS animation visibility with delay

Unfortunately you can't animate the display property. For a full list of what you can animate, try this CSS animation list by w3 Schools.

If you want to retain it's visual position on the page, you should try animating either it's height (which will still affect the position of other elements), or opacity (how transparent it is). You could even try animating the z-index, which is the position on the z axis (depth), by putting an element over the top of it, and then rearranging what's on top. However, I'd suggest using opacity, as it retains the vertical space where the element is.

I've updated the fiddle to show an example.

Good luck!

Angular Material: mat-select not selecting default

My solution is little tricky and simpler.

<div>
    <mat-select
        [placeholder]="selected2">
      <mat-option
          *ngFor="let option of options2"
          value="{{ option.id }}">
        {{ option.name }}
      </mat-option>
    </mat-select>
  </div>

I just made use of the placeholder. The default color of material placeholder is light gray. To make it look like the option is selected, I just manipulated the CSS as follows:

::ng-deep .mat-select-placeholder {
    color: black;
}

How to use OR condition in a JavaScript IF statement?

Worth noting that || will also return true if BOTH A and B are true.

In JavaScript, if you're looking for A or B, but not both, you'll need to do something similar to:

if( (A && !B) || (B && !A) ) { ... }

Base 64 encode and decode example code

Above many answers but doesn't work for me some of them no exception handling in correct way. here am adding a perfect solution work amazing for me sure also for you too.

//base64 decode string 
 String s = "ewoic2VydmVyIjoic2cuenhjLmx1IiwKInNuaSI6InRlc3RpbmciLAoidXNlcm5hbWUiOiJ0ZXN0
    ZXIiLAoicGFzc3dvcmQiOiJ0ZXN0ZXIiLAoicG9ydCI6IjQ0MyIKfQ==";
    String val = a(s) ;
     Toast.makeText(this, ""+val, Toast.LENGTH_SHORT).show();
    
       public static String a(String str) {
             try {
                 return new String(Base64.decode(str, 0), "UTF-8");
             } catch (UnsupportedEncodingException | IllegalArgumentException unused) {
                 return "This is not a base64 data";
             }
         }

How to add an action to a UIAlertView button using Swift iOS

this is for swift 4.2, 5 and 5+

let alert = UIAlertController(title: "ooops!", message: "Unable to login", preferredStyle: .alert)

alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))

self.present(alert, animated: true)

SQL Server - Create a copy of a database table and place it in the same database?

1st option

select *
  into ABC_1
  from ABC;

2nd option: use SSIS, that is right click on database in object explorer > all tasks > export data

  • source and target: your DB
  • source table: ABC
  • target table: ABC_1 (table will be created)

PHP - Indirect modification of overloaded property

I was receiving this notice for doing this:

$var = reset($myClass->my_magic_property);

This fixed it:

$tmp = $myClass->my_magic_property;
$var = reset($tmp);

Installing OpenCV for Python on Ubuntu, getting ImportError: No module named cv2.cv

I tried all the other options here, but I could not get import cv2 working with Anaconda on Ubuntu. This is the only thing that helped:

pip install opencv-python

React / JSX Dynamic Component Name

I figured out a new solution. Do note that I am using ES6 modules so I am requiring the class. You could also define a new React class instead.

var components = {
    example: React.createFactory( require('./ExampleComponent') )
};

var type = "example";

newComponent() {
    return components[type]({ attribute: "value" });
}

Remove a string from the beginning of a string

Plain form, without regex:

$prefix = 'bla_';
$str = 'bla_string_bla_bla_bla';

if (substr($str, 0, strlen($prefix)) == $prefix) {
    $str = substr($str, strlen($prefix));
} 

Takes: 0.0369 ms (0.000,036,954 seconds)

And with:

$prefix = 'bla_';
$str = 'bla_string_bla_bla_bla';
$str = preg_replace('/^' . preg_quote($prefix, '/') . '/', '', $str);

Takes: 0.1749 ms (0.000,174,999 seconds) the 1st run (compiling), and 0.0510 ms (0.000,051,021 seconds) after.

Profiled on my server, obviously.

No 'Access-Control-Allow-Origin' header is present on the requested resource- AngularJS

In my case, I was trying to hit a WebAPI service on localhost from inside an MVC app that used a lot of Angular code. My WebAPI service worked fine with Fiddler via http://localhost/myservice. Once I took a moment to configure the MVC app to use IIS instead of IIS Express (a part of Visual Studio), it worked fine, without adding any CORS-related configuration to either area.

In mocha testing while calling asynchronous function how to avoid the timeout Error: timeout of 2000ms exceeded

My issue was not sending the response back, so it was hanging. If you are using express make sure that res.send(data), res.json(data) or whatever the api method you wanna use is executed for the route you are testing.

How to show Error & Warning Message Box in .NET/ How to Customize MessageBox

Try this:

MessageBox.Show("Some text", "Some title", 
    MessageBoxButtons.OK, MessageBoxIcon.Error);

How do I post form data with fetch api?

To quote MDN on FormData (emphasis mine):

The FormData interface provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest.send() method. It uses the same format a form would use if the encoding type were set to "multipart/form-data".

So when using FormData you are locking yourself into multipart/form-data. There is no way to send a FormData object as the body and not sending data in the multipart/form-data format.

If you want to send the data as application/x-www-form-urlencoded you will either have to specify the body as an URL-encoded string, or pass a URLSearchParams object. The latter unfortunately cannot be directly initialized from a form element. If you don’t want to iterate through your form elements yourself (which you could do using HTMLFormElement.elements), you could also create a URLSearchParams object from a FormData object:

const data = new URLSearchParams();
for (const pair of new FormData(formElement)) {
    data.append(pair[0], pair[1]);
}

fetch(url, {
    method: 'post',
    body: data,
})
.then(…);

Note that you do not need to specify a Content-Type header yourself.


As noted by monk-time in the comments, you can also create URLSearchParams and pass the FormData object directly, instead of appending the values in a loop:

const data = new URLSearchParams(new FormData(formElement));

This still has some experimental support in browsers though, so make sure to test this properly before you use it.

JavaScript override methods

Edit: It's now six years since the original answer was written and a lot has changed!

  • If you're using a newer version of JavaScript, possibly compiled with a tool like Babel, you can use real classes.
  • If you're using the class-like component constructors provided by Angular or React, you'll want to look in the docs for that framework.
  • If you're using ES5 and making "fake" classes by hand using prototypes, the answer below is still as right as it ever was.

Good luck!


JavaScript inheritance looks a bit different from Java. Here is how the native JavaScript object system looks:

// Create a class
function Vehicle(color){
  this.color = color;
}

// Add an instance method
Vehicle.prototype.go = function(){
  return "Underway in " + this.color;
}

// Add a second class
function Car(color){
  this.color = color;
}

// And declare it is a subclass of the first
Car.prototype = new Vehicle();

// Override the instance method
Car.prototype.go = function(){
  return Vehicle.prototype.go.call(this) + " car"
}

// Create some instances and see the overridden behavior.
var v = new Vehicle("blue");
v.go() // "Underway in blue"

var c = new Car("red");
c.go() // "Underway in red car"

Unfortunately this is a bit ugly and it does not include a very nice way to "super": you have to manually specify which parent classes' method you want to call. As a result, there are a variety of tools to make creating classes nicer. Try looking at Prototype.js, Backbone.js, or a similar library that includes a nicer syntax for doing OOP in js.

How to delete a whole folder and content?

According to the documentation:

If this abstract pathname does not denote a directory, then this method returns null.

So you should check if listFiles is null and only continue if it's not

boolean deleteDirectory(File path) {
    if(path.exists()) {
        File[] files = path.listFiles();
        if (files == null) {
            return false;
        }
        for (File file : files) {
            if (file.isDirectory()) {
                deleteDirectory(file);
            } else {
                boolean wasSuccessful = file.delete();
                if (wasSuccessful) {
                    Log.i("Deleted ", "successfully");
                }
            }
        }
    }
    return(path.delete());
}

Gerrit error when Change-Id in commit messages are missing

You need to follow below 2 steps instructions:

[Issue] remote: Hint: To automatically insert Change-Id, install the hook:

1) gitdir=$(git rev-parse --git-dir);

2) scp -p -P 29418 <username>@gerrit.xyz.se:hooks/commit-msg ${gitdir}/hooks/

normally $gitdir = ".git". You need to update the username and the Gerrit link.

Iterate Multi-Dimensional Array with Nested Foreach Statement

Use LINQ .Cast<int>() to convert 2D array to IEnumerable<int>.

LINQPad example:

var arr = new int[,] { 
  { 1, 2, 3 }, 
  { 4, 5, 6 } 
};

IEnumerable<int> values = arr.Cast<int>();
Console.WriteLine(values);

Output:

Sequence is 1,2,3,4,5,6

How to disable scientific notation?

You can effectively remove scientific notation in printing with this code:

options(scipen=999)

Make a link use POST instead of GET

You can use this jQuery function

function makePostRequest(url, data) {
    var jForm = $('<form></form>');
    jForm.attr('action', url);
    jForm.attr('method', 'post');
    for (name in data) {
        var jInput = $("<input>");
        jInput.attr('name', name);
        jInput.attr('value', data[name]);
        jForm.append(jInput);
    }
    jForm.submit();
}

Here is an example in jsFiddle (http://jsfiddle.net/S7zUm/)

Among $_REQUEST, $_GET and $_POST which one is the fastest?

There are certain security concerns involved as a hacker can set a cookie that will override a $_POST or $_GET value. If you handle sensitive data, I would not recommend using $_REQUEST. – Xandor

you can't be used $_GET alternative of $_POST on some case.

When ??

  • when you want to upload a file.
  • when you don't won't to show a data in url.

GET also has limits on the amount of information to send. The limitation is about 2000 characters.

Other thing's there are few case when you can't retrieve a data using $_POST

When ?

  • when data is passed in URL.

For Rest Service

`GET` - Provides a read only access to a resource.

`PUT` - Used to create a new resource.

there is nothing be wrong to use $_REQUEST.

But the way to do that is to check $_SERVER['REQUEST_METHOD'] explicitly, not rely on $_POST being empty for a GET.

How to pre-populate the sms body text via an html link

<a href="sms:/* phone number here */&body=/* body text here */">Link</a>

This works on my iPhone 5S!

Gson: How to exclude specific fields from Serialization without annotations

I ran into this issue, in which I had a small number of fields I wanted to exclude only from serialization, so I developed a fairly simple solution that uses Gson's @Expose annotation with custom exclusion strategies.

The only built-in way to use @Expose is by setting GsonBuilder.excludeFieldsWithoutExposeAnnotation(), but as the name indicates, fields without an explicit @Expose are ignored. As I only had a few fields I wanted to exclude, I found the prospect of adding the annotation to every field very cumbersome.

I effectively wanted the inverse, in which everything was included unless I explicitly used @Expose to exclude it. I used the following exclusion strategies to accomplish this:

new GsonBuilder()
        .addSerializationExclusionStrategy(new ExclusionStrategy() {
            @Override
            public boolean shouldSkipField(FieldAttributes fieldAttributes) {
                final Expose expose = fieldAttributes.getAnnotation(Expose.class);
                return expose != null && !expose.serialize();
            }

            @Override
            public boolean shouldSkipClass(Class<?> aClass) {
                return false;
            }
        })
        .addDeserializationExclusionStrategy(new ExclusionStrategy() {
            @Override
            public boolean shouldSkipField(FieldAttributes fieldAttributes) {
                final Expose expose = fieldAttributes.getAnnotation(Expose.class);
                return expose != null && !expose.deserialize();
            }

            @Override
            public boolean shouldSkipClass(Class<?> aClass) {
                return false;
            }
        })
        .create();

Now I can easily exclude a few fields with @Expose(serialize = false) or @Expose(deserialize = false) annotations (note that the default value for both @Expose attributes is true). You can of course use @Expose(serialize = false, deserialize = false), but that is more concisely accomplished by declaring the field transient instead (which does still take effect with these custom exclusion strategies).