Programs & Examples On #Spsitedataquery

How does the ARM architecture differ from x86?

Additional to Jerry Coffin's first paragraph. Ie, ARM design gives lower power consumption.

The company ARM, only licenses the CPU technology. They don't make physical chips. This allows other companies to add various peripheral technologies, typically called SOC or system-on-chip. Whether the device is a tablet, a cell phone, or an in-car entertainment system. This allows chip vendors to tailor the rest of the chip to a particular application. This has additional benefits,

  1. Lower board cost
  2. Lower power (note1)
  3. Easier manufacture
  4. Smaller form factor

ARM supports SOC vendors with AMBA, allowing SOC implementers to purchase off the shelf 3rd party modules; like an Ethernet, memory and interrupt controllers. Some other CPU platforms support this, like MIPS, but MIPS is not as power conscious.

All of these are beneficial to a handheld/battery operated design. Some are just good all around. As well, ARM has a history of battery operated devices; Apple Newton, Psion Organizers. The PDA software infra-structure was leveraged by some companies to create smart phone type devices. Although, more success was had by those who re-invented the GUI for use with a smart phone.

The rise of Open source tool sets and operating systems also facilitated the various SOC chips. A closed organization would have issues trying to support all the various devices available for the ARM. The two most popular cellular platforms, Andriod and OSx/IOS, are based up Linux and FreeBSD, Mach and NetBSD os's. Open Source helps SOC vendors provide software support for their chip sets.

Hopefully, why x86 is used for the keyboard is self-evident. It has the software, and more importantly people trained to use that software. Netwinder is one ARM system that was originally designed for the keyboard. Also, manufacturer's are currently looking at ARM64 for the server market. Power/heat is a concern at 24/7 data centers.

So I would say that the ecosystem that grows around these chips is as important as features like low power consumption. ARM has been striving for low power, higher performance computing for some time (mid to late 1980's) and they have a lot of people on board.

Note1: Multiple chips need bus drivers to inter-communicate at known voltages and drive. Also, typically separate chips need support capacitors and other power components which can be shared in an SOC system.

How to Specify Eclipse Proxy Authentication Credentials?

In Eclipse, go to Window → Preferences → General → Network Connections. In the Active Provider combo box, choose "Manual". In the proxy entries table, for each entry click "Edit..." and supply your proxy host, port, username and password details.

Eclipse screenshot

How do I rename the extension for a bunch of files?

Rename file extensions for all files under current directory and sub directories without any other packages (only use shell script):

  1. Create a shell script rename.sh under current directory with the following code:

    #!/bin/bash
    
    for file in $(find . -name "*$1"); do
      mv "$file" "${file%$1}$2"
    done
    
  2. Run it by ./rename.sh .old .new.

    Eg. ./rename.sh .html .txt

How to sign an android apk file

Don't worry...! Follow these below steps and you will get your signed .apk file. I was also worry about that, but these step get ride me off from the frustration. Steps to sign your application:

  1. Export the unsigned package:

Right click on the project in Eclipse -> Android Tools -> Export Unsigned Application Package (like here we export our GoogleDriveApp.apk to Desktop)

Sign the application using your keystore and the jarsigner tool (follow below steps):

Open cmd-->change directory where your "jarsigner.exe" exist (like here in my system it exist at "C:\Program Files\Java\jdk1.6.0_17\bin"

Now enter belwo command in cmd:

jarsigner -verbose -keystore c:\users\android\debug.keystore c:\users\pir fahim\Desktops\GoogleDriveApp.apk my_keystore_alias

It will ask you to provide your password: Enter Passphrase for keystore: It will sign your apk.To verify that the signing is successful you can run:

jarsigner -verify c:\users\pir fahim\Desktops\GoogleDriveApp.apk

It should come back with: jar verified.

Method 2

If you are using eclipse with ADT, then it is simple to compiled, signed, aligned, and ready the file for distribution.what you have to do just follow this steps.

  • File > Export.
  • Export android application
  • Browse-->select your project
  • Next-->Next

These steps will compiled, signed and zip aligned your project and now you are ready to distribute your project or upload at Google Play store.

How to use JavaScript source maps (.map files)?

Just to add to how to use map files. I use chrome for ubuntu and if I go to sources and click on a file, if there is a map file a message comes up telling me that I can view the original file and how to do it.

For the Angular files that I worked with today I click

Ctrl-P and a list of original files comes up in a small window.

I can then browse through the list to view the file that I would like to inspect and check where the issue might be.

How to make an Asynchronous Method return a value?

There are a few ways of doing that... the simplest is to have the async method also do the follow-on operation. Another popular approach is to pass in a callback, i.e.

void RunFooAsync(..., Action<bool> callback) {
     // do some stuff
     bool result = ...

     if(callback != null) callback(result);
}

Another approach would be to raise an event (with the result in the event-args data) when the async operation is complete.

Also, if you are using the TPL, you can use ContinueWith:

Task<bool> outerTask = ...;
outerTask.ContinueWith(task =>
{
    bool result = task.Result;
    // do something with that
});

How to get text from each cell of an HTML table?

$content = '';
    for($rowth=0; $rowth<=100; $rowth++){
        $content .= $selenium->getTable("tblReports.{$rowth}.0") . "\n";
        //$content .= $selenium->getTable("tblReports.{$rowth}.1") . "\n";
        $content .= $selenium->getTable("tblReports.{$rowth}.2") . " ";
        $content .= $selenium->getTable("tblReports.{$rowth}.3") . " ";
        $content .= $selenium->getTable("tblReports.{$rowth}.4") . " ";
        $content .= $selenium->getTable("tblReports.{$rowth}.5") . " ";
        $content .= $selenium->getTable("tblReports.{$rowth}.6") . "\n";

    }

Python: How to check if keys exists and retrieve value from Dictionary in descending priority

Use .get(), which if the key is not found, returns None.

for i in keySet:
    temp = myDict.get(i)
    if temp is not None:
        print temp
        break

How do I set default value of select box in angularjs

As per the docs select, the following piece of code worked for me.

<div ng-controller="ExampleController">
<form name="myForm">
<label for="mySelect">Make a choice:</label>
<select name="mySelect" id="mySelect"
  ng-options="option.name for option in data.availableOptions track by     option.id"
  ng-model="data.selectedOption"></select>
</form>
<hr>
<tt>option = {{data.selectedOption}}</tt><br/>
</div>

how to implement regions/code collapse in javascript

Microsoft now has an extension for VS 2010 that provides this functionality:

JScript Editor Extensions

Rails: Adding an index after adding column

For references you can call

rails generate migration AddUserIdColumnToTable user:references

If in the future you need to add a general index you can launch this

rails g migration AddOrdinationNumberToTable ordination_number:integer:index

Generate code:

class AddOrdinationNumberToTable < ActiveRecord::Migration
  def change
   add_column :tables, :ordination_number, :integer
   add_index :tables, :ordination_number, unique: true
  end
end

Subversion stuck due to "previous operation has not finished"?

I had tried the most voted answers here and a few others to no avail. My WORK_QUEUE table was empty and I wasn't able to try a clean up at a higher folder. What did work was the following (this is via Tortoise SVN);

  • Right click on folder
  • Go to TortoiseSVN -> Clean Up...
  • Make sure the option to Break Locks is ticked and click OK

The Clean Up operation now completes successfully and I can continue. No downloading of sqlite3 or other convoluted solutions required.

error: command 'gcc' failed with exit status 1 while installing eventlet

if you are on Mac as myself, try in terminal: xcode-select --install

Then accept the installation request, then it works afterward https://github.com/python-pillow/Pillow/issues/3438

Error: The type exists in both directories

I fixed this by checking Delete all existing files prior to publish in Visual Studio:

enter image description here

Python object deleting itself

Indeed, Python does garbage collection through reference counting. As soon as the last reference to an object falls out of scope, it is deleted. In your example:

a = A()
a.kill()

I don't believe there's any way for variable 'a' to implicitly set itself to None.

How to use jQuery Plugin with Angular 4?

ngOnInit() {
     const $ = window["$"];
     $('.flexslider').flexslider({
        animation: 'slide',
        start: function (slider) {
          $('body').removeClass('loading')
        }
     })
}

FFMPEG mp4 from http live streaming m3u8 file?

Aergistal's answer works, but I found that converting to mp4 can make some m3u8 videos broken. If you are stuck with this problem, try to convert them to mkv, and convert them to mp4 later.

Java: Add elements to arraylist with FOR loop where element name has increasing number

Thomas's solution is good enough for this matter.

If you want to use loop to access these three Answers, you first need to put there three into an array-like data structure ---- kind of like a principle. So loop is used for operating on an array-like data structure, not just simply to simplify typing task. And you cannot use FOR loop by simply just giving increasing-number-names to the elements.

Git push results in "Authentication Failed"

Just to chime in here, what fixed the issue for me was I simply canceled out of the initial prompt, the ssh one opened up with my bitbucket account, I entered the password there and everything worked as expected.

How many bytes in a JavaScript string?

String values are not implementation dependent, according the ECMA-262 3rd Edition Specification, each character represents a single 16-bit unit of UTF-16 text:

4.3.16 String Value

A string value is a member of the type String and is a finite ordered sequence of zero or more 16-bit unsigned integer values.

NOTE Although each value usually represents a single 16-bit unit of UTF-16 text, the language does not place any restrictions or requirements on the values except that they be 16-bit unsigned integers.

Add one day to date in javascript

The Date constructor that takes a single number is expecting the number of milliseconds since December 31st, 1969.

Date.getDate() returns the day index for the current date object. In your example, the day is 30. The final expression is 31, therefore it's returning 31 milliseconds after December 31st, 1969.

A simple solution using your existing approach is to use Date.getTime() instead. Then, add a days worth of milliseconds instead of 1.

For example,

var dateString = 'Mon Jun 30 2014 00:00:00';

var startDate = new Date(dateString);

// seconds * minutes * hours * milliseconds = 1 day 
var day = 60 * 60 * 24 * 1000;

var endDate = new Date(startDate.getTime() + day);

JSFiddle

Please note that this solution doesn't handle edge cases related to daylight savings, leap years, etc. It is always a more cost effective approach to instead, use a mature open source library like moment.js to handle everything.

How to show the "Are you sure you want to navigate away from this page?" when changes committed?

jquerys 'beforeunload' worked great for me

$(window).bind('beforeunload', function(){
    if( $('input').val() !== '' ){
        return "It looks like you have input you haven't submitted."
    }
});

Remove duplicates from dataframe, based on two columns A,B, keeping row with max value in another column C

I think groupby should work.

df.groupby(['A', 'B']).max()['C']

If you need a dataframe back you can chain the reset index call.

df.groupby(['A', 'B']).max()['C'].reset_index()

PHP Warning: Division by zero

when my divisor has 0 value

if ($divisor == 0) {
    $divisor = 1;
}

How to delete a file from SD card?

Also you have to give permission if you are using >1.6 SDK

uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"

in AndroidManifest.xml file

Java String to Date object of the format "yyyy-mm-dd HH:mm:ss"

tl;dr

LocalDateTime.parse( 
    "2012-07-10 14:58:00.000000".replace( " " , "T" )  
)

Microseconds do not fit

You are attempting to squeeze a value with microseconds (six decimal digits) into a data type capable only of milliseconds resolution (three decimal digits). That is impossible.

Instead, use a data type with fine enough resolution. The java.time classes use nanosecond resolution (nine decimal digits).

Unzoned input does not fit a zoned type

You are attempting to put a value lacking any offset-from-UTC or time zone into a data type (Date) that only represents values in UTC. So you are adding information (UTC offset) not intended by the input.

Use an appropriate data type instead. Specifically, java.time.LocalDateTime.

Case-sensitive

Other Answers and Comments correctly explain that the formatting pattern codes are case-sensitive. So MM and mm have different effects.

Avoid legacy classes

The troublesome old date-time classes bundled with the earliest versions of Java are now legacy, supplanted by the java.time classes built into Java 8 and later.

ISO 8601

Your input strings nearly comply with the ISO 8601 standard formats. Replace the SPACE in the middle with a T to comply fully.

The java.time classes use the standard formats by default when parsing/generating strings. So no need to specify a formatting pattern.

Date-time objects have no "format"

and I need the resultant date object to be of the same format.

No, date-time objects do not have a "format". Do not conflate date-time objects with mere strings. Strings are inputs and outputs of the objects. The objects maintain their own internal representions of the date-time info, the details of which are irrelevant to us as calling programmers.

java.time

Your input lacks any indicator of offset-from-UTC or troublesome me zone. So we parse as a LocalDateTime objects which lacks those concepts.

String input = "2012-07-10 14:58:00.000000".replace( " " , "T" ) ;
LocalDateTime ldt = LocalDateTime.parse( input ) ;

Generating strings

To generate a String representing the value of your LocalDateTime:

  • Call toString to get a String in standard ISO 8601 format.
  • Use DateTimeFormatter for producing strings in either custom formats or automatically-localized formats.

Search Stack Overflow for more info as these topics have been covered many many times already.

ZonedDateTime

A LocalDateTime does not represent an exact point on the timeline.

To determine an actual moment, assign a time zone. For example noon in Kolkata India comes much earlier than noon in Paris France. Noon without a time zone could be happening at any point over a range of about 26-27 hours.

ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

logout and redirecting session in php

Only this is necessary

session_start();
unset($_SESSION["nome"]);  // where $_SESSION["nome"] is your own variable. if you do not have one use only this as follow **session_unset();**
header("Location: home.php");

JQuery Find #ID, RemoveClass and AddClass

corrected Code:

jQuery('#testID2').addClass('test3').removeClass('test2');

How do you log all events fired by an element in jQuery?

I recently found and modified this snippet from an existing SO post that I have not been able to find again but I've found it very useful

// specify any elements you've attached listeners to here
const nodes = [document]

// https://developer.mozilla.org/en-US/docs/Web/Events
const logBrowserEvents = () => {
  const AllEvents = {
    AnimationEvent: ['animationend', 'animationiteration', 'animationstart'],
    AudioProcessingEvent: ['audioprocess'],
    BeforeUnloadEvent: ['beforeunload'],
    CompositionEvent: [
      'compositionend',
      'compositionstart',
      'compositionupdate',
    ],
    ClipboardEvent: ['copy', 'cut', 'paste'],
    DeviceLightEvent: ['devicelight'],
    DeviceMotionEvent: ['devicemotion'],
    DeviceOrientationEvent: ['deviceorientation'],
    DeviceProximityEvent: ['deviceproximity'],
    DragEvent: [
      'drag',
      'dragend',
      'dragenter',
      'dragleave',
      'dragover',
      'dragstart',
      'drop',
    ],
    Event: [
      'DOMContentLoaded',
      'abort',
      'afterprint',
      'beforeprint',
      'cached',
      'canplay',
      'canplaythrough',
      'change',
      'chargingchange',
      'chargingtimechange',
      'checking',
      'close',
      'dischargingtimechange',
      'downloading',
      'durationchange',
      'emptied',
      'ended',
      'error',
      'fullscreenchange',
      'fullscreenerror',
      'input',
      'invalid',
      'languagechange',
      'levelchange',
      'loadeddata',
      'loadedmetadata',
      'noupdate',
      'obsolete',
      'offline',
      'online',
      'open',
      'open',
      'orientationchange',
      'pause',
      'play',
      'playing',
      'pointerlockchange',
      'pointerlockerror',
      'ratechange',
      'readystatechange',
      'reset',
      'seeked',
      'seeking',
      'stalled',
      'submit',
      'success',
      'suspend',
      'timeupdate',
      'updateready',
      'visibilitychange',
      'volumechange',
      'waiting',
    ],
    FocusEvent: [
      'DOMFocusIn',
      'DOMFocusOut',
      'Unimplemented',
      'blur',
      'focus',
      'focusin',
      'focusout',
    ],
    GamepadEvent: ['gamepadconnected', 'gamepaddisconnected'],
    HashChangeEvent: ['hashchange'],
    KeyboardEvent: ['keydown', 'keypress', 'keyup'],
    MessageEvent: ['message'],
    MouseEvent: [
      'click',
      'contextmenu',
      'dblclick',
      'mousedown',
      'mouseenter',
      'mouseleave',
      'mousemove',
      'mouseout',
      'mouseover',
      'mouseup',
      'show',
    ],
    // https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Mutation_events
    MutationNameEvent: ['DOMAttributeNameChanged', 'DOMElementNameChanged'],
    MutationEvent: [
      'DOMAttrModified',
      'DOMCharacterDataModified',
      'DOMNodeInserted',
      'DOMNodeInsertedIntoDocument',
      'DOMNodeRemoved',
      'DOMNodeRemovedFromDocument',
      'DOMSubtreeModified',
    ],
    OfflineAudioCompletionEvent: ['complete'],
    OtherEvent: ['blocked', 'complete', 'upgradeneeded', 'versionchange'],
    UIEvent: [
      'DOMActivate',
      'abort',
      'error',
      'load',
      'resize',
      'scroll',
      'select',
      'unload',
    ],
    PageTransitionEvent: ['pagehide', 'pageshow'],
    PopStateEvent: ['popstate'],
    ProgressEvent: [
      'abort',
      'error',
      'load',
      'loadend',
      'loadstart',
      'progress',
    ],
    SensorEvent: ['compassneedscalibration', 'Unimplemented', 'userproximity'],
    StorageEvent: ['storage'],
    SVGEvent: [
      'SVGAbort',
      'SVGError',
      'SVGLoad',
      'SVGResize',
      'SVGScroll',
      'SVGUnload',
    ],
    SVGZoomEvent: ['SVGZoom'],
    TimeEvent: ['beginEvent', 'endEvent', 'repeatEvent'],
    TouchEvent: [
      'touchcancel',
      'touchend',
      'touchenter',
      'touchleave',
      'touchmove',
      'touchstart',
    ],
    TransitionEvent: ['transitionend'],
    WheelEvent: ['wheel'],
  }

  const RecentlyLoggedDOMEventTypes = {}

  Object.keys(AllEvents).forEach((DOMEvent) => {
    const DOMEventTypes = AllEvents[DOMEvent]

    if (Object.prototype.hasOwnProperty.call(AllEvents, DOMEvent)) {
      DOMEventTypes.forEach((DOMEventType) => {
        const DOMEventCategory = `${DOMEvent} ${DOMEventType}`

        nodes.forEach((node) => {
          node.addEventListener(
            DOMEventType,
            (e) => {
              if (RecentlyLoggedDOMEventTypes[DOMEventCategory]) return

              RecentlyLoggedDOMEventTypes[DOMEventCategory] = true

              // NOTE: throttle continuous events
              setTimeout(() => {
                RecentlyLoggedDOMEventTypes[DOMEventCategory] = false
              }, 1000)

              const isActive = e.target === document.activeElement

              // https://developer.mozilla.org/en-US/docs/Web/API/DocumentOrShadowRoot/activeElement
              const hasActiveElement = document.activeElement !== document.body

              const msg = [
                DOMEventCategory,
                'target:',
                e.target,
                ...(hasActiveElement
                  ? ['active:', document.activeElement]
                  : []),
              ]

              if (isActive) {
                console.info(...msg)
              }
            },
            true,
          )
        })
      })
    }
  })
}
logBrowserEvents()
// export default logBrowserEvents

Time in milliseconds in C

Yes, this program has likely used less than a millsecond. Try using microsecond resolution with timeval.

e.g:

#include <sys/time.h>

struct timeval stop, start;
gettimeofday(&start, NULL);
//do stuff
gettimeofday(&stop, NULL);
printf("took %lu us\n", (stop.tv_sec - start.tv_sec) * 1000000 + stop.tv_usec - start.tv_usec); 

You can then query the difference (in microseconds) between stop.tv_usec - start.tv_usec. Note that this will only work for subsecond times (as tv_usec will loop). For the general case use a combination of tv_sec and tv_usec.

Edit 2016-08-19

A more appropriate approach on system with clock_gettime support would be:

struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC_RAW, &start);
//do stuff
clock_gettime(CLOCK_MONOTONIC_RAW, &end);

uint64_t delta_us = (end.tv_sec - start.tv_sec) * 1000000 + (end.tv_nsec - start.tv_nsec) / 1000;

css absolute position won't work with margin-left:auto margin-right: auto

EDIT : this answer used to claim that it isn't possible to center an absolutely positioned element with margin: auto;, but this simply isn't true. Because this is the most up-voted and accepted answer, I guessed I'd just change it to be correct.

When you apply the following CSS to an element

position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;

And then give the element a fixed width and height, such as 200px or 40%, the element will center itself.

Here's a Fiddle that demonstrates the effect.

How to watch for a route change in AngularJS?

If you don't want to place the watch inside a specific controller, you can add the watch for the whole aplication in Angular app run()

var myApp = angular.module('myApp', []);

myApp.run(function($rootScope) {
    $rootScope.$on("$locationChangeStart", function(event, next, current) { 
        // handle route changes     
    });
});

How to validate an Email in PHP?

I always use this:

function validEmail($email){
    // First, we check that there's one @ symbol, and that the lengths are right
    if (!preg_match("/^[^@]{1,64}@[^@]{1,255}$/", $email)) {
        // Email invalid because wrong number of characters in one section, or wrong number of @ symbols.
        return false;
    }
    // Split it into sections to make life easier
    $email_array = explode("@", $email);
    $local_array = explode(".", $email_array[0]);
    for ($i = 0; $i < sizeof($local_array); $i++) {
        if (!preg_match("/^(([A-Za-z0-9!#$%&'*+\/=?^_`{|}~-][A-Za-z0-9!#$%&'*+\/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$/", $local_array[$i])) {
            return false;
        }
    }
    if (!preg_match("/^\[?[0-9\.]+\]?$/", $email_array[1])) { // Check if domain is IP. If not, it should be valid domain name
        $domain_array = explode(".", $email_array[1]);
        if (sizeof($domain_array) < 2) {
            return false; // Not enough parts to domain
        }
        for ($i = 0; $i < sizeof($domain_array); $i++) {
            if (!preg_match("/^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$/", $domain_array[$i])) {
                return false;
            }
        }
    }

    return true;
}

How to build an APK file in Eclipse?

The APK file is in the /workspace/PROJECT_FOLDER/bin directory. To install the APK file in a real device:

  1. Connect your real device with a PC/laptop.

  2. Go to sdk/tools/ using a terminal or command prompt.

  3. adb install <FILE PATH OF .APK FILE>

That's it...

Javascript loading CSV file into an array

If your not overly worried about the size of the file then it may be easier for you to store the data as a JS object in another file and import it in your . Either synchronously or asynchronously using the syntax <script src="countries.js" async></script>. Saves on you needing to import the file and parse it.

However, i can see why you wouldnt want to rewrite 10000 entries so here's a basic object orientated csv parser i wrote.

function requestCSV(f,c){return new CSVAJAX(f,c);};
function CSVAJAX(filepath,callback)
{
    this.request = new XMLHttpRequest();
    this.request.timeout = 10000;
    this.request.open("GET", filepath, true);
    this.request.parent = this;
    this.callback = callback;
    this.request.onload = function() 
    {
        var d = this.response.split('\n'); /*1st separator*/
        var i = d.length;
        while(i--)
        {
            if(d[i] !== "")
                d[i] = d[i].split(','); /*2nd separator*/
            else
                d.splice(i,1);
        }
        this.parent.response = d;
        if(typeof this.parent.callback !== "undefined")
            this.parent.callback(d);
    };
    this.request.send();
};

Which can be used like this;

var foo = requestCSV("csvfile.csv",drawlines(lines)); 

The first parameter is the file, relative to the position of your html file in this case. The second parameter is an optional callback function the runs when the file has been completely loaded.

If your file has non-separating commmas then it wont get on with this, as it just creates 2d arrays by chopping at returns and commas. You might want to look into regexp if you need that functionality.

//THIS works 

"1234","ABCD" \n
"!@£$" \n

//Gives you 
[
 [
  1234,
  'ABCD'
 ],
 [
  '!@£$'
 ]
]

//This DOESN'T!

"12,34","AB,CD" \n
"!@,£$" \n

//Gives you

[
 [
  '"12',
  '34"',
  '"AB',
  'CD'
 ]
 [
  '"!@',
  '£$'
 ]
]

If your not used to the OO methods; they create a new object (like a number, string, array) with their own local functions and variables via a 'constructor' function. Very handy in certain situations. This function could be used to load 10 different files with different callbacks all at the same time(depending on your level of csv love! )

How to stop/kill a query in postgresql?

What I did is first check what are the running processes by

SELECT * FROM pg_stat_activity WHERE state = 'active';

Find the process you want to kill, then type:

SELECT pg_cancel_backend(<pid of the process>)

This basically "starts" a request to terminate gracefully, which may be satisfied after some time, though the query comes back immediately.

If the process cannot be killed, try:

SELECT pg_terminate_backend(<pid of the process>)

Angular CLI SASS options

Angular-CLI is the recommended method and is the standard in the Angular 2+ community.

Crete a new project with SCSS

ng new My-New-Project --style=sass

Convert an existing project (CLI less than v6)

ng set defaults.styleExt scss

(must rename all .css files manually with this approach, don't forget to rename in your component files)


Convert an existing project (CLI greater than v6)

  1. rename all CSS files to SCSS and update components that reference them.
  2. add the following to the "schematics" key of angular.json (usually line 11):

"@schematics/angular:component": { "styleext": "sass" }

how can I display tooltip or item information on mouse over?

The simplest way to get tooltips in most browsers is to set some text in the title attribute.

eg.

<img src="myimage.jpg" alt="a cat" title="My cat sat on a table" />

produces (hover your mouse over the image):

a cat http://www.imagechicken.com/uploads/1275939952008633500.jpg

Title attributes can be applied to most HTML elements.

How to change position of Toast in Android?

From the documentation,

Positioning your Toast

A standard toast notification appears near the bottom of the screen, centered horizontally. You can change this position with the setGravity(int, int, int) method. This accepts three parameters: a Gravity constant, an x-position offset, and a y-position offset.

For example, if you decide that the toast should appear in the top-left corner, you can set the gravity like this:

toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);

If you want to nudge the position to the right, increase the value of the second parameter. To nudge it down, increase the value of the last parameter.

retrieve data from db and display it in table in php .. see this code whats wrong with it?

Here is the solution total html with php and database connections

   <!doctype html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>database connections</title>
    </head>
    <body>
      <?php
      $username = "database-username";
      $password = "database-password";
      $host = "localhost";

      $connector = mysql_connect($host,$username,$password)
          or die("Unable to connect");
        echo "Connections are made successfully::";
      $selected = mysql_select_db("test_db", $connector)
        or die("Unable to connect");

      //execute the SQL query and return records
      $result = mysql_query("SELECT * FROM table_one ");
      ?>
      <table border="2" style= "background-color: #84ed86; color: #761a9b; margin: 0 auto;" >
      <thead>
        <tr>
          <th>Employee_id</th>
          <th>Employee_Name</th>
          <th>Employee_dob</th>
          <th>Employee_Adress</th>
          <th>Employee_dept</th>
          <td>Employee_salary</td>
        </tr>
      </thead>
      <tbody>
        <?php
          while( $row = mysql_fetch_assoc( $result ) ){
            echo
            "<tr>
              <td>{$row\['employee_id'\]}</td>
              <td>{$row\['employee_name'\]}</td>
              <td>{$row\['employee_dob'\]}</td>
              <td>{$row\['employee_addr'\]}</td>
              <td>{$row\['employee_dept'\]}</td>
              <td>{$row\['employee_sal'\]}</td> 
            </tr>\n";
          }
        ?>
      </tbody>
    </table>
     <?php mysql_close($connector); ?>
    </body>
    </html>

Functional style of Java 8's Optional.ifPresent and if-not-Present?

In case you want store the value:

Pair.of<List<>, List<>> output = opt.map(details -> Pair.of(details.a, details.b))).orElseGet(() -> Pair.of(Collections.emptyList(), Collections.emptyList()));

How do I share variables between different .c files?

Those other variables would have to be declared public (use extern, public is for C++), and you would have to include that .c file. However, I recommend creating appropriate .h files to define all of your variables.

For example, for hello.c, you would have a hello.h, and hello.h would store your variable definitions. Then another .c file, such as world.c would have this piece of code at the top:

#include "hello.h"

That will allow world.c to use variables that are defined in hello.h

It's slightly more complicated than that though. You may use < > to include library files found on your OS's path. As a beginner I would stick all of your files in the same folder and use the " " syntax.

SimpleXML - I/O warning : failed to load external entity

this also works:

$url = "http://www.some-url";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$xmlresponse = curl_exec($ch);
$xml=simplexml_load_string($xmlresponse);

then I just run a forloop to grab the stuff from the nodes.

like this:`

for($i = 0; $i < 20; $i++) {
$title = $xml->channel->item[$i]->title;
$link = $xml->channel->item[$i]->link;
$desc = $xml->channel->item[$i]->description;
$html .="<div><h3>$title</h3>$link<br />$desc</div><hr>";
}
echo $html;

***note that your node names will differ, obviously..and your HTML might be structured differently...also your loop might be set to higher or lower amount of results.

Should __init__() call the parent class's __init__()?

If you need something from super's __init__ to be done in addition to what is being done in the current class's __init__, you must call it yourself, since that will not happen automatically. But if you don't need anything from super's __init__, no need to call it. Example:

>>> class C(object):
        def __init__(self):
            self.b = 1


>>> class D(C):
        def __init__(self):
            super().__init__() # in Python 2 use super(D, self).__init__()
            self.a = 1


>>> class E(C):
        def __init__(self):
            self.a = 1


>>> d = D()
>>> d.a
1
>>> d.b  # This works because of the call to super's init
1
>>> e = E()
>>> e.a
1
>>> e.b  # This is going to fail since nothing in E initializes b...
Traceback (most recent call last):
  File "<pyshell#70>", line 1, in <module>
    e.b  # This is going to fail since nothing in E initializes b...
AttributeError: 'E' object has no attribute 'b'

__del__ is the same way, (but be wary of relying on __del__ for finalization - consider doing it via the with statement instead).

I rarely use __new__. I do all the initialization in __init__.

Adding n hours to a date in Java?

If you use Apache Commons / Lang, you can do it in one step using DateUtils.addHours():

Date newDate = DateUtils.addHours(oldDate, 3);

(The original object is unchanged)

How to set a default value for an existing column

First drop constraints

https://stackoverflow.com/a/49393045/2547164

DECLARE @ConstraintName nvarchar(200)
SELECT @ConstraintName = Name FROM SYS.DEFAULT_CONSTRAINTS
WHERE PARENT_OBJECT_ID = OBJECT_ID('__TableName__')
AND PARENT_COLUMN_ID = (SELECT column_id FROM sys.columns
                        WHERE NAME = N'__ColumnName__'
                        AND object_id = OBJECT_ID(N'__TableName__'))
IF @ConstraintName IS NOT NULL
EXEC('ALTER TABLE __TableName__ DROP CONSTRAINT ' + @ConstraintName)

Second create default value

ALTER TABLE [table name] ADD DEFAULT [default value] FOR [column name]

Cannot connect to repo with TortoiseSVN

Run ipconfig /flushdns from a command prompt. Apparently some people seem to think I posted this answer for sheer fun. That's why they down voted my answer. Perhaps an explanation would help them. When I used "SVN Update" it said it can't connect to the SVN repository although I could ping the server. After running ipconfig /flushdns the issue was fixed.

Getting a better understanding of callback functions in JavaScript

You can just say

callback();

Alternately you can use the call method if you want to adjust the value of this within the callback.

callback.call( newValueForThis);

Inside the function this would be whatever newValueForThis is.

Why can't I duplicate a slice with `copy()`?

NOTE: This is an incorrect solution as @benlemasurier proved

Here is a way to copy a slice. I'm a bit late, but there is a simpler, and faster answer than @Dave's. This are the instructions generated from a code like @Dave's. These is the instructions generated by mine. As you can see there are far fewer instructions. What is does is it just does append(slice), which copies the slice. This code:

package main

import "fmt"

func main() {
    var foo = []int{1, 2, 3, 4, 5}
    fmt.Println("foo:", foo)
    var bar = append(foo)
    fmt.Println("bar:", bar)
    bar = append(bar, 6)
    fmt.Println("foo after:", foo)
    fmt.Println("bar after:", bar)
}

Outputs this:

foo: [1 2 3 4 5]
bar: [1 2 3 4 5]
foo after: [1 2 3 4 5]
bar after: [1 2 3 4 5 6]

Why an interface can not implement another interface?

Interface is the class that contains an abstract method that cannot create any object.Since Interface cannot create the object and its not a pure class, Its no worth implementing it.

NavigationBar bar, tint, and title text color in iOS 8

To do this job in storyboard (Interface Builder Inspector)

With help of IBDesignable, we can add more options to Interface Builder Inspector for UINavigationController and tweak them on storyboard. First, add the following code to your project.

@IBDesignable extension UINavigationController {
    @IBInspectable var barTintColor: UIColor? {
        set {
            navigationBar.barTintColor = newValue
        }
        get {
            guard  let color = navigationBar.barTintColor else { return nil }
            return color
        }
    }

    @IBInspectable var tintColor: UIColor? {
        set {
            navigationBar.tintColor = newValue
        }
        get {
            guard  let color = navigationBar.tintColor else { return nil }
            return color
        }
    }

    @IBInspectable var titleColor: UIColor? {
        set {
            guard let color = newValue else { return }
            navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: color]
        }
        get {
            return navigationBar.titleTextAttributes?["NSForegroundColorAttributeName"] as? UIColor
        }
    }
}

Then simply set the attributes for UINavigationController on storyboard.

enter image description here

Real-world examples of recursion

People often sort stacks of documents using a recursive method. For example, imagine you are sorting 100 documents with names on them. First place documents into piles by the first letter, then sort each pile.

Looking up words in the dictionary is often performed by a binary-search-like technique, which is recursive.

In organizations, bosses often give commands to department heads, who in turn give commands to managers, and so on.

How to set the holo dark theme in a Android app?

In your application android manifest file, under the application tag you can try several of these themes.

Replace

<application
    android:theme="@style/AppTheme" >

with different themes defined by the android system. They can be like:-

android:theme="@android:style/Theme.Black"
android:theme="@android:style/Theme.DeviceDefault"
android:theme="@android:style/Theme.DeviceDefault.Dialog"
android:theme="@android:style/Theme.Holo"
android:theme="@android:style/Theme.Translucent"

Each of these themes will have a different effect on your application like the DeviceDefault.Dialog will make your application look like a dialog box. You should try more of these. You can have a look from the android sdk or simply use auto complete in Eclipse IDE to explore the various available options.

A correct way to define your own theme would be to edit the styles.xml file present in the resources folder of your application.

How do I check if a cookie exists?

/// ************************************************ cookie_exists

/// global entry point, export to global namespace

/// <synopsis>
///   cookie_exists ( name );
///
/// <summary>
///   determines if a cookie with name exists
///
/// <param name="name">
///   string containing the name of the cookie to test for 
//    existence
///
/// <returns>
///   true, if the cookie exists; otherwise, false
///
/// <example>
///   if ( cookie_exists ( name ) );
///     {
///     // do something with the existing cookie
///     }
///   else
///     {
///     // cookies does not exist, do something else 
///     }

function cookie_exists ( name )
  {
  var exists = false;

  if ( document.cookie )
    {
    if ( document.cookie.length > 0 )
      {
                                    // trim name
      if ( ( name = name.replace ( /^\s*/, "" ).length > 0 ) )
        {
        var cookies = document.cookie.split ( ";" );
        var name_with_equal = name + "=";

        for ( var i = 0; ( i < cookies.length ); i++ )
          {
                                    // trim cookie
          var cookie = cookies [ i ].replace ( /^\s*/, "" );

          if ( cookie.indexOf ( name_with_equal ) === 0 )
            {
            exists = true;
            break;
            }
          }
        }
      }
    }

  return ( exists );

  } // cookie_exists

PHP Fatal error: Call to undefined function mssql_connect()

I have just tried to install that extension on my dev server.

First, make sure that the extension is correctly enabled. Your phpinfo() output doesn't seem complete.

If it is indeed installed properly, your phpinfo() should have a section that looks like this: enter image description here

If you do not get that section in your phpinfo(). Make sure that you are using the right version. There are both non-thread-safe and thread-safe versions of the extension.

Finally, check your extension_dir setting. By default it's this: extension_dir = "ext", for most of the time it works fine, but if it doesn't try: extension_dir = "C:\PHP\ext".

===========================================================================

EDIT given new info:

You are using the wrong function. mssql_connect() is part of the Mssql extension. You are using microsoft's extension, so use sqlsrv_connect(), for the API for the microsoft driver, look at SQLSRV_Help.chm which should be extracted to your ext directory when you extracted the extension.

Excel Validation Drop Down list using VBA

Private Sub main()

'replace "J2" with the cell you want to insert the drop down list
With Range("J2").Validation
    .Delete
    'replace "=A1:A6" with the range the data is in.
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
    Operator:=xlBetween, Formula1:="=Sheet1!A1:A6"
    .IgnoreBlank = True
    .InCellDropdown = True
    .InputTitle = ""
    .ErrorTitle = ""
    .InputMessage = ""
    .ErrorMessage = ""
    .ShowInput = True
    .ShowError = True
End With
End Sub

Height of status bar in Android

Try this:

    Rect rect = new Rect();
    Window win = this.getWindow();
    win.getDecorView().getWindowVisibleDisplayFrame(rect);
    int statusBarHeight = rect.top;
    int contentViewTop = win.findViewById(Window.ID_ANDROID_CONTENT).getTop();
    int titleBarHeight = contentViewTop - statusBarHeight;
    Log.d("ID-ANDROID-CONTENT", "titleBarHeight = " + titleBarHeight );

it didn't work for me in the onCreate method for the activity, but did when I put it in an onClickListener and gave me a measurement of 25

Mockito matcher and array of primitives

I used Matchers.refEq for this.

TypeError: no implicit conversion of Symbol into Integer

Your item variable holds Array instance (in [hash_key, hash_value] format), so it doesn't expect Symbol in [] method.

This is how you could do it using Hash#each:

def format(hash)
  output = Hash.new
  hash.each do |key, value|
    output[key] = cleanup(value)
  end
  output
end

or, without this:

def format(hash)
  output = hash.dup
  output[:company_name] = cleanup(output[:company_name])
  output[:street] = cleanup(output[:street])
  output
end

"commence before first target. Stop." error

if you have added a new line, Make sure you have added next line syntax in previous line. typically if "\" is missing in your previous line of changes, you will get this error.

Getting XML Node text value with Java DOM

I use a very old java. Jdk 1.4.08 and I had the same issue. The Node class for me did not had the getTextContent() method. I had to use Node.getFirstChild().getNodeValue() instead of Node.getNodeValue() to get the value of the node. This fixed for me.

script to map network drive

use the net use command:

net use Z: \\10.0.1.1\DRIVENAME

Edit 1: Also, I believe the password should be simply appended:

net use Z: \\10.0.1.1\DRIVENAME PASSWORD

You can find out more about this command and its arguments via:

net use ?

Edit 2: As Tomalak mentioned in comments, you can later un-map it via

net use Z: \delete

Getting the client IP address: REMOTE_ADDR, HTTP_X_FORWARDED_FOR, what else could be useful?

It depends on the nature of your site.

I happen to work on a bit of software where IP tracking is important, and within a field consumed by parter sites I'd guess some 20% - 40% of requests are either detectably spoofed IPs or headers blanked out, depending on the time of day and where they came from. For a site which gets organic traffic (i.e. not through partners) I'd expect a much higher ratio of good IPs.

As Kosi said, be careful what you're doing with this - IPs are in no way a reliable way to identify unique visitors.

Putty: Getting Server refused our key Error

I have this issue where sshd only reads from authorized_keys2.

Copying or renaming the file fixed the problem for me.

cd  ~/.ssh
sudo cat authorized_keys >> authorized_keys2

P.S. I'm using Putty from Windows and used PuTTyKeygen for key pair generation.

Is returning out of a switch statement considered a better practice than using break?

It depends, if your function only consists of the switch statement, then I think that its fine. However, if you want to perform any other operations within that function, its probably not a great idea. You also may have to consider your requirements right now versus in the future. If you want to change your function from option one to option two, more refactoring will be needed.

However, given that within if/else statements it is best practice to do the following:

var foo = "bar";

if(foo == "bar") {
    return 0;
}
else {
    return 100;
}

Based on this, the argument could be made that option one is better practice.

In short, there's no clear answer, so as long as your code adheres to a consistent, readable, maintainable standard - that is to say don't mix and match options one and two throughout your application, that is the best practice you should be following.

What is and how to fix System.TypeInitializationException error?

System.TypeInitializationException happens when the code that gets executed during the process of loading the type throws an exception.

When .NET loads the type, it must prepare all its static fields before the first time that you use the type. Sometimes, initialization requires running code. It is when that code fails that you get a System.TypeInitializationException.

In your specific case, the following three static fields run some code:

private static string s_bstCommonAppData = Path.Combine(s_commonAppData, "XXXX");
private static string s_bstUserDataDir = Path.Combine(s_bstCommonAppData, "UserData");
private static string s_commonAppData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);

Note that s_bstCommonAppData depends on s_commonAppData, but it is declared ahead of its dependency. Therefore, the value of s_commonAppData is null at the time that the Path.Combine is called, resulting in ArgumentNullException. Same goes for the s_bstUserDataDir and s_bstCommonAppData: they are declared in reverse order to the desired order of initialization.

Re-order the lines to fix this problem:

private static string s_commonAppData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
private static string s_bstCommonAppData = Path.Combine(s_commonAppData, "XXXX");
private static string s_bstUserDataDir = Path.Combine(s_bstCommonAppData, "UserData");

Most efficient way to concatenate strings in JavaScript?

You can also do string concat with template literals. I updated the other posters' JSPerf tests to include it.

for (var res = '', i = 0; i < data.length; i++) {
  res = `${res}${data[i]}`;
}

How exactly to use Notification.Builder

In case it helps anyone... I was having a lot of trouble with setting up notifications using the support package when testing against newer an older API's. I was able to get them to work on the newer device but would get an error testing on the old device. What finally got it working for me was to delete all the imports related to the notification functions. In particular the NotificationCompat and the TaskStackBuilder. It seems that while setting up my code in the beginning the imports where added from the newer build and not from the support package. Then when I wanted to implement these items later in eclipse, I wasn't prompted to import them again. Hope that makes sense, and that it helps someone else out :)

Comprehensive methods of viewing memory usage on Solaris

Here are the basics. I'm not sure that any of these count as "clear and simple" though.

ps(1)

For process-level view:

$ ps -opid,vsz,rss,osz,args
  PID  VSZ  RSS   SZ COMMAND
 1831 1776 1008  222 ps -opid,vsz,rss,osz,args
 1782 3464 2504  433 -bash
$

vsz/VSZ: total virtual process size (kb)

rss/RSS: resident set size (kb, may be inaccurate(!), see man)

osz/SZ: total size in memory (pages)

To compute byte size from pages:

$ sz_pages=$(ps -o osz -p $pid | grep -v SZ )
$ sz_bytes=$(( $sz_pages * $(pagesize) ))
$ sz_mbytes=$(( $sz_bytes / ( 1024 * 1024 ) ))
$ echo "$pid OSZ=$sz_mbytes MB"

vmstat(1M)

$ vmstat 5 5 
 kthr      memory            page            disk          faults      cpu
 r b w   swap  free  re  mf pi po fr de sr rm s3 -- --   in   sy   cs us sy id
 0 0 0 535832 219880  1   2  0  0  0  0  0 -0  0  0  0  402   19   97  0  1 99
 0 0 0 514376 203648  1   4  0  0  0  0  0  0  0  0  0  402   19   96  0  1 99
^C

prstat(1M)

   PID USERNAME  SIZE   RSS STATE  PRI NICE      TIME  CPU PROCESS/NLWP       
  1852 martin   4840K 3600K cpu0    59    0   0:00:00 0.3% prstat/1
  1780 martin   9384K 2920K sleep   59    0   0:00:00 0.0% sshd/1
  ...

swap(1)

"Long listing" and "summary" modes:

$ swap -l
swapfile             dev  swaplo blocks   free
/dev/zvol/dsk/rpool/swap 256,1      16 1048560 1048560
$ swap -s 
total: 42352k bytes allocated + 20192k reserved = 62544k used, 607672k available
$

top(1)

An older version (3.51) is available on the Solaris companion CD from Sun, with the disclaimer that this is "Community (not Sun) supported". More recent binary packages available from sunfreeware.com or blastwave.org.

load averages:  0.02,  0.00,  0.00;                      up 2+12:31:38                                                                                            08:53:58
31 processes: 30 sleeping, 1 on cpu
CPU states: 98.0% idle,  0.0% user,  2.0% kernel,  0.0% iowait,  0.0% swap
Memory: 1024M phys mem, 197M free mem, 512M total swap, 512M free swap

   PID USERNAME LWP PRI NICE  SIZE   RES STATE    TIME    CPU COMMAND
  1898 martin     1  54    0 3336K 1808K cpu      0:00  0.96% top
     7 root      11  59    0   10M 7912K sleep    0:09  0.02% svc.startd

sar(1M)

And just what's wrong with sar? :)

How to implode array with key and value without foreach in PHP

There is also var_export and print_r more commonly known for printing debug output but both functions can take an optional argument to return a string instead.

Using the example from the question as data.

$array = ["item1"=>"object1", "item2"=>"object2","item-n"=>"object-n"];

Using print_r to turn the array into a string

This will output a human readable representation of the variable.

$string = print_r($array, true);
echo $string;

Will output:

Array
(
    [item1] => object1
    [item2] => object2
    [item-n] => object-n
)

Using var_export to turn the array into a string

Which will output a php string representation of the variable.

$string = var_export($array, true);
echo $string;

Will output:

array (
  'item1' => 'object1',
  'item2' => 'object2',
  'item-n' => 'object-n',
)

Because it is valid php we can evaluate it.

eval('$array2 = ' . var_export($array, true) . ';');
var_dump($array2 === $array);

Outputs:

bool(true)

Docker: Copying files from Docker container to host

I used PowerShell (Admin) with this command.

docker cp {container id}:{container path}/error.html  C:\\error.html

Example

docker cp ff3a6608467d:/var/www/app/error.html  C:\\error.html

How to remove the first Item from a list?

Then just delete it:

x = [0, 1, 2, 3, 4]
del x[0]
print x
# [1, 2, 3, 4]

Exploitable PHP functions

i'd particularly want to add unserialize() to this list. It has had a long history of various vulnerabilities including arbitrary code execution, denial of service and memory information leakage. It should never be called on user-supplied data. Many of these vuls have been fixed in releases over the last dew years, but it still retains a couple of nasty vuls at the current time of writing.

For other information about dodgy php functions/usage look around the Hardened PHP Project and its advisories. Also the recent Month of PHP Security and 2007's Month of PHP Bugs projects

Also note that, by design, unserializing an object will cause the constructor and destructor functions to execute; another reason not to call it on user-supplied data.

Android. Fragment getActivity() sometimes returns null

Ok, I know that this question is actually solved but I decided to share my solution for this. I've created abstract parent class for my Fragment:

public abstract class ABaseFragment extends Fragment{

    protected IActivityEnabledListener aeListener;

    protected interface IActivityEnabledListener{
        void onActivityEnabled(FragmentActivity activity);
    }

    protected void getAvailableActivity(IActivityEnabledListener listener){
        if (getActivity() == null){
            aeListener = listener;

        } else {
            listener.onActivityEnabled(getActivity());
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        if (aeListener != null){
            aeListener.onActivityEnabled((FragmentActivity) activity);
            aeListener = null;
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        if (aeListener != null){
            aeListener.onActivityEnabled((FragmentActivity) context);
            aeListener = null;
        }
    }
}

As you can see, I've added a listener so, whenever I'll need to get Fragments Activity instead of standard getActivity(), I'll need to call

 getAvailableActivity(new IActivityEnabledListener() {
        @Override
        public void onActivityEnabled(FragmentActivity activity) {
            // Do manipulations with your activity
        }
    });

How to view DB2 Table structure

I am running DB2/LINUXX8664 10.5.3 and describe select * from schema_name.table_name works for me.

However, describe table schema_name.table_name fails with this error:

SQL0100W No row was found for FETCH, UPDATE or DELETE; or the result of a query is an empty table. SQLSTATE=02000

state provider and route provider in angularJS

You shouldn't use both ngRoute and UI-router. Here's a sample code for UI-router:

_x000D_
_x000D_
repoApp.config(function($stateProvider, $urlRouterProvider) {_x000D_
  _x000D_
  $stateProvider_x000D_
    .state('state1', {_x000D_
      url: "/state1",_x000D_
      templateUrl: "partials/state1.html",_x000D_
      controller: 'YourCtrl'_x000D_
    })_x000D_
    _x000D_
    .state('state2', {_x000D_
      url: "/state2",_x000D_
      templateUrl: "partials/state2.html",_x000D_
      controller: 'YourOtherCtrl'_x000D_
    });_x000D_
    $urlRouterProvider.otherwise("/state1");_x000D_
});_x000D_
//etc.
_x000D_
_x000D_
_x000D_

You can find a great answer on the difference between these two in this thread: What is the difference between angular-route and angular-ui-router?

You can also consult UI-Router's docs here: https://github.com/angular-ui/ui-router

Does java.util.List.isEmpty() check if the list itself is null?

No java.util.List.isEmpty() doesn't check if a list is null.

If you are using Spring framework you can use the CollectionUtils class to check if a list is empty or not. It also takes care of the null references. Following is the code snippet from Spring framework's CollectionUtils class.

public static boolean isEmpty(Collection<?> collection) {
    return (collection == null || collection.isEmpty());
}

Even if you are not using Spring, you can go on and tweak this code to add in your AppUtil class.

Command copy exited with code 4 when building - Visual Studio restart solves it

I crossed the same error, but it is not due to the file is locked, but the file is missing.

The reason why VS tried to copy an not existing file, is because of the Post-build event command.

After I cleared that, problem solved.

UPDATE:

As @rhughes commented:

The real issue is how to get the command here to work, rather than to remove it.

and he is absolutely right.

enter image description here

Using array map to filter results with if conditional

You're looking for the .filter() function:

  $scope.appIds = $scope.applicationsHere.filter(function(obj) {
    return obj.selected;
  });

That'll produce an array that contains only those objects whose "selected" property is true (or truthy).

edit sorry I was getting some coffee and I missed the comments - yes, as jAndy noted in a comment, to filter and then pluck out just the "id" values, it'd be:

  $scope.appIds = $scope.applicationsHere.filter(function(obj) {
    return obj.selected;
  }).map(function(obj) { return obj.id; });

Some functional libraries (like Functional, which in my opinion doesn't get enough love) have a .pluck() function to extract property values from a list of objects, but native JavaScript has a pretty lean set of such tools.

How to Get enum item name from its value

No, you have no way to get the "name" from the value in C++ because all the symbols are discarded during compilation.

You may need this way X Macros

How to select first child with jQuery?

Hi we can use default method "first" in jQuery

Here some examples:

When you want to add class for first div

  $('.alldivs div').first().addClass('active');

When you want to change the remove the "onediv" class and add only to first child

   $('.alldivs div').removeClass('onediv').first().addClass('onediv');

Set height of chart in Chart.js

You can wrap your canvas element in a parent div, relatively positioned, then give that div the height you want, setting maintainAspectRatio: false in your options

//HTML
<div id="canvasWrapper" style="position: relative; height: 80vh/500px/whatever">
<canvas id="chart"></canvas>
</div>

<script>
new Chart(somechart, {
options: {
    responsive: true,
    maintainAspectRatio: false

/*, your other options*/

}
});
</script>

How to insert values in two dimensional array programmatically?

this is output of this program

Scanner s=new Scanner (System.in);
int row, elem, col;

Systm.out.println("Enter Element to insert");
elem = s.nextInt();
System.out.println("Enter row");
row=s.nextInt();
System.out.println("Enter row");
col=s.nextInt();
for (int c=row-1; c < row; c++)
{
    for (d = col-1 ; d < col ; d++)
         array[c][d] = elem;
}
for(c = 0; c < size; c++)
{ 
   for (d = 0 ; d < size ; d++)
         System.out.print( array[c] [d] +"   ");
   System.out.println();
}

Should I use Java's String.format() if performance is important?

I wrote a small class to test which has the better performance of the two and + comes ahead of format. by a factor of 5 to 6. Try it your self

import java.io.*;
import java.util.Date;

public class StringTest{

    public static void main( String[] args ){
    int i = 0;
    long prev_time = System.currentTimeMillis();
    long time;

    for( i = 0; i< 100000; i++){
        String s = "Blah" + i + "Blah";
    }
    time = System.currentTimeMillis() - prev_time;

    System.out.println("Time after for loop " + time);

    prev_time = System.currentTimeMillis();
    for( i = 0; i<100000; i++){
        String s = String.format("Blah %d Blah", i);
    }
    time = System.currentTimeMillis() - prev_time;
    System.out.println("Time after for loop " + time);

    }
}

Running the above for different N shows that both behave linearly, but String.format is 5-30 times slower.

The reason is that in the current implementation String.format first parses the input with regular expressions and then fills in the parameters. Concatenation with plus, on the other hand, gets optimized by javac (not by the JIT) and uses StringBuilder.append directly.

Runtime comparison

Can't use Swift classes inside Objective-C

In my case, apart from these steps:

  1. Product Module Name : myproject
  2. Defines Module : YES
  3. Embedded Content Contains Swift : YES
  4. Install Objective-C Compatibility Header : YES
  5. Objective-C Bridging Header : $(SRCROOT)/Sources/SwiftBridging.h

I have needed to put the class as public in order to create productName-Swift.h file:

import UIKit

   @objc public class TestSwift: NSObject {
       func sayHello() {
          print("Hi there!")
       }
   }

Git: How to reset a remote Git repository to remove all commits?

First, follow the instructions in this question to squash everything to a single commit. Then make a forced push to the remote:

$ git push origin +master

And optionally delete all other branches both locally and remotely:

$ git push origin :<branch>
$ git branch -d <branch>

Compare two date formats in javascript/jquery

As in your example, the fit_start_time is not later than the fit_end_time.

Try it the other way round:

var fit_start_time  = $("#fit_start_time").val(); //2013-09-5
var fit_end_time    = $("#fit_end_time").val(); //2013-09-10

if(Date.parse(fit_start_time) <= Date.parse(fit_end_time)){
    alert("Please select a different End Date.");
}

Update

Your code implies that you want to see the alert with the current variables you have. If this is the case then the above code is correct. If you're intention (as per the implication of the alert message) is to make sure their fit_start_time variable is a date that is before the fit_end_time, then your original code is fine, but the data you're getting from the jQuery .val() methods is not parsing correctly. It would help if you gave us the actual HTML which the selector is sniffing at.

How to check if element exists using a lambda expression?

Try to use anyMatch of Lambda Expression. It is much better approach.

 boolean idExists = tabPane.getTabs().stream()
            .anyMatch(t -> t.getId().equals(idToCheck));

What's the correct way to convert bytes to a hex string in Python 3?

it can been used the format specifier %x02 that format and output a hex value. For example:

>>> foo = b"tC\xfc}\x05i\x8d\x86\x05\xa5\xb4\xd3]Vd\x9cZ\x92~'6"
>>> res = ""
>>> for b in foo:
...     res += "%02x" % b
... 
>>> print(res)
7443fc7d05698d8605a5b4d35d56649c5a927e2736

C# delete a folder and all files and folders within that folder

Err, what about just calling Directory.Delete(path, true); ?

Floating elements within a div, floats outside of div. Why?

Put your floating div(s) in a div and in CSS give it overflow:hidden;
it will work fine.

Getting number of days in a month

 int days = DateTime.DaysInMonth(int year,int month);

or

 int days=System.Globalization.CultureInfo.CurrentCulture.Calendar.GetDaysInMonth(int year,int month);

you have to pass year and month as int then days in month will be return on currespoting year and month

Select multiple elements from a list

mylist[c(5,7,9)] should do it.

You want the sublists returned as sublists of the result list; you don't use [[]] (or rather, the function is [[) for that -- as Dason mentions in comments, [[ grabs the element.

What is the best way to clone/deep copy a .NET generic Dictionary<string, T>?

Binary Serialization method works fine but in my tests it showed to be 10x slower than a non-serialization implementation of clone. Tested it on Dictionary<string , List<double>>

Changing CSS for last <li>

I've done this with pure CSS (probably because I come from the future - 3 years later than everyone else :P )

Supposing we have a list:

<ul id="nav">
  <li><span>Category 1</span></li>
  <li><span>Category 2</span></li>
  <li><span>Category 3</span></li>
</ul>

Then we can easily make the text of the last item red with:

ul#nav li:last-child span {
   color: Red;
}

How to suppress Update Links warning?

(I don't have enough rep points to add a comment, but I want to add some clarity on the answers here)

Application.AskToUpdateLinks = False is probably not what you want.

If set to False, then MS Excel will attempt to update the links automatically it just won't prompt the user beforehand, sorta counter-intuitive.

The correct solution, if you're looking to open a file without updating links should be:

Workbook.Open(UpdateLinks:=0)

Related link: Difference in AskToUpdateLinks=False and UpdateLinks:=0

How can I insert new line/carriage returns into an element.textContent?

The following code works well (On FireFox, IE and Chrome) :

var display_out = "This is line 1" + "<br>" + "This is line 2";

document.getElementById("demo").innerHTML = display_out;

How to request Google to re-crawl my website?

There are two options. The first (and better) one is using the Fetch as Google option in Webmaster Tools that Mike Flynn commented about. Here are detailed instructions:

  1. Go to: https://www.google.com/webmasters/tools/ and log in
  2. If you haven't already, add and verify the site with the "Add a Site" button
  3. Click on the site name for the one you want to manage
  4. Click Crawl -> Fetch as Google
  5. Optional: if you want to do a specific page only, type in the URL
  6. Click Fetch
  7. Click Submit to Index
  8. Select either "URL" or "URL and its direct links"
  9. Click OK and you're done.

With the option above, as long as every page can be reached from some link on the initial page or a page that it links to, Google should recrawl the whole thing. If you want to explicitly tell it a list of pages to crawl on the domain, you can follow the directions to submit a sitemap.

Your second (and generally slower) option is, as seanbreeden pointed out, submitting here: http://www.google.com/addurl/

Update 2019:

  1. Login to - Google Search Console
  2. Add a site and verify it with the available methods.
  3. After verification from the console, click on URL Inspection.
  4. In the Search bar on top, enter your website URL or custom URLs for inspection and enter.
  5. After Inspection, it'll show an option to Request Indexing
  6. Click on it and GoogleBot will add your website in a Queue for crawling.

How to stop a function

A simple return statement will 'stop' or return the function; in precise terms, it 'returns' function execution to the point at which the function was called - the function is terminated without further action.

That means you could have a number of places throughout your function where it might return. Like this:

def player():
    # do something here
    check_winner_variable = check_winner()  # check something 
    if check_winner_variable == '1': 
        return
    second_test_variable = second_test()
    if second_test_variable == '1': 
        return
       
    # let the computer do something
    computer()

Android: Is it possible to display video thumbnails?

Try this it's working for me

RequestOptions requestOptions = new RequestOptions();
 Glide.with(getContext())
      .load("video_url")
      .apply(requestOptions)
      .thumbnail(Glide.with(getContext()).load("video_url"))
      .into("yourimageview");

Why am I getting "undefined reference to sqrt" error even though I include math.h header?

Because you didn't tell the linker about location of math library. Compile with gcc test.c -o test -lm

How to delete a module in Android Studio

The "Mark as Excluded" option isn't there anymore.

The current (Android Studio 0.8.x - 2.2.x) way to do this is via the Project Structure dialog. It can be accessed via "File -> Project Structure" or by right-clicking on a Module and selecting "Module Settings".

enter image description here

Then select the module, and click the "minus" button to remove it.

enter image description here

The directory will still be visible in the "Project" view (though not in the "Android" view) since it's not actually deleted, but it will no longer be treated as a module.

If you want, you can then physically delete the files it by right-clicking on it and pressing "Delete".

User Get-ADUser to list all properties and export to .csv

@AnsgarWiechers - it's not my experience that querying everything and then pruning the result is more efficient when you're doing a targeted search of known accounts. Although, yes, it is also more efficient to select just the properties you need to return.

The below examples are based on a domain in the range of 20,000 account objects.

measure-command {Get-ADUser -Filter '*' -Properties DisplayName,st }
...
Seconds           : 16
Milliseconds      : 208

measure-command {$userlist | get-aduser -Properties DisplayName,st}
...
Seconds           : 3
Milliseconds      : 496

In the second example, $userlist contains 368 account names (just strings, not pre-fetched account objects).

Note that if I include the where clause per your suggestion to prune to the actually desired results, it's even more expensive.

measure-command {Get-ADUser -Filter '*' -Properties DisplayName,st |where {$userlist -Contains $_.samaccountname } }
...
Seconds           : 17
Milliseconds      : 876

Indexed attributes seem to have similar performance (I tried just returning displayName).

Even if I return all user account properties in my set, it's more efficient. (Adding a select statement to the below brings it down by a half-second).

measure-command {$userlist | get-aduser -Properties *}
...
Seconds           : 12
Milliseconds      : 75

I can't find a good document that was written in ye olde days about AD queries to link to, but you're hitting every account in your search scope to return the properties. This discusses the basics of doing effective AD queries - scoping and filtering: https://msdn.microsoft.com/en-us/library/ms808539.aspx#efficientadapps_topic01

When your search scope is "*", you're still building a (big) list of the objects and iterating through each one. An LDAP search filter is always more efficient to build the list first (or a narrow search base, which is again building a smaller list to query).

How to remove any URL within a string in Python

In order to remove any URL within a string in Python, you can use this RegEx function :

import re

def remove_URL(text):
    """Remove URLs from a text string"""
    return re.sub(r"http\S+", "", text)

Can you append strings to variables in PHP?

In PHP use .= to append strings, and not +=.

Why does this output 0? [...] Does PHP not like += with strings?

+= is an arithmetic operator to add a number to another number. Using that operator with strings leads to an automatic type conversion. In the OP's case the strings have been converted to integers of the value 0.


More about operators in PHP:

Way to go from recursion to iteration

Just killing time... A recursive function

void foo(Node* node)
{
    if(node == NULL)
       return;
    // Do something with node...
    foo(node->left);
    foo(node->right);
}

can be converted to

void foo(Node* node)
{
    if(node == NULL)
       return;

    // Do something with node...

    stack.push(node->right);
    stack.push(node->left);

    while(!stack.empty()) {
         node1 = stack.pop();
         if(node1 == NULL)
            continue;
         // Do something with node1...
         stack.push(node1->right);             
         stack.push(node1->left);
    }

}

JSON library for C#

The .net framework supports JSON through JavaScriptSerializer. Here is a good example to get you started.

using System.Collections.Generic;
using System.Web.Script.Serialization;

namespace GoogleTranslator.GoogleJSON
{
    public class FooTest
    {
        public void Test()
        {
            const string json = @"{
              ""DisplayFieldName"" : ""ObjectName"", 
              ""FieldAliases"" : {
                ""ObjectName"" : ""ObjectName"", 
                ""ObjectType"" : ""ObjectType""
              }, 
              ""PositionType"" : ""Point"", 
              ""Reference"" : {
                ""Id"" : 1111
              }, 
              ""Objects"" : [
                {
                  ""Attributes"" : {
                    ""ObjectName"" : ""test name"", 
                    ""ObjectType"" : ""test type""
                  }, 
                  ""Position"" : 
                  {
                    ""X"" : 5, 
                    ""Y"" : 7
                  }
                }
              ]
            }";

            var ser = new JavaScriptSerializer();
            ser.Deserialize<Foo>(json);
        }
    }

    public class Foo
    {
        public Foo() { Objects = new List<SubObject>(); }
        public string DisplayFieldName { get; set; }
        public NameTypePair FieldAliases { get; set; }
        public PositionType PositionType { get; set; }
        public Ref Reference { get; set; }
        public List<SubObject> Objects { get; set; }
    }

    public class NameTypePair
    {
        public string ObjectName { get; set; }
        public string ObjectType { get; set; }
    }

    public enum PositionType { None, Point }
    public class Ref
    {
        public int Id { get; set; }
    }

    public class SubObject
    {
        public NameTypePair Attributes { get; set; }
        public Position Position { get; set; }
    }

    public class Position
    {
        public int X { get; set; }
        public int Y { get; set; }
    }
}

Joining Multiple Tables - Oracle

While former answer is absolutely correct, I prefer using the JOIN ON syntax to be sure that I know how do I join and on what fields. It would look something like this:

SELECT bc.firstname, bc.lastname, b.title, TO_CHAR(bo.orderdate, 'MM/DD/YYYY') "Order         Date", p.publishername
FROM books b
JOIN book_customer bc ON bc.costumer_id = b.book_id
LEFT JOIN book_order bo ON bo.book_id = b.book_id
(etc.)
WHERE b.publishername = 'PRINTING IS US';

This syntax seperates completely the WHERE clause from the JOIN clause, making the statement more readable and easier for you to debug.

What are the ways to make an html link open a folder

Using file:///// just doesn't work if security settings are set to even a moderate level.

If you just want users to be able to download/view files* located on a network or share you can set up a Virtual Directory in IIS. On the Properties tab make sure the "A share located on another computer" is selected and the "Connect as..." is an account that can see the network location.

Link to the virtual directory from your webpage (e.g. http://yoursite/yourvirtualdir/) and this will open up a view of the directory in the web browser.

*You can allow write permissions on the virtual directory to allow users to add files but not tried it and assume network permissions would override this setting.

How can I convert uppercase letters to lowercase in Notepad++

You could also, higlight the text you want to change, then navigate to - 'Edit' > 'Convert Case to' choose UPPERCASE or lowercase (as required).

How to run PyCharm in Ubuntu - "Run in Terminal" or "Run"?

For Pycharm CE 2018.3 and Ubuntu 18.04 with snap installation:

env BAMF_DESKTOP_FILE_HINT=/var/lib/snapd/desktop/applications/pycharm-community_pycharm-community.desktop /snap/bin/pycharm-community %f

I get this command from KDE desktop launch icon.

pychar-ce-command

Sorry for the language but I am a Spanish developer so I have my system in Spanish.

Configure WAMP server to send email

I used Mercury/32 and Pegasus Mail to get the mail() functional. It works great too as a mail server if you want an email address ending with your domain name.

Get current time in milliseconds using C++ and Boost

If you mean milliseconds since epoch you could do

ptime time_t_epoch(date(1970,1,1)); 
ptime now = microsec_clock::local_time();
time_duration diff = now - time_t_epoch;
x = diff.total_milliseconds();

However, it's not particularly clear what you're after.

Have a look at the example in the documentation for DateTime at Boost Date Time

Entity Framework Join 3 Tables

This is untested, but I believe the syntax should work for a lambda query. As you join more tables with this syntax you have to drill further down into the new objects to reach the values you want to manipulate.

var fullEntries = dbContext.tbl_EntryPoint
    .Join(
        dbContext.tbl_Entry,
        entryPoint => entryPoint.EID,
        entry => entry.EID,
        (entryPoint, entry) => new { entryPoint, entry }
    )
    .Join(
        dbContext.tbl_Title,
        combinedEntry => combinedEntry.entry.TID,
        title => title.TID,
        (combinedEntry, title) => new 
        {
            UID = combinedEntry.entry.OwnerUID,
            TID = combinedEntry.entry.TID,
            EID = combinedEntry.entryPoint.EID,
            Title = title.Title
        }
    )
    .Where(fullEntry => fullEntry.UID == user.UID)
    .Take(10);

Apache and IIS side by side (both listening to port 80) on windows2003

For people with only one IP address and multiple sites on one server, you can configure IIS to listen on a port other than 80, e.g 8080 by setting the TCP port in the properties of each of its sites (including the default one).

In Apache, enable mod_proxy and mod_proxy_http, then add a catch-all VirtualHost (after all others) so that requests Apache isn't explicitly handling get "forwarded" on to IIS.

<VirtualHost *:80>
    ServerName foo.bar
    ServerAlias *
    ProxyPreserveHost On
    ProxyPass / http://127.0.0.1:8080/
</VirtualHost>

Now you can have Apache serve some sites and IIS serve others, with no visible difference to the user.

Edit: your IIS sites must not include their port number in any URLs within their responses, including headers.

Android Studio Checkout Github Error "CreateProcess=2" (Windows)

If you have downloaded Github Desktop Client 1.0.9 then the path for git.exe will be

C:\Users\Username\AppData\Local\GitHubDesktop\app-1.0.9\resources\app\git\cmd\git.exe

Why dict.get(key) instead of dict[key]?

get takes a second optional value. If the specified key does not exist in your dictionary, then this value will be returned.

dictionary = {"Name": "Harry", "Age": 17}
dictionary.get('Year', 'No available data')
>> 'No available data'

If you do not give the second parameter, None will be returned.

If you use indexing as in dictionary['Year'], nonexistent keys will raise KeyError.

Hibernate: How to fix "identifier of an instance altered from X to Y"?

Problem can be also in different types of object's PK ("User" in your case) and type you ask hibernate to get session.get(type, id);.

In my case error was identifier of an instance of <skipped> was altered from 16 to 32. Object's PK type was Integer, hibernate was asked for Long type.

How to get Tensorflow tensor dimensions (shape) as int values?

Another simple solution is to use map() as follows:

tensor_shape = map(int, my_tensor.shape)

This converts all the Dimension objects to int

How to extract string following a pattern with grep, regex or perl

If you're using Perl, download a module to parse the XML: XML::Simple, XML::Twig, or XML::LibXML. Don't re-invent the wheel.

How do I handle the window close event in Tkinter?

If you want to change what the x button does or make it so that you cannot close it at all try this.

yourwindow.protocol("WM_DELETE_WINDOW", whatever)

then defy what "whatever" means

def whatever():
    #Replace this with what you want python to do when the user hits the x button

You can also make it so that when you close that window you can call it back like this

yourwindow.withdraw() 

This hides the window but does not close it

yourwindow.deiconify()

This makes the window visible again

Understanding Python super() with __init__() methods

Super has no side effects

Base = ChildB

Base()

works as expected

Base = ChildA

Base()

gets into infinite recursion.

Return string Input with parse.string

You don't need to parse the string, it's defined as a string already.

Just do:

    private static String getStringInput (String prompt) {
     String input = EZJ.getUserInput(prompt);
     return input;
    }

In Objective-C, how do I test the object type?

Running a simple test, I thought I'd document what works and what doesn't. Often I see people checking to see if the object's class is a member of the other class or is equal to the other class.

For the line below, we have some poorly formed data that can be an NSArray, an NSDictionary or (null).

NSArray *hits = [[[myXML objectForKey: @"Answer"] objectForKey: @"hits"] objectForKey: @"Hit"];

These are the tests that were performed:

NSLog(@"%@", [hits class]);

if ([hits isMemberOfClass:[NSMutableArray class]]) {
    NSLog(@"%@", [hits class]);
}

if ([hits isMemberOfClass:[NSMutableDictionary class]]) {
    NSLog(@"%@", [hits class]);
}

if ([hits isMemberOfClass:[NSArray class]]) {
    NSLog(@"%@", [hits class]);
}

if ([hits isMemberOfClass:[NSDictionary class]]) {
    NSLog(@"%@", [hits class]);
}

if ([hits isKindOfClass:[NSMutableDictionary class]]) {
    NSLog(@"%@", [hits class]);
}

if ([hits isKindOfClass:[NSDictionary class]]) {
    NSLog(@"%@", [hits class]);
}

if ([hits isKindOfClass:[NSArray class]]) {
    NSLog(@"%@", [hits class]);
}

if ([hits isKindOfClass:[NSMutableArray class]]) {
    NSLog(@"%@", [hits class]);
}

isKindOfClass worked rather well while isMemberOfClass didn't.

Is it possible to use "return" in stored procedure?

-- IN arguments : you get them. You can modify them locally but caller won't see it
-- IN OUT arguments: initialized by caller, already have a value, you can modify them and the caller will see it
-- OUT arguments: they're reinitialized by the procedure, the caller will see the final value.
CREATE PROCEDURE f (p IN NUMBER, x IN OUT NUMBER, y OUT NUMBER)
IS
BEGIN
   x:=x * p;
   y:=4 * p;
END;
/

SET SERVEROUTPUT ON

declare
   foo number := 30;
   bar number := 0;
begin
   f(5,foo,bar);
   dbms_output.put_line(foo || ' ' || bar);
end;
/

-- Procedure output can be collected from variables x and y (ans1:= x and ans2:=y) will be: 150 and 20 respectively.

-- Answer borrowed from: https://stackoverflow.com/a/9484228/1661078

#pragma once vs include guards?

I don't think it will make a significant difference in compile time but #pragma once is very well supported across compilers but not actually part of the standard. The preprocessor may be a little faster with it as it is more simple to understand your exact intent.

#pragma once is less prone to making mistakes and it is less code to type.

To speed up compile time more just forward declare instead of including in .h files when you can.

I prefer to use #pragma once.

See this wikipedia article about the possibility of using both.

update listview dynamically with adapter

Most people recommend using notifyDataSetChanged(), but I found this link pretty useful. In fact using clear and add you can accomplish the same goal using less memory footprint, and more responsibe app.

For example:

notesListAdapter.clear();
notes = new ArrayList<Note>();
notesListAdapter.add(todayNote);
if (birthdayNote != null) notesListAdapter.add(birthdayNote);

/* no need to refresh, let the adaptor do its job */

Array initialization syntax when not in a declaration

For those of you, who doesn't like this monstrous new AClass[] { ... } syntax, here's some sugar:

public AClass[] c(AClass... arr) { return arr; }

Use this little function as you like:

AClass[] array;
...
array = c(object1, object2);

Allowed characters in filename

OK, so looking at Comparison of file systems if you only care about the main players file systems:

so any byte except NUL, \, /, :, *, ", <, >, | and you can't have files/folders call . or .. and no control characters (of course).

Expand a random range from 1–5 to 1–7

Why don't you just divide by 5 and multiply by 7, and then round? (Granted, you would have to use floating-point no.s)

It's much easier and more reliable (really?) than the other solutions. E.g. in Python:

def ranndomNo7():
    import random
    rand5 = random.randint(4)    # Produces range: [0, 4]
    rand7 = int(rand5 / 5 * 7)   # /5, *7, +0.5 and floor()
    return rand7

Wasn't that easy?

http://localhost/phpMyAdmin/ unable to connect

http://localhost:(port number of phpmyadmin)/phpmyadmin/

For example: http://localhost:8080/phpmyadmin/

It works great!

"Error 404 Not Found" in Magento Admin Login Page

Finally, I found the solution to my problem.

I looked into the Magento system log file (var/log/system.log). There I saw the exact error.

The error is as below:-

Recoverable Error: Argument 1 passed to Mage_Core_Model_Store::setWebsite() must be an instance of Mage_Core_Model_Website, null given, called in YOUR_PATH\app\code\core\Mage\Core\Model\App.php on line 555 and defined in YOUR_PATH\app\code\core\Mage\Core\Model\Store.php on line 285

Recoverable Error: Argument 1 passed to Mage_Core_Model_Store_Group::setWebsite() must be an instance of Mage_Core_Model_Website, null given, called in YOUR_PATH\app\code\core\Mage\Core\Model\App.php on line 575 and defined in YOUR_PATH\app\code\core\Mage\Core\Model\Store\Group.php on line 227

Actually, I had this error before. But, error display message like Error: 404 Not Found was new to me.

The reason for this error is that store_id and website_id for admin should be set to 0 (zero). But, when you import database to new server, somehow these values are not set to 0.

Open PhpMyAdmin and run the following query in your database:-

SET FOREIGN_KEY_CHECKS=0;
UPDATE `core_store` SET store_id = 0 WHERE code='admin';
UPDATE `core_store_group` SET group_id = 0 WHERE name='Default';
UPDATE `core_website` SET website_id = 0 WHERE code='admin';
UPDATE `customer_group` SET customer_group_id = 0 WHERE customer_group_code='NOT LOGGED IN';
SET FOREIGN_KEY_CHECKS=1;

I have written about this problem and solution over here:-

Magento: Solution to "Error: 404 Not Found" in Admin Login Page

Recommended way to get hostname in Java

InetAddress.getLocalHost().getHostName() is the best way out of the two as this is the best abstraction at the developer level.

How to add a Java Properties file to my Java Project in Eclipse

In the package explorer, right-click on the package and select New -> File, then enter the filename including the ".properties" suffix.

Put buttons at bottom of screen with LinearLayout?

Just add layout_weight="1" to in your linearLayout which having Buttons.

Edit :- let me make it simple

follow something like below, tags name may not be correct, it is just an Idea

<LL>// Top Parrent LinearLayout
   <LL1 height="fill_parent" weight="1" "other tags as requirement"> <TV /><Butons /></LL1> // this layout will fill your screen.
   <LL2 height="wrap_content" weight="1"  orientation="Horizontal" "other tags as requirement"> <BT1 /><BT2/ ></LL2> // this layout gonna take lower part of button height of your screen

<LL/> TOP PARENT CLOSED

JavaScript sleep/wait before continuing

JS does not have a sleep function, it has setTimeout() or setInterval() functions.

If you can move the code that you need to run after the pause into the setTimeout() callback, you can do something like this:

//code before the pause
setTimeout(function(){
    //do what you need here
}, 2000);

see example here : http://jsfiddle.net/9LZQp/

This won't halt the execution of your script, but due to the fact that setTimeout() is an asynchronous function, this code

console.log("HELLO");
setTimeout(function(){
    console.log("THIS IS");
}, 2000);
console.log("DOG");

will print this in the console:

HELLO
DOG
THIS IS

(note that DOG is printed before THIS IS)


You can use the following code to simulate a sleep for short periods of time:

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

now, if you want to sleep for 1 second, just use:

sleep(1000);

example: http://jsfiddle.net/HrJku/1/

please note that this code will keep your script busy for n milliseconds. This will not only stop execution of Javascript on your page, but depending on the browser implementation, may possibly make the page completely unresponsive, and possibly make the entire browser unresponsive. In other words this is almost always the wrong thing to do.

What is the difference between signed and unsigned int

In laymen's terms an unsigned int is an integer that can not be negative and thus has a higher range of positive values that it can assume. A signed int is an integer that can be negative but has a lower positive range in exchange for more negative values it can assume.

Align div right in Bootstrap 3

Bootstrap 4+ has made changes to the utility classes for this. From the documentation:

Added .float-{sm,md,lg,xl}-{left,right,none} classes for responsive floats and removed .pull-left and .pull-right since they’re redundant to .float-left and .float-right.

So use the .float-right (or a size equivalent such as .float-lg-right) instead of .pull-right for your right alignment if you're using a newer Bootstrap version.

RecyclerView and java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder in Samsung devices

I ran into the same problem when I have update data while the RecyclerView is scrolling. And I fixed it with the following solution:

  1. Stop scroll our RecyclerView before update data.
  2. Custom layout manager likes with the preceding answer.
  3. Use DiffUtils to ensure updating data is correct.

Rounding a double to turn it into an int (java)

The Math.round function is overloaded When it receives a float value, it will give you an int. For example this would work.

int a=Math.round(1.7f);

When it receives a double value, it will give you a long, therefore you have to typecast it to int.

int a=(int)Math.round(1.7);

This is done to prevent loss of precision. Your double value is 64bit, but then your int variable can only store 32bit so it just converts it to long, which is 64bit but you can typecast it to 32bit as explained above.

Insert a line at specific line number with sed or awk

Perl solutions:

quick and dirty:

perl -lpe 'print "Project_Name=sowstest" if $. == 8' file

  • -l strips newlines and adds them back in, eliminating the need for "\n"
  • -p loops over the input file, printing every line
  • -e executes the code in single quotes

$. is the line number

equivalent to @glenn's awk solution, using named arguments:

perl -slpe 'print $s if $. == $n' -- -n=8 -s="Project_Name=sowstest" file

  • -s enables a rudimentary argument parser
  • -- prevents -n and -s from being parsed by the standard perl argument parser

positional command arguments:

perl -lpe 'BEGIN{$n=shift; $s=shift}; print $s if $. == $n' 8 "Project_Name=sowstest" file

environment variables:

setenv n 8 ; setenv s "Project_Name=sowstest"
echo $n ; echo $s
perl -slpe 'print $ENV{s} if $. == $ENV{n}' file

ENV is the hash which contains all environment variables

Getopt to parse arguments into hash %o:

perl -MGetopt::Std -lpe 'BEGIN{getopt("ns",\%o)}; print $o{s} if $. == $o{n}' -- -n 8 -s "Project_Name=sowstest" file

Getopt::Long and longer option names

perl -MGetopt::Long -lpe 'BEGIN{GetOptions(\%o,"line=i","string=s")}; print $o{string} if $. == $o{line}' -- --line 8 --string "Project_Name=sowstest" file

Getopt is the recommended standard-library solution.
This may be overkill for one-line perl scripts, but it can be done

Uncaught SyntaxError: Unexpected token u in JSON at position 0

localStorage.clear()

That'll clear the stored data. Then refresh and things should start to work.

What are Aggregates and PODs and how/why are they special?

Changes in C++17

Download the C++17 International Standard final draft here.

Aggregates

C++17 expands and enhances aggregates and aggregate initialization. The standard library also now includes an std::is_aggregate type trait class. Here is the formal definition from section 11.6.1.1 and 11.6.1.2 (internal references elided):

An aggregate is an array or a class with
— no user-provided, explicit, or inherited constructors,
— no private or protected non-static data members,
— no virtual functions, and
— no virtual, private, or protected base classes.
[ Note: Aggregate initialization does not allow accessing protected and private base class’ members or constructors. —end note ]
The elements of an aggregate are:
— for an array, the array elements in increasing subscript order, or
— for a class, the direct base classes in declaration order, followed by the direct non-static data members that are not members of an anonymous union, in declaration order.

What changed?

  1. Aggregates can now have public, non-virtual base classes. Furthermore, it is not a requirement that base classes be aggregates. If they are not aggregates, they are list-initialized.
struct B1 // not a aggregate
{
    int i1;
    B1(int a) : i1(a) { }
};
struct B2
{
    int i2;
    B2() = default;
};
struct M // not an aggregate
{
    int m;
    M(int a) : m(a) { }
};
struct C : B1, B2
{
    int j;
    M m;
    C() = default;
};
C c { { 1 }, { 2 }, 3, { 4 } };
cout
    << "is C aggregate?: " << (std::is_aggregate<C>::value ? 'Y' : 'N')
    << " i1: " << c.i1 << " i2: " << c.i2
    << " j: " << c.j << " m.m: " << c.m.m << endl;

//stdout: is C aggregate?: Y, i1=1 i2=2 j=3 m.m=4
  1. Explicit defaulted constructors are disallowed
struct D // not an aggregate
{
    int i = 0;
    D() = default;
    explicit D(D const&) = default;
};
  1. Inheriting constructors are disallowed
struct B1
{
    int i1;
    B1() : i1(0) { }
};
struct C : B1 // not an aggregate
{
    using B1::B1;
};


Trivial Classes

The definition of trivial class was reworked in C++17 to address several defects that were not addressed in C++14. The changes were technical in nature. Here is the new definition at 12.0.6 (internal references elided):

A trivially copyable class is a class:
— where each copy constructor, move constructor, copy assignment operator, and move assignment operator is either deleted or trivial,
— that has at least one non-deleted copy constructor, move constructor, copy assignment operator, or move assignment operator, and
— that has a trivial, non-deleted destructor.
A trivial class is a class that is trivially copyable and has one or more default constructors, all of which are either trivial or deleted and at least one of which is not deleted. [ Note: In particular, a trivially copyable or trivial class does not have virtual functions or virtual base classes.—end note ]

Changes:

  1. Under C++14, for a class to be trivial, the class could not have any copy/move constructor/assignment operators that were non-trivial. However, then an implicitly declared as defaulted constructor/operator could be non-trivial and yet defined as deleted because, for example, the class contained a subobject of class type that could not be copied/moved. The presence of such non-trivial, defined-as-deleted constructor/operator would cause the whole class to be non-trivial. A similar problem existed with destructors. C++17 clarifies that the presence of such constructor/operators does not cause the class to be non-trivially copyable, hence non-trivial, and that a trivially copyable class must have a trivial, non-deleted destructor. DR1734, DR1928
  2. C++14 allowed a trivially copyable class, hence a trivial class, to have every copy/move constructor/assignment operator declared as deleted. If such as class was also standard layout, it could, however, be legally copied/moved with std::memcpy. This was a semantic contradiction, because, by defining as deleted all constructor/assignment operators, the creator of the class clearly intended that the class could not be copied/moved, yet the class still met the definition of a trivially copyable class. Hence in C++17 we have a new clause stating that trivially copyable class must have at least one trivial, non-deleted (though not necessarily publicly accessible) copy/move constructor/assignment operator. See N4148, DR1734
  3. The third technical change concerns a similar problem with default constructors. Under C++14, a class could have trivial default constructors that were implicitly defined as deleted, yet still be a trivial class. The new definition clarifies that a trivial class must have a least one trivial, non-deleted default constructor. See DR1496

Standard-layout Classes

The definition of standard-layout was also reworked to address defect reports. Again the changes were technical in nature. Here is the text from the standard (12.0.7). As before, internal references are elided:

A class S is a standard-layout class if it:
— has no non-static data members of type non-standard-layout class (or array of such types) or reference,
— has no virtual functions and no virtual base classes,
— has the same access control for all non-static data members,
— has no non-standard-layout base classes,
— has at most one base class subobject of any given type,
— has all non-static data members and bit-fields in the class and its base classes first declared in the same class, and
— has no element of the set M(S) of types (defined below) as a base class.108
M(X) is defined as follows:
— If X is a non-union class type with no (possibly inherited) non-static data members, the set M(X) is empty.
— If X is a non-union class type whose first non-static data member has type X0 (where said member may be an anonymous union), the set M(X) consists of X0 and the elements of M(X0).
— If X is a union type, the set M(X) is the union of all M(Ui) and the set containing all Ui, where each Ui is the type of the ith non-static data member of X.
— If X is an array type with element type Xe, the set M(X) consists of Xe and the elements of M(Xe).
— If X is a non-class, non-array type, the set M(X) is empty.
[ Note: M(X) is the set of the types of all non-base-class subobjects that are guaranteed in a standard-layout class to be at a zero offset in X. —end note ]
[ Example:

struct B { int i; }; // standard-layout class
struct C : B { }; // standard-layout class
struct D : C { }; // standard-layout class
struct E : D { char : 4; }; // not a standard-layout class
struct Q {};
struct S : Q { };
struct T : Q { };
struct U : S, T { }; // not a standard-layout class
—end example ]
108) This ensures that two subobjects that have the same class type and that belong to the same most derived object are not allocated at the same address.

Changes:

  1. Clarified that the requirement that only one class in the derivation tree "has" non-static data members refers to a class where such data members are first declared, not classes where they may be inherited, and extended this requirement to non-static bit fields. Also clarified that a standard-layout class "has at most one base class subobject of any given type." See DR1813, DR1881
  2. The definition of standard-layout has never allowed the type of any base class to be the same type as the first non-static data member. It is to avoid a situation where a data member at offset zero has the same type as any base class. The C++17 standard provides a more rigorous, recursive definition of "the set of the types of all non-base-class subobjects that are guaranteed in a standard-layout class to be at a zero offset" so as to prohibit such types from being the type of any base class. See DR1672, DR2120.

Note: The C++ standards committee intended the above changes based on defect reports to apply to C++14, though the new language is not in the published C++14 standard. It is in the C++17 standard.

Getting RSA private key from PEM BASE64 Encoded private key file

You've just published that private key, so now the whole world knows what it is. Hopefully that was just for testing.

EDIT: Others have noted that the openssl text header of the published key, -----BEGIN RSA PRIVATE KEY-----, indicates that it is PKCS#1. However, the actual Base64 contents of the key in question is PKCS#8. Evidently the OP copy and pasted the header and trailer of a PKCS#1 key onto the PKCS#8 key for some unknown reason. The sample code I've provided below works with PKCS#8 private keys.

Here is some code that will create the private key from that data. You'll have to replace the Base64 decoding with your IBM Base64 decoder.

public class RSAToy {

    private static final String BEGIN_RSA_PRIVATE_KEY = "-----BEGIN RSA PRIVATE KEY-----\n"
            + "MIIEuwIBADAN ...skipped the rest\n"
         // + ...   
         // + ... skipped the rest
         // + ...   
            + "-----END RSA PRIVATE KEY-----";

    public static void main(String[] args) throws Exception {

        // Remove the first and last lines

        String privKeyPEM = BEGIN_RSA_PRIVATE_KEY.replace("-----BEGIN RSA PRIVATE KEY-----\n", "");
        privKeyPEM = privKeyPEM.replace("-----END RSA PRIVATE KEY-----", "");
        System.out.println(privKeyPEM);

        // Base64 decode the data

        byte [] encoded = Base64.decode(privKeyPEM);

        // PKCS8 decode the encoded RSA private key

        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PrivateKey privKey = kf.generatePrivate(keySpec);

        // Display the results

        System.out.println(privKey);
    }
}

Rerender view on browser resize with React

This code is using the new React context API:

  import React, { PureComponent, createContext } from 'react';

  const { Provider, Consumer } = createContext({ width: 0, height: 0 });

  class WindowProvider extends PureComponent {
    state = this.getDimensions();

    componentDidMount() {
      window.addEventListener('resize', this.updateDimensions);
    }

    componentWillUnmount() {
      window.removeEventListener('resize', this.updateDimensions);
    }

    getDimensions() {
      const w = window;
      const d = document;
      const documentElement = d.documentElement;
      const body = d.getElementsByTagName('body')[0];
      const width = w.innerWidth || documentElement.clientWidth || body.clientWidth;
      const height = w.innerHeight || documentElement.clientHeight || body.clientHeight;

      return { width, height };
    }

    updateDimensions = () => {
      this.setState(this.getDimensions());
    };

    render() {
      return <Provider value={this.state}>{this.props.children}</Provider>;
    }
  }

Then you can use it wherever you want in your code like this:

<WindowConsumer>
  {({ width, height }) =>  //do what you want}
</WindowConsumer>

Truncating Text in PHP?

$mystring = "this is the text I would like to truncate";

// Pass your variable to the function
$mystring = truncate($mystring);

// Truncated tring printed out;
echo $mystring;

//truncate text function
public function truncate($text) {

    //specify number fo characters to shorten by
    $chars = 25;

    $text = $text." ";
    $text = substr($text,0,$chars);
    $text = substr($text,0,strrpos($text,' '));
    $text = $text."...";
    return $text;
}

taking input of a string word by word

(This is for the benefit of others who may refer)

You can simply use cin and a char array. The cin input is delimited by the first whitespace it encounters.

#include<iostream>
using namespace std;

main()
{
    char word[50];
    cin>>word;
    while(word){
        //Do stuff with word[]
        cin>>word;
    }
}

Read lines from a text file but skip the first two lines

Dim sFileName As String
Dim iFileNum As Integer
Dim sBuf As String
Dim Fields as String
Dim TempStr as String

sFileName = "c:\fields.ini"
''//Does the file exist?
If Len(Dir$(sFileName)) = 0 Then
    MsgBox ("Cannot find fields.ini")
End If

iFileNum = FreeFile()
Open sFileName For Input As iFileNum

''//This part skips the first two lines
if not(EOF(iFileNum)) Then Line Input #iFilenum, TempStr
if not(EOF(iFileNum)) Then Line Input #iFilenum, TempStr

Do While Not EOF(iFileNum)
    Line Input #iFileNum, Fields

    MsgBox (Fields)
Loop

Reading a .txt file using Scanner class in Java

The file you read in must have exactly the file name you specify: "10_random" not "10_random.txt" not "10_random.blah", it must exactly match what you are asking for. You can change either one to match so that they line up, but just be sure they do. It may help to show the file extensions in whatever OS you're using.

Also, for file location, it must be located in the working directory (same level) as the final executable (the .class file) that is the result of compilation.

ListBox with ItemTemplate (and ScrollBar!)

ListBox will try to expand in height that is available.. When you set the Height property of ListBox you get a scrollviewer that actually works...

If you wish your ListBox to accodate the height available, you might want to try to regulate the Height from your parent controls.. In a Grid for example, setting the Height to Auto in your RowDefinition might do the trick...

HTH

Which UUID version to use?

If you want a random number, use a random number library. If you want a unique identifier with effectively 0.00...many more 0s here...001% chance of collision, you should use UUIDv1. See Nick's post for UUIDv3 and v5.

UUIDv1 is NOT secure. It isn't meant to be. It is meant to be UNIQUE, not un-guessable. UUIDv1 uses the current timestamp, plus a machine identifier, plus some random-ish stuff to make a number that will never be generated by that algorithm again. This is appropriate for a transaction ID (even if everyone is doing millions of transactions/s).

To be honest, I don't understand why UUIDv4 exists... from reading RFC4122, it looks like that version does NOT eliminate possibility of collisions. It is just a random number generator. If that is true, than you have a very GOOD chance of two machines in the world eventually creating the same "UUID"v4 (quotes because there isn't a mechanism for guaranteeing U.niversal U.niqueness). In that situation, I don't think that algorithm belongs in a RFC describing methods for generating unique values. It would belong in a RFC about generating randomness. For a set of random numbers:

chance_of_collision = 1 - (set_size! / (set_size - tries)!) / (set_size ^ tries)

Python: How exactly can you take a string, split it, reverse it and join it back together again?

Do you mean like this?

import string
astr='a(b[c])d'

deleter=string.maketrans('()[]','    ')
print(astr.translate(deleter))
# a b c  d
print(astr.translate(deleter).split())
# ['a', 'b', 'c', 'd']
print(list(reversed(astr.translate(deleter).split())))
# ['d', 'c', 'b', 'a']
print(' '.join(reversed(astr.translate(deleter).split())))
# d c b a

How to run Ruby code from terminal?

If Ruby is installed, then

ruby yourfile.rb

where yourfile.rb is the file containing the ruby code.

Or

irb

to start the interactive Ruby environment, where you can type lines of code and see the results immediately.

"Line contains NULL byte" in CSV reader (Python)

I've solved a similar problem with an easier solution:

import codecs
csvReader = csv.reader(codecs.open('file.csv', 'rU', 'utf-16'))

The key was using the codecs module to open the file with the UTF-16 encoding, there are a lot more of encodings, check the documentation.

Android Completely transparent Status Bar?

 <item name="android:statusBarColor" tools:targetApi="lollipop">@android:color/transparent</item>
            <!--<item name="android:windowLightStatusBar" tools:targetApi="m">true</item>-->

Dont use windowLightStatusBar use instead statusBarColor = @android:color/transparent

Invalid date in safari

The pattern yyyy-MM-dd isn't an officially supported format for Date constructor. Firefox seems to support it, but don't count on other browsers doing the same.

Here are some supported strings:

  • MM-dd-yyyy
  • yyyy/MM/dd
  • MM/dd/yyyy
  • MMMM dd, yyyy
  • MMM dd, yyyy

DateJS seems like a good library for parsing non standard date formats.

Edit: just checked ECMA-262 standard. Quoting from section 15.9.1.15:

Date Time String Format

ECMAScript defines a string interchange format for date-times based upon a simplification of the ISO 8601 Extended Format. The format is as follows: YYYY-MM-DDTHH:mm:ss.sssZ Where the fields are as follows:

  • YYYY is the decimal digits of the year in the Gregorian calendar.
  • "-" (hyphon) appears literally twice in the string.
  • MM is the month of the year from 01 (January) to 12 (December).
  • DD is the day of the month from 01 to 31.
  • "T" appears literally in the string, to indicate the beginning of the time element.
  • HH is the number of complete hours that have passed since midnight as two decimal digits.
  • ":" (colon) appears literally twice in the string.
  • mm is the number of complete minutes since the start of the hour as two decimal digits.
  • ss is the number of complete seconds since the start of the minute as two decimal digits.
  • "." (dot) appears literally in the string.
  • sss is the number of complete milliseconds since the start of the second as three decimal digits. Both the "." and the milliseconds field may be omitted.
  • Z is the time zone offset specified as "Z" (for UTC) or either "+" or "-" followed by a time expression hh:mm

This format includes date-only forms:

  • YYYY
  • YYYY-MM
  • YYYY-MM-DD

It also includes time-only forms with an optional time zone offset appended:

  • THH:mm
  • THH:mm:ss
  • THH:mm:ss.sss

Also included are "date-times" which may be any combination of the above.

So, it seems that YYYY-MM-DD is included in the standard, but for some reason, Safari doesn't support it.

Update: after looking at datejs documentation, using it, your problem should be solved using code like this:

var myDate1 = Date.parseExact("29-11-2010", "dd-MM-yyyy");
var myDate2 = Date.parseExact("11-29-2010", "MM-dd-yyyy");
var myDate3 = Date.parseExact("2010-11-29", "yyyy-MM-dd");
var myDate4 = Date.parseExact("2010-29-11", "yyyy-dd-MM");

Alternative Windows shells, besides CMD.EXE?

I am a fan of Cmder, a package including clink, conemu, msysgit, and some cosmetic enhancements.

http://cmder.net/

https://github.com/cmderdev/cmder

https://chocolatey.org/packages/Cmder

enter image description here

CSS: fixed position on x-axis but not y?

Updated the script to check the start position:

function float_horizontal_scroll(id) {
var el = jQuery(id);
var isLeft = el.css('left') !== 'auto';
var start =((isLeft ? el.css('left') : el.css('right')).replace("px", ""));
jQuery(window).scroll(function () {
    var leftScroll = jQuery(this).scrollLeft();
    if (isLeft)
        el.css({ 'left': (start + leftScroll) + 'px' });
    else
        el.css({ 'right': (start - leftScroll) + 'px' });
});

}

How to sort by two fields in Java?

I would be careful when using Guava's ComparisonChain because it creates an instance of it per element been compared so you would be looking at a creation of N x Log N comparison chains just to compare if you are sorting, or N instances if you are iterating and checking for equality.

I would instead create a static Comparator using the newest Java 8 API if possible or Guava's Ordering API which allows you to do that, here is an example with Java 8:

import java.util.Comparator;
import static java.util.Comparator.naturalOrder;
import static java.util.Comparator.nullsLast;

private static final Comparator<Person> COMPARATOR = Comparator
  .comparing(Person::getName, nullsLast(naturalOrder()))
  .thenComparingInt(Person::getAge);

@Override
public int compareTo(@NotNull Person other) {
  return COMPARATOR.compare(this, other);
}

Here is how to use the Guava's Ordering API: https://github.com/google/guava/wiki/OrderingExplained

How do I add a foreign key to an existing SQLite table?

Create a foreign key to the existing SQLLite table:

There is no direct way to do that for SQL LITE. Run the below query to recreate STUDENTS table with foreign keys. Run the query after creating initial STUDENTS table and inserting data into the table.

CREATE TABLE    STUDENTS    (       
    STUDENT_ID  INT NOT NULL,   
    FIRST_NAME  VARCHAR(50) NOT NULL,   
    LAST_NAME   VARCHAR(50) NOT NULL,   
    CITY    VARCHAR(50) DEFAULT NULL,   
    BADGE_NO    INT DEFAULT NULL
    PRIMARY KEY(STUDENT_ID) 
);

Insert data into STUDENTS table.

Then Add FOREIGN KEY : making BADGE_NO as the foreign key of same STUDENTS table

BEGIN;
CREATE TABLE STUDENTS_new (
    STUDENT_ID  INT NOT NULL,   
    FIRST_NAME  VARCHAR(50) NOT NULL,   
    LAST_NAME   VARCHAR(50) NOT NULL,   
    CITY    VARCHAR(50) DEFAULT NULL,   
    BADGE_NO    INT DEFAULT NULL,
    PRIMARY KEY(STUDENT_ID) ,
    FOREIGN KEY(BADGE_NO) REFERENCES STUDENTS(STUDENT_ID)   
);
INSERT INTO STUDENTS_new SELECT * FROM STUDENTS;
DROP TABLE STUDENTS;
ALTER TABLE STUDENTS_new RENAME TO STUDENTS;
COMMIT;

we can add the foreign key from any other table as well.

Load and execute external js file in node.js with access to local variables?

If you are planning to load an external javascript file's functions or objects, load on this context using the following code – note the runInThisContext method:

var vm = require("vm");
var fs = require("fs");

var data = fs.readFileSync('./externalfile.js');
const script = new vm.Script(data);
script.runInThisContext();

// here you can use externalfile's functions or objects as if they were instantiated here. They have been added to this context. 

What's the simplest way to list conflicted files in Git?

The answer by Jones Agyemang is probably sufficient for most use cases and was a great starting point for my solution. For scripting in Git Bent, the git wrapper library I made, I needed something a bit more robust. I'm posting the prototype I've written which is not yet totally script-friendly

Notes

  • The linked answer checks for <<<<<<< HEAD which doesn't work for merge conflicts from using git stash apply which has <<<<<<< Updated Upstream
  • My solution confirms the presence of ======= & >>>>>>>
  • The linked answer is surely more performant, as it doesn't have to do as much
  • My solution does NOT provide line numbers

Print files with merge conflicts

You need the str_split_line function from below.

# Root git directory
dir="$(git rev-parse --show-toplevel)"
# Put the grep output into an array (see below)
str_split_line "$(grep -r "^<<<<<<< " "${dir})" files
bn="$(basename "${dir}")"
for i in "${files[@]}"; do 
    # Remove the matched string, so we're left with the file name  
    file="$(sed -e "s/:<<<<<<< .*//" <<< "${i}")"

    # Remove the path, keep the project dir's name  
    fileShort="${file#"${dir}"}"
    fileShort="${bn}${fileShort}"

    # Confirm merge divider & closer are present
    c1=$(grep -c "^=======" "${file}")
    c2=$(grep -c "^>>>>>>> " "${file}")
    if [[ c1 -gt 0 && c2 -gt 0 ]]; then
        echo "${fileShort} has a merge conflict"
    fi
done

Output

projectdir/file-name
projectdir/subdir/file-name

Split strings by line function

You can just copy the block of code if you don't want this as a separate function

function str_split_line(){
# for IFS, see https://stackoverflow.com/questions/16831429/when-setting-ifs-to-split-on-newlines-why-is-it-necessary-to-include-a-backspac
IFS="
"
    declare -n lines=$2
    while read line; do
        lines+=("${line}")
    done <<< "${1}"
}

Fast query runs slow in SSRS

In my case, I just had to disconnect and connect the SSMS. I profiled the query and the duration of execution was showing 1 minute even though the query itself runs under 2 seconds. Restarted the connection and ran again, this time the duration showed the correct execution time.

Ajax Upload image

You can use jquery.form.js plugin to upload image via ajax to the server.

http://malsup.com/jquery/form/

Here is the sample jQuery ajax image upload script

(function() {
$('form').ajaxForm({
    beforeSubmit: function() {  
        //do validation here


    },

    beforeSend:function(){
       $('#loader').show();
       $('#image_upload').hide();
    },
    success: function(msg) {

        ///on success do some here
    }
}); })();  

If you have any doubt, please refer following ajax image upload tutorial here

http://www.smarttutorials.net/ajax-image-upload-using-jquery-php-mysql/

How to submit a form when the return key is pressed?

I tried various javascript/jQuery-based strategies, but I kept having issues. The latest issue to arise involved accidental submission when the user uses the enter key to select from the browser's built-in auto-complete list. I finally switched to this strategy, which seems to work on all the browsers my company supports:

<div class="hidden-submit"><input type="submit" tabindex="-1"/></div>
.hidden-submit {
    border: 0 none;
    height: 0;
    width: 0;
    padding: 0;
    margin: 0;
    overflow: hidden;
}

This is similar to the currently-accepted answer by Chris Marasti-Georg, but by avoiding display: none, it appears to work correctly on all browsers.

Update

I edited the code above to include a negative tabindex so it doesn't capture the tab key. While this technically won't validate in HTML 4, the HTML5 spec includes language to make it work the way most browsers were already implementing it anyway.

How to Maximize a firefox browser window using Selenium WebDriver with node.js

Use this code:

driver.manage().window().maximize() 

works well,

Please make sure that you give enough time for the window to load before you declare this statement.

If you are finding any element to input some data then provide reasonable delay between this and the input statement.

SQL server 2008 backup error - Operating system error 5(failed to retrieve text for this error. Reason: 15105)

I've got the same error. I have been trying to fixing this by setting higher permission to account running SQL Client service, however it didnt help. The problem was that I run MS Sql Management studio just within my account. So, next time... assure that you are running it as Run as Administrator, if using Win7 with UAC enabled.

Is there a quick change tabs function in Visual Studio Code?

By default, Ctrl+Tab in Visual Studio Code cycles through tabs in order of most recently used. This is confusing because it depends on hidden state.

Web browsers cycle through tabs in visible order. This is much more intuitive.

To achieve this in Visual Studio Code, you have to edit keybindings.json. Use the Command Palette with CTRL+SHIFT+P, enter "Preferences: Open Keyboard Shortcuts (JSON)", and hit Enter.

Then add to the end of the file:

[
    // ...
    {
        "key": "ctrl+tab",
        "command": "workbench.action.nextEditor"
    },
    {
        "key": "ctrl+shift+tab",
        "command": "workbench.action.previousEditor"
    }
]

Alternatively, to only cycle through tabs of the current window/split view, you can use:

[
    {
        "key": "ctrl+tab",
        "command": "workbench.action.nextEditorInGroup"
    },
    {
        "key": "ctrl+shift+tab",
        "command": "workbench.action.previousEditorInGroup"
    }
]

Alternatively, you can use Ctrl+PageDown (Windows) or Cmd+Option+Right (Mac).

Calculate mean and standard deviation from a vector of samples in C++ using Boost

Using accumulators is the way to compute means and standard deviations in Boost.

accumulator_set<double, stats<tag::variance> > acc;
for_each(a_vec.begin(), a_vec.end(), bind<void>(ref(acc), _1));

cout << mean(acc) << endl;
cout << sqrt(variance(acc)) << endl;

 

DateTime.ToString("MM/dd/yyyy HH:mm:ss.fff") resulted in something like "09/14/2013 07.20.31.371"

You can use String.Format:

DateTime d = DateTime.Now;
string str = String.Format("{0:00}/{1:00}/{2:0000} {3:00}:{4:00}:{5:00}.{6:000}", d.Month, d.Day, d.Year, d.Hour, d.Minute, d.Second, d.Millisecond);
// I got this result: "02/23/2015 16:42:38.234"

How can I change the value of the elements in a vector?

You can access the values in a vector just as you access any other array.

for (int i = 0; i < v.size(); i++)
{         
  v[i] -= 1;         
} 

Cannot open database "test" requested by the login. The login failed. Login failed for user 'xyz\ASPNET'

I have not seen this mentioned in the previous issues, so let me throw out another possibility. It could be that IFItest is not reachable or simply does not exist. For example, if one has a number of configurations, each with its own database, it could be that the database name was not changed to the correct one for the current configuration.

How do I sort strings alphabetically while accounting for value when a string is numeric?

This seems a weird request and deserves a weird solution:

string[] sizes = new string[] { "105", "101", "102", "103", "90" };

foreach (var size in sizes.OrderBy(x => {
    double sum = 0;
    int position = 0;
    foreach (char c in x.ToCharArray().Reverse()) {
        sum += (c - 48) * (int)(Math.Pow(10,position));
        position++;
    }
    return sum;
}))

{
    Console.WriteLine(size);
}

The given key was not present in the dictionary. Which key?

In the general case, the answer is No.

However, you can set the debugger to break at the point where the exception is first thrown. At that time, the key which was not present will be accessible as a value in the call stack.

In Visual Studio, this option is located here:

Debug → Exceptions... → Common Language Runtime Exceptions → System.Collections.Generic

There, you can check the Thrown box.


For more specific instances where information is needed at runtime, provided your code uses IDictionary<TKey, TValue> and not tied directly to Dictionary<TKey, TValue>, you can implement your own dictionary class which provides this behavior.

Bootstrap Alert Auto Close

I found this to be a better solution

$(".alert-dismissible").fadeTo(2000, 500).slideUp(500, function(){
    $(".alert-dismissible").alert('close');
});

UILabel - auto-size label to fit text?

Please check out my gist where I have made a category for UILabel for something very similar, my category lets a UILabel stretch it's height to show all the content: https://gist.github.com/1005520

Or check out this post: https://stackoverflow.com/a/7242981/662605

This would stretch the height, but you can change it around easily to work the other way and stretch the width with something like this, which is I believe what you want to do:

@implementation UILabel (dynamicSizeMeWidth)

- (void)resizeToStretch{
    float width = [self expectedWidth];
    CGRect newFrame = [self frame];
    newFrame.size.width = width;
    [self setFrame:newFrame];
}

- (float)expectedWidth{
    [self setNumberOfLines:1];

    CGSize maximumLabelSize = CGSizeMake(CGRectGetWidth(self.bounds), CGFLOAT_MAX);

    CGSize expectedLabelSize = [[self text] sizeWithFont:[self font] 
                                            constrainedToSize:maximumLabelSize
                                            lineBreakMode:[self lineBreakMode]]; 
    return expectedLabelSize.width;
}

@end

You could more simply use the sizeToFit method available from the UIView class, but set the number of lines to 1 to be safe.


iOS 6 update

If you are using AutoLayout, then you have a built in solution. By setting the number of lines to 0, the framework will resize your label appropriately (adding more height) to fit your text.


iOS 8 update

sizeWithFont: is deprecated so use sizeWithAttributes: instead:

- (float)expectedWidth{
    [self setNumberOfLines:1];

    CGSize expectedLabelSize = [[self text] sizeWithAttributes:@{NSFontAttributeName:self.font}];

    return expectedLabelSize.width;
}

Create a Path from String in Java7

From the javadocs..http://docs.oracle.com/javase/tutorial/essential/io/pathOps.html

Path p1 = Paths.get("/tmp/foo"); 

is the same as

Path p4 = FileSystems.getDefault().getPath("/tmp/foo");

Path p3 = Paths.get(URI.create("file:///Users/joe/FileTest.java"));

Path p5 = Paths.get(System.getProperty("user.home"),"logs", "foo.log"); 

In Windows, creates file C:\joe\logs\foo.log (assuming user home as C:\joe)
In Unix, creates file /u/joe/logs/foo.log (assuming user home as /u/joe)

Convert a RGB Color Value to a Hexadecimal String

You can use

String hex = String.format("#%02x%02x%02x", r, g, b);  

Use capital X's if you want your resulting hex-digits to be capitalized (#FFFFFF vs. #ffffff).

How do I delete unpushed git commits?

Delete the most recent commit, keeping the work you've done:

git reset --soft HEAD~1

Delete the most recent commit, destroying the work you've done:

git reset --hard HEAD~1

Clear text field value in JQuery

You are comparing doc_val_check with an empty string. You want to assign the empty string to doc_val_check

so it should be this:

doc_val_check = "";

What are my options for storing data when using React Native? (iOS and Android)

We dont need redux-persist we can simply use redux for persistance.

react-redux + AsyncStorage = redux-persist

so inside createsotre file simply add these lines

store.subscribe(async()=> await AsyncStorage.setItem("store", JSON.stringify(store.getState())))

this will update the AsyncStorage whenever there are some changes in the redux store.

Then load the json converted store. when ever the app loads. and set the store again.

Because redux-persist creates issues when using wix react-native-navigation. If that's the case then I prefer to use simple redux with above subscriber function

How to watch for form changes in Angular

To complete a bit more previous great answers, you need to be aware that forms leverage observables to detect and handle value changes. It's something really important and powerful. Both Mark and dfsq described this aspect in their answers.

Observables allow not only to use the subscribe method (something similar to the then method of promises in Angular 1). You can go further if needed to implement some processing chains for updated data in forms.

I mean you can specify at this level the debounce time with the debounceTime method. This allows you to wait for an amount of time before handling the change and correctly handle several inputs:

this.form.valueChanges
    .debounceTime(500)
    .subscribe(data => console.log('form changes', data));

You can also directly plug the processing you want to trigger (some asynchronous one for example) when values are updated. For example, if you want to handle a text value to filter a list based on an AJAX request, you can leverage the switchMap method:

this.textValue.valueChanges
    .debounceTime(500)
    .switchMap(data => this.httpService.getListValues(data))
    .subscribe(data => console.log('new list values', data));

You even go further by linking the returned observable directly to a property of your component:

this.list = this.textValue.valueChanges
    .debounceTime(500)
    .switchMap(data => this.httpService.getListValues(data))
    .subscribe(data => console.log('new list values', data));

and display it using the async pipe:

<ul>
  <li *ngFor="#elt of (list | async)">{{elt.name}}</li>
</ul>

Just to say that you need to think the way to handle forms differently in Angular2 (a much more powerful way ;-)).

Hope it helps you, Thierry

Get to UIViewController from UIView?

Using the example posted by Brock, I modified it so that it is a category of UIView instead UIViewController and made it recursive so that any subview can (hopefully) find the parent UIViewController.

@interface UIView (FindUIViewController)
- (UIViewController *) firstAvailableUIViewController;
- (id) traverseResponderChainForUIViewController;
@end

@implementation UIView (FindUIViewController)
- (UIViewController *) firstAvailableUIViewController {
    // convenience function for casting and to "mask" the recursive function
    return (UIViewController *)[self traverseResponderChainForUIViewController];
}

- (id) traverseResponderChainForUIViewController {
    id nextResponder = [self nextResponder];
    if ([nextResponder isKindOfClass:[UIViewController class]]) {
        return nextResponder;
    } else if ([nextResponder isKindOfClass:[UIView class]]) {
        return [nextResponder traverseResponderChainForUIViewController];
    } else {
        return nil;
    }
}
@end

To use this code, add it into an new class file (I named mine "UIKitCategories") and remove the class data... copy the @interface into the header, and the @implementation into the .m file. Then in your project, #import "UIKitCategories.h" and use within the UIView code:

// from a UIView subclass... returns nil if UIViewController not available
UIViewController * myController = [self firstAvailableUIViewController];

Localhost not working in chrome and firefox

I faced the same issue and the complete solution is to set to false(uncheck) the "Automatically detect settings" checkbox from Lan Area Network( the same window as for Bypass proxy server for local address )

Pandas: Return Hour from Datetime Column Directly

Assuming timestamp is the index of the data frame, you can just do the following:

hours = sales.index.hour

If you want to add that to your sales data frame, just do:

import pandas as pd
pd.concat([sales, pd.DataFrame(hours, index=sales.index)], axis = 1)

Edit: If you have several columns of datetime objects, it's the same process. If you have a column ['date'] in your data frame, and assuming that 'date' has datetime values, you can access the hour from the 'date' as:

hours = sales['date'].hour

Edit2: If you want to adjust a column in your data frame you have to include dt:

sales['datehour'] = sales['date'].dt.hour

How can I get the Google cache age of any URL or web page?

You can use this site: https://cachedviews.com/ . Cache View or Cached Pages of Any Website - Google Cached Pages of Any Website

Parse error: syntax error, unexpected T_ECHO in

Missing ; after var_dump($row)

using lodash .groupBy. how to add your own keys for grouped output?

Isn't it this simple?

var result = _(data)
            .groupBy(x => x.color)
            .map((value, key) => ({color: key, users: value}))
            .value();

How to use && in EL boolean expressions in Facelets?

In addition to the answer of BalusC, use the following Java RegExp to replace && with and:

Search:  (#\{[^\}]*)(&&)([^\}]*\})
Replace: $1and$3

You have run this regular expression replacement multiple times to find all occurences in case you are using >2 literals in your EL expressions. Mind to replace the leading # by $ if your EL expression syntax differs.

Get single listView SelectedItem

Sometimes using only the line below throws me an Exception,

String text = listView1.SelectedItems[0].Text; 

so I use this code below:

private void listView1_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    if (listView1.SelectedIndices.Count <= 0) 
    { 
        return; 
    } 
    int intselectedindex = listView1.SelectedIndices[0]; 
    if (intselectedindex >= 0) 
    {
        String text = listView1.Items[intselectedindex].Text;

        //do something
        //MessageBox.Show(listView1.Items[intselectedindex].Text); 
    } 
}

How do I make a comment in a Dockerfile?

Use the # syntax for comments

From: https://docs.docker.com/engine/reference/builder/#format

# My comment here
RUN echo 'we are running some cool things'

How to format strings using printf() to get equal length in the output

Additionally, if you want the flexibility of choosing the width, you can choose between one of the following two formats (with or without truncation):

int width = 30;
// No truncation uses %-*s
printf( "%-*s %s\n", width, "Starting initialization...", "Ok." );
// Output is "Starting initialization...     Ok."

// Truncated to the specified width uses %-.*s
printf( "%-.*s %s\n", width, "Starting initialization...", "Ok." );
// Output is "Starting initialization... Ok."

Programmatically navigate using react router V4

Step 1: There is only one thing to import on top:

import {Route} from 'react-router-dom';

Step 2: In your Route, pass the history:

<Route
  exact
  path='/posts/add'
  render={({history}) => (
    <PostAdd history={history} />
  )}
/>

Step 3: history gets accepted as part of props in the next Component, so you can simply:

this.props.history.push('/');

That was easy and really powerful.

Python Unicode Encode Error

Likely, your problem is that you parsed it okay, and now you're trying to print the contents of the XML and you can't because theres some foreign Unicode characters. Try to encode your unicode string as ascii first:

unicodeData.encode('ascii', 'ignore')

the 'ignore' part will tell it to just skip those characters. From the python docs:

>>> # Python 2: u = unichr(40960) + u'abcd' + unichr(1972)
>>> u = chr(40960) + u'abcd' + chr(1972)
>>> u.encode('utf-8')
'\xea\x80\x80abcd\xde\xb4'
>>> u.encode('ascii')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
UnicodeEncodeError: 'ascii' codec can't encode character '\ua000' in position 0: ordinal not in range(128)
>>> u.encode('ascii', 'ignore')
'abcd'
>>> u.encode('ascii', 'replace')
'?abcd?'
>>> u.encode('ascii', 'xmlcharrefreplace')
'&#40960;abcd&#1972;'

You might want to read this article: http://www.joelonsoftware.com/articles/Unicode.html, which I found very useful as a basic tutorial on what's going on. After the read, you'll stop feeling like you're just guessing what commands to use (or at least that happened to me).