Programs & Examples On #Cllocationmanager

The CLLocationManager class defines the interface for configuring the delivery of location- and heading-related events to your application

How can I get current location from user in iOS

In Swift (for iOS 8+).

Info.plist

First things first. You need to add your descriptive string in the info.plist file for the keys NSLocationWhenInUseUsageDescription or NSLocationAlwaysUsageDescription depending on what kind of service you are requesting

Code

import Foundation
import CoreLocation

class LocationManager: NSObject, CLLocationManagerDelegate {
    
    let manager: CLLocationManager
    var locationManagerClosures: [((userLocation: CLLocation) -> ())] = []
    
    override init() {
        self.manager = CLLocationManager()
        super.init()
        self.manager.delegate = self
    }
    
    //This is the main method for getting the users location and will pass back the usersLocation when it is available
    func getlocationForUser(userLocationClosure: ((userLocation: CLLocation) -> ())) {
        
        self.locationManagerClosures.append(userLocationClosure)
        
        //First need to check if the apple device has location services availabel. (i.e. Some iTouch's don't have this enabled)
        if CLLocationManager.locationServicesEnabled() {
            //Then check whether the user has granted you permission to get his location
            if CLLocationManager.authorizationStatus() == .NotDetermined {
                //Request permission
                //Note: you can also ask for .requestWhenInUseAuthorization
                manager.requestWhenInUseAuthorization()
            } else if CLLocationManager.authorizationStatus() == .Restricted || CLLocationManager.authorizationStatus() == .Denied {
                //... Sorry for you. You can huff and puff but you are not getting any location
            } else if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse {
                // This will trigger the locationManager:didUpdateLocation delegate method to get called when the next available location of the user is available
                manager.startUpdatingLocation()
            }
        }
        
    }
    
    //MARK: CLLocationManager Delegate methods
    
    @objc func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
        if status == .AuthorizedAlways || status == .AuthorizedWhenInUse {
            manager.startUpdatingLocation()
        }
    }
    
    func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) {
        //Because multiple methods might have called getlocationForUser: method there might me multiple methods that need the users location.
        //These userLocation closures will have been stored in the locationManagerClosures array so now that we have the users location we can pass the users location into all of them and then reset the array.
        let tempClosures = self.locationManagerClosures
        for closure in tempClosures {
            closure(userLocation: newLocation)
        }
        self.locationManagerClosures = []
    }
}

Usage

self.locationManager = LocationManager()
self.locationManager.getlocationForUser { (userLocation: CLLocation) -> () in
            print(userLocation)
        }

Get User's Current Location / Coordinates

Import library like:

import CoreLocation

set Delegate:

CLLocationManagerDelegate

Take variable like:

var locationManager:CLLocationManager!

On viewDidLoad() write this pretty code:

 locationManager = CLLocationManager()
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestAlwaysAuthorization()

    if CLLocationManager.locationServicesEnabled(){
        locationManager.startUpdatingLocation()
    }

Write CLLocation delegate methods:

    //MARK: - location delegate methods
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let userLocation :CLLocation = locations[0] as CLLocation

    print("user latitude = \(userLocation.coordinate.latitude)")
    print("user longitude = \(userLocation.coordinate.longitude)")

    self.labelLat.text = "\(userLocation.coordinate.latitude)"
    self.labelLongi.text = "\(userLocation.coordinate.longitude)"

    let geocoder = CLGeocoder()
    geocoder.reverseGeocodeLocation(userLocation) { (placemarks, error) in
        if (error != nil){
            print("error in reverseGeocode")
        }
        let placemark = placemarks! as [CLPlacemark]
        if placemark.count>0{
            let placemark = placemarks![0]
            print(placemark.locality!)
            print(placemark.administrativeArea!)
            print(placemark.country!)

            self.labelAdd.text = "\(placemark.locality!), \(placemark.administrativeArea!), \(placemark.country!)"
        }
    }

}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
    print("Error \(error)")
}

Now set permission for access the location, so add these key value into your info.plist file

 <key>NSLocationAlwaysUsageDescription</key>
<string>Will you allow this app to always know your location?</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>Do you allow this app to know your current location?</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Do you allow this app to know your current location?</string>

enter image description here

100% working without any issue. TESTED

Location Services not working in iOS 8

I get a similar error in iOS9 (working with Xcode 7 and Swift 2): Trying to start MapKit location updates without prompting for location authorization. Must call -[CLLocationManager requestWhenInUseAuthorization] or -[CLLocationManager requestAlwaysAuthorization] first. I was following a tutorial but the tutor was using iOS8 and Swift 1.2. There are some changes in Xcode 7 and Swift 2, I found this code and it works fine for me (if somebody needs help):

import UIKit
import MapKit
import CoreLocation

class MapViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {

    // MARK: Properties
    @IBOutlet weak var mapView: MKMapView!

    let locationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()

        self.locationManager.delegate = self
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
        self.locationManager.requestWhenInUseAuthorization()
        self.locationManager.startUpdatingLocation()
        self.mapView.showsUserLocation = true

    }

    // MARK: - Location Delegate Methods

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let location = locations.last
        let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)
        let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 1, longitudeDelta: 1))
        self.mapView.setRegion(region, animated: true)
    }

    func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
        print("Errors: " + error.localizedDescription)
    }
}

Finally, I put that in info.plist: Information Property List: NSLocationWhenInUseUsageDescription Value: App needs location servers for staff

Show Current Location and Update Location in MKMapView in Swift

Hi Sometimes setting the showsUserLocation in code doesn't work for some weird reason.

So try a combination of the following.

In viewDidLoad()

  self.mapView.showsUserLocation = true

Go to your storyboard in Xcode, on the right panel's attribute inspector tick the User location check box, like in the attached image. run your app and you should be able to see the User location

enter image description here

Posting form to different MVC post action depending on the clicked submit button

you can use ajax calls to call different methods without a postback

$.ajax({
    type: "POST",
     url: "@(Url.Action("Action", "Controller"))",
     data: {id: 'id', id1: 'id1' },
     contentType: "application/json; charset=utf-8",
     cache: false,
     async: true,
     success: function (result) {
        //do something
     }
});

What is the difference between Views and Materialized Views in Oracle?

Materialized views are disk based and are updated periodically based upon the query definition.

Views are virtual only and run the query definition each time they are accessed.

How do I grant read access for a user to a database in SQL Server?

This is a two-step process:

  1. you need to create a login to SQL Server for that user, based on its Windows account

    CREATE LOGIN [<domainName>\<loginName>] FROM WINDOWS;
    
  2. you need to grant this login permission to access a database:

    USE (your database)
    CREATE USER (username) FOR LOGIN (your login name)
    

Once you have that user in your database, you can give it any rights you want, e.g. you could assign it the db_datareader database role to read all tables.

USE (your database)
EXEC sp_addrolemember 'db_datareader', '(your user name)'

accessing a file using [NSBundle mainBundle] pathForResource: ofType:inDirectory:

Go to "Target" -> "Build Phases", select your target, select the “Build Phases” tab, click “Add Build Phase”, and select “Add Copy Files”. Change the destination to “Products Directory”. Drag your file into the “Add files” section.

How to compare type of an object in Python?

It is because you have to write

s="hello"
type(s) == type("")

type accepts an instance and returns its type. In this case you have to compare two instances' types.

If you need to do preemptive checking, it is better if you check for a supported interface than the type.

The type does not really tell you much, apart of the fact that your code want an instance of a specific type, regardless of the fact that you could have another instance of a completely different type which would be perfectly fine because it implements the same interface.

For example, suppose you have this code

def firstElement(parameter):
    return parameter[0]

Now, suppose you say: I want this code to accept only a tuple.

import types

def firstElement(parameter):
    if type(parameter) != types.TupleType:
         raise TypeError("function accepts only a tuple")
    return parameter[0]

This is reducing the reusability of this routine. It won't work if you pass a list, or a string, or a numpy.array. Something better would be

def firstElement(parameter):
    if not (hasattr(parameter, "__getitem__") and callable(getattr(parameter,"__getitem__"))):
        raise TypeError("interface violation")
    return parameter[0]

but there's no point in doing it: parameter[0] will raise an exception if the protocol is not satisfied anyway... this of course unless you want to prevent side effects or having to recover from calls that you could invoke before failing. (Stupid) example, just to make the point:

def firstElement(parameter):
    if not (hasattr(parameter, "__getitem__") and callable(getattr(parameter,"__getitem__"))):
        raise TypeError("interface violation")
    os.system("rm file")
    return parameter[0]

in this case, your code will raise an exception before running the system() call. Without interface checks, you would have removed the file, and then raised the exception.

Get product id and product type in magento?

IN MAGENTO query in the database and fetch the result like. product id, product name and manufracturer with out using the product flat table use the eav catalog_product_entity and its attribute table product_id product_name manufacturer 1 | PRODUCTA | NOKIA 2 | PRODUCTB | SAMSUNG

How to allow only a number (digits and decimal point) to be typed in an input?

Here's my really quick-n-dirty one:

<!-- HTML file -->
<html ng-app="num">
  <head></head>
  <body ng-controller="numCtrl">
    <form class="digits" name="digits" ng-submit="getGrades()" novalidate >
      <input type="text" placeholder="digits here plz" name="nums" ng-model="nums" required ng-pattern="/^(\d)+$/" />
      <p class="alert" ng-show="digits.nums.$error.pattern">Numbers only, please.</p> 
      <br>
      <input type="text" placeholder="txt here plz" name="alpha" ng-model="alpha" required ng-pattern="/^(\D)+$/" />
      <p class="alert" ng-show="digits.alpha.$error.pattern">Text only, please.</p>
      <br>
      <input class="btn" type="submit" value="Do it!" ng-disabled="!digits.$valid" />
    </form>
  </body>
</html>

// Javascript file
var app = angular.module('num', ['ngResource']);
app.controller('numCtrl', function($scope, $http){
  $scope.digits = {};
});

This requires you include the angular-resource library for persistent bindings to the fields for validation purposes.

Working example here

Works like a champ in 1.2.0-rc.3+. Modify the regex and you should be all set. Perhaps something like /^(\d|\.)+$/ ? As always, validate server-side when you're done.

CSS Box Shadow - Top and Bottom Only

So this is my first answer here, and because I needed something similar I did with pseudo elements for 2 inner shadows, and an extra DIV for an upper outer shadow. Don't know if this is the best solutions but maybe it will help someone.

HTML

<div class="shadow-block">
    <div class="shadow"></div>
    <div class="overlay">
        <div class="overlay-inner">
            content here
        </div>
    </div>
</div>

CSS

.overlay {
    background: #f7f7f4;
    height: 185px;
    overflow: hidden;
    position: relative;
    width: 100%; 
}

.overlay:before {
    border-radius: 50% 50% 50% 50%;
    box-shadow: 0 0 50px 2px rgba(1, 1, 1, 0.6);
    content: " ";
    display: block;
    margin: 0 auto;
    width: 80%;
}

.overlay:after {
    border-radius: 50% 50% 50% 50%;
    box-shadow: 0 0 70px 5px rgba(1, 1, 1, 0.5);
    content: "-";
    display: block;
    margin: 0 auto;
    position: absolute;
    bottom: -65px;
    left: -50%;
    right: -50%;
    width: 80%;
}

.shadow {
    position: relative;
    width:100%;
    height:8px;
    margin: 0 0 -22px 0;
    -webkit-box-shadow: 0px 0px 50px 3px rgba(1, 1, 1, 0.6);
    box-shadow: 0px 0px 50px 3px rgba(1, 1, 1, 0.6);
    border-radius: 50%;
}

How copy data from Excel to a table using Oracle SQL Developer

None of these options show up for me. The way to paste data from Excel is as follows:

  • Add an extra column to the left of your spreadsheet data (if you don't have row numbers showing in PL/SQL Developer you may not have to have an extra empty column to the left).

  • Copy the rows of data from your spreadsheet including the empty column.

  • In PL/SQL Developer, open your table in edit mode. You can right-click the table name in the object browser and select Edit Data or write your own select statement that includes the rowid and click the lock icon. Be sure your columns are ordered the same as in your spreadsheet.

  • Here's the part that took me forever to figure out: click on the left side of the first empty row to highlight it. It will not work if you don't have the first empty row highlighted.

  • Paste as usual using Ctrl+V or right-click Paste.

I couldn't find this info anywhere when I needed it, so I wanted to be sure to post it.

Optional args in MATLAB functions

A simple way of doing this is via nargin (N arguments in). The downside is you have to make sure that your argument list and the nargin checks match.

It is worth remembering that all inputs are optional, but the functions will exit with an error if it calls a variable which is not set. The following example sets defaults for b and c. Will exit if a is not present.

function [ output_args ] = input_example( a, b, c )
if nargin < 1
  error('input_example :  a is a required input')
end

if nargin < 2
  b = 20
end

if nargin < 3
  c = 30
end
end

How to pretty print XML from the command line?

Without installing anything on macOS / most Unix.

Use tidy

cat filename.xml | tidy -xml -iq

Redirecting viewing a file with cat to tidy specifying the file type of xml and to indent while quiet output will suppress error output. JSON also works with -json.

Create a circular button in BS3

Use font-awesome stacked icons (alternative to bootstrap badges). Here are more examples: http://fontawesome.io/examples/

_x000D_
_x000D_
 .no-border {_x000D_
        border: none;_x000D_
        background-color: white;_x000D_
        outline: none;_x000D_
        cursor: pointer;_x000D_
    }_x000D_
.color-no-focus {_x000D_
        color: grey;_x000D_
    }_x000D_
  .hover:hover {_x000D_
        color: blue;_x000D_
    }_x000D_
 .white {_x000D_
        color: white;_x000D_
    }
_x000D_
<button type="button" (click)="doSomething()" _x000D_
class="hover color-no-focus no-border fa-stack fa-lg">_x000D_
<i class="color-focus fa fa-circle fa-stack-2x"></i>_x000D_
<span class="white fa-stack-1x">1</span>_x000D_
</button>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
_x000D_
_x000D_
_x000D_

How to set IntelliJ IDEA Project SDK

For a new project select the home directory of the jdk

eg C:\Java\jdk1.7.0_99 or C:\Program Files\Java\jdk1.7.0_99

For an existing project.

1) You need to have a jdk installed on the system.

for instance in

C:\Java\jdk1.7.0_99

2) go to project structure under File menu ctrl+alt+shift+S

3) SDKs is located under Platform Settings. Select it.

4) click the green + up the top of the window.

5) select JDK (I have to use keyboard to select it do not know why).

select the home directory for your jdk installation.

should be good to go.

How do I concatenate text in a query in sql server?

You have to explicitly cast the string types to the same in order to concatenate them, In your case you may solve the issue by simply addig an 'N' in front of 'SomeText' (N'SomeText'). If that doesn't work, try Cast('SomeText' as nvarchar(8)).

How can I add a line to a file in a shell script?

sed is line based, so I'm not sure why you want to do this with sed. The paradigm is more processing one line at a time( you could also programatically find the # of fields in the CSV and generate your header line with awk) Why not just

echo "c1, c2, ... " >> file
cat testfile.csv >> file

?

TypeScript: casting HTMLElement

Just to clarify, this is correct.

Cannot convert 'NodeList' to 'HTMLScriptElement[]'

as a NodeList is not an actual array (e.g. it doesn't contain .forEach, .slice, .push, etc...).

Thus if it did convert to HTMLScriptElement[] in the type system, you'd get no type errors if you tried to call Array.prototype members on it at compile time, but it would fail at run time.

List all liquibase sql types

For checking type conversions in version 3, you can go to their github and check into the different liquibase types and check the method toDatabaseDataType. For example, for Boolean, you can check here:

https://github.com/liquibase/liquibase/blob/master/liquibase-core/src/main/java/liquibase/datatype/core/BooleanType.java

For version 2.0.x, the conversion seems to be into database specific classes. For example, for Mysql:

https://github.com/liquibase/liquibase/blob/2_0_x/liquibase-core/src/main/java/liquibase/database/typeconversion/core/MySQLTypeConverter.java

VBA module that runs other modules

Is "Module1" part of the same workbook that contains "moduleController"?
If not, you could call public method of "Module1" using Application.Run someWorkbook.xlsm!methodOfModule.

Checking if form has been submitted - PHP

Try this

 <form action="" method="POST" id="formaddtask">
      Add Task: <input type="text"name="newtaskname" />
      <input type="submit" value="Submit"/>
 </form>

    //Check if the form is submitted
    if($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['newtaskname'])){

    }

How to Convert a Text File into a List in Python

Going with what you've started:

row = [[]] 
crimefile = open(fileName, 'r') 
for line in crimefile.readlines(): 
    tmp = []
    for element in line[0:-1].split(','):
        tmp.append(element)
row.append(tmp)

Jquery Ajax Loading image

Try something like this:

<div id="LoadingImage" style="display: none">
  <img src="" />
</div>

<script>
  function ajaxCall(){
    $("#LoadingImage").show();
      $.ajax({ 
        type: "GET", 
        url: surl, 
        dataType: "jsonp", 
        cache : false, 
        jsonp : "onJSONPLoad", 
        jsonpCallback: "newarticlescallback", 
        crossDomain: "true", 
        success: function(response) { 
          $("#LoadingImage").hide();
          alert("Success"); 
        }, 
        error: function (xhr, status) {  
          $("#LoadingImage").hide();
          alert('Unknown error ' + status); 
        }    
      });  
    }
</script>

How to convert ISO8859-15 to UTF8?

Could it be that your file is not ISO-8859-15 encoded? You should be able to check with the file command:

file YourFile.txt

Also, you can use iconv without providing the encoding of the original file:

iconv -t UTF-8 YourFile.txt

Unable to Build using MAVEN with ERROR - Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile

For my situation, I switched the value of "fork" to false, such as <fork>false</fork>. I do not understand why, hope someone could explain to me. Thanks in advance.

How to do a for loop in windows command line?

This may help you find what you're looking for... Batch script loop

My answer is as follows:

@echo off
:start
set /a var+=1
if %var% EQU 100 goto end
:: Code you want to run goes here
goto start

:end
echo var has reached %var%.
pause
exit

The first set of commands under the start label loops until a variable, %var% reaches 100. Once this happens it will notify you and allow you to exit. This code can be adapted to your needs by changing the 100 to 17 and putting your code or using a call command followed by the batch file's path (Shift+Right Click on file and select "Copy as Path") where the comment is placed.

Load local JSON file into variable

The built-in node.js module fs will do it either asynchronously or synchronously depending on your needs.

You can load it using var fs = require('fs');

Asynchronous

fs.readFile('./content.json', (err, data) => {
    if (err)
      console.log(err);
    else {
      var json = JSON.parse(data);
    //your code using json object
    }
})

Synchronous

var json = JSON.parse(fs.readFileSync('./content.json').toString());

What does the function then() mean in JavaScript?

Another example:

_x000D_
_x000D_
new Promise(function(ok) {
   ok( 
      /* myFunc1(param1, param2, ..) */
   )
}).then(function(){
     /* myFunc1 succeed */
     /* Launch something else */
     /* console.log(whateverparam1) */
     /* myFunc2(whateverparam1, otherparam, ..) */
}).then(function(){
     /* myFunc2 succeed */
     /* Launch something else */
     /* myFunc3(whatever38, ..) */
})
_x000D_
_x000D_
_x000D_

The same logic using arrow functions shorthand.

?? This can cause issues with multiple calls see comments!

The syntax of the first snippet using plain function is preferable here.

_x000D_
_x000D_
new Promise((ok) =>
   ok( 
      /* myFunc1(param1, param2, ..) */
)).then(() =>
     /* myFunc1 succeed */
     /* Launch something else */
     /* Only ONE call or statment can be made inside arrow functions */
     /* For example, using console.log here will break everything */
     /* myFunc2(whateverparam1, otherparam, ..) */
).then(() =>
     /* myFunc2 succeed */
     /* Launch something else */
     /* Only ONE call or statment can be made inside arrow functions */
     /* For example, using console.log here will break everything */
     /* myFunc3(whatever38, ..) */
)
_x000D_
_x000D_
_x000D_

How to activate "Share" button in android app?

Share Any File as below ( Kotlin ) :
first create a folder named xml in the res folder and create a new XML Resource File named provider_paths.xml and put the below code inside it :

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <files-path
        name="files"
        path="."/>

    <external-path
        name="external_files"
        path="."/>
</paths>

now go to the manifests folder and open the AndroidManifest.xml and then put the below code inside the <application> tag :

<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
    android:name="android.support.FILE_PROVIDER_PATHS"
    android:resource="@xml/provider_paths" /> // provider_paths.xml file path in this example
</provider>

now you put the below code in the setOnLongClickListener :

share_btn.setOnClickListener {
    try {
        val file = File("pathOfFile")
        if(file.exists()) {
            val uri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", file)
            val intent = Intent(Intent.ACTION_SEND)
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            intent.setType("*/*")
            intent.putExtra(Intent.EXTRA_STREAM, uri)
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent)
        }
    } catch (e: java.lang.Exception) {
        e.printStackTrace()
        toast("Error")
    }
}

Disable keyboard on EditText

This worked for me. First add this android:windowSoftInputMode="stateHidden" in your android manifest file, under your activity. like below:

<activity ... android:windowSoftInputMode="stateHidden">

Then on onCreate method of youractivity, add the foloowing code:

EditText editText = (EditText)findViewById(R.id.edit_text);
edit_text.setOnTouchListener(new OnTouchListener() {

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        v.onTouchEvent(event);
        InputMethodManager inputMethod = (InputMethodManager)v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputMethod!= null) {
            inputMethod.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }                
        return true;
    }
});

Then if you want the pointer to be visible add this on your xml android:textIsSelectable="true".

This will make the pointer visible. In this way the keyboard will not popup when your activity starts and also will be hidden when you click on the edittext.

Usages of doThrow() doAnswer() doNothing() and doReturn() in mockito

To add a bit to accepted answer ...

If you get an UnfinishedStubbingException, be sure to set the method to be stubbed after the when closure, which is different than when you write Mockito.when

Mockito.doNothing().when(mock).method()    //method is declared after 'when' closes

Mockito.when(mock.method()).thenReturn(something)   //method is declared inside 'when'

How to style SVG with external CSS?

You can include in your SVG files link to external css file using:

<link xmlns="http://www.w3.org/1999/xhtml" rel="stylesheet" href="mystyles.css" type="text/css"/>

You need to put this after opening tag:

<svg>
  <link xmlns="http://www.w3.org/1999/xhtml" rel="stylesheet" href="mystyles.css" type="text/css"/>
  <g>
    <path d=.../>
  </g>
</svg>

It's not perfect solution, because you have to modify svg files, but you modify them once and than all styling changes can be done in one css file for all svg files.

Minimum Hardware requirements for Android development

Hey, I have used the same software on an AMD 3Ghz chip, dual core. had 2gbs of ram at the time, and i noticed the emulator ran at an alright speed, but took a ridiculous amount of time to load. I have not done enough development on Android to tell you if this is a common, or even still existing problem, but it is certainly something I remember from my experience.

Remove useless zero digits from decimals in PHP

Ultimate Solution: The only safe way is to use regex:

echo preg_replace("/\.?0+$/", "", 3.0); // 3
echo preg_replace("/\d+\.?\d*(\.?0+)/", "", 3.0); // 3

it will work for any case

Installing Apache Maven Plugin for Eclipse

I found Maven Integration for Eclipse here.

http://download.eclipse.org/technology/m2e/releases

After installing restart eclipse. Worked for me running Eclipse Juno.

How to fill in proxy information in cntlm config file?

The solution takes two steps!

First, complete the user, domain, and proxy fields in cntlm.ini. The username and domain should probably be whatever you use to log in to Windows at your office, eg.

Username            employee1730
Domain              corporate
Proxy               proxy.infosys.corp:8080

Then test cntlm with a command such as

cntlm.exe -c cntlm.ini -I -M http://www.bbc.co.uk

It will ask for your password (again whatever you use to log in to Windows_). Hopefully it will print 'http 200 ok' somewhere, and print your some cryptic tokens authentication information. Now add these to cntlm.ini, eg:

Auth            NTLM
PassNT          A2A7104B1CE00000000000000007E1E1
PassLM          C66000000000000000000000008060C8

Finally, set the http_proxy environment variable in Windows (assuming you didn't change with the Listen field which by default is set to 3128) to the following

http://localhost:3128

Appending to an empty DataFrame in Pandas?

That should work:

>>> df = pd.DataFrame()
>>> data = pd.DataFrame({"A": range(3)})
>>> df.append(data)
   A
0  0
1  1
2  2

But the append doesn't happen in-place, so you'll have to store the output if you want it:

>>> df
Empty DataFrame
Columns: []
Index: []
>>> df = df.append(data)
>>> df
   A
0  0
1  1
2  2

Thymeleaf: how to use conditionals to dynamically add/remove a CSS class

Another very similar answer is to use "equals" instead of "contains".

<li th:class="${#strings.equals(pageTitle,'How It Works')} ? active : ''">

How to use a table type in a SELECT FROM statement?

You can't do it in a single query inside the package - you can't mix the SQL and PL/SQL types, and would need to define the types in the SQL layer as Tony, Marcin and Thio have said.

If you really want this done locally, and you can index the table type by VARCHAR instead of BINARY_INTEGER, you can do something like this:

-- dummy ITEM table as we don't know what the real ones looks like
create table item(
    item_num number,
    currency varchar2(9)
)
/   

insert into item values(1,'GBP');
insert into item values(2,'AUD');
insert into item values(3,'GBP');
insert into item values(4,'AUD');
insert into item values(5,'CDN');

create package so_5165580 as
    type exch_row is record(
        exch_rt_eur number,
        exch_rt_usd number);
    type exch_tbl is table of exch_row index by varchar2(9);
    exch_rt exch_tbl;
    procedure show_items;
end so_5165580;
/

create package body so_5165580 as
    procedure populate_rates is
        rate exch_row;
    begin
        rate.exch_rt_eur := 0.614394;
        rate.exch_rt_usd := 0.8494;
        exch_rt('GBP') := rate;
        rate.exch_rt_eur := 0.9817;
        rate.exch_rt_usd := 1.3572;
        exch_rt('AUD') := rate;
    end;

    procedure show_items is
        cursor c0 is
            select i.*
            from item i;
    begin
        for r0 in c0 loop
            if exch_rt.exists(r0.currency) then
                dbms_output.put_line('Item ' || r0.item_num
                    || ' Currency ' || r0.currency
                    || ' EUR ' || exch_rt(r0.currency).exch_rt_eur
                    || ' USD ' || exch_rt(r0.currency).exch_rt_usd);
            else
                dbms_output.put_line('Item ' || r0.item_num
                    || ' Currency ' || r0.currency
                    || ' ** no rates defined **');
            end if;
        end loop;
    end;
begin
    populate_rates;
end so_5165580;
/

So inside your loop, wherever you would have expected to use r0.exch_rt_eur you instead use exch_rt(r0.currency).exch_rt_eur, and the same for USD. Testing from an anonymous block:

begin
    so_5165580.show_items;
end;
/

Item 1 Currency GBP EUR .614394 USD .8494
Item 2 Currency AUD EUR .9817 USD 1.3572
Item 3 Currency GBP EUR .614394 USD .8494
Item 4 Currency AUD EUR .9817 USD 1.3572
Item 5 Currency CDN ** no rates defined **

Based on the answer Stef posted, this doesn't need to be in a package at all; the same results could be achieved with an insert statement. Assuming EXCH holds exchange rates of other currencies against the Euro, including USD with currency_key=1:

insert into detail_items
with rt as (select c.currency_cd as currency_cd,
        e.exch_rt as exch_rt_eur,
        (e.exch_rt / usd.exch_rt) as exch_rt_usd
    from exch e,
        currency c,
        (select exch_rt from exch where currency_key = 1) usd
    where c.currency_key = e.currency_key)
select i.doc,
    i.doc_currency,
    i.net_value,
    i.net_value / rt.exch_rt_usd AS net_value_in_usd,
    i.net_value / rt.exch_rt_eur as net_value_in_euro
from item i
join rt on i.doc_currency = rt.currency_cd;

With items valued at 19.99 GBP and 25.00 AUD, you get detail_items:

DOC DOC_CURRENCY NET_VALUE         NET_VALUE_IN_USD  NET_VALUE_IN_EURO
--- ------------ ----------------- ----------------- -----------------
1   GBP          19.99             32.53611          23.53426
2   AUD          25                25.46041          18.41621

If you want the currency stuff to be more re-usable you could create a view:

create view rt as
select c.currency_cd as currency_cd,
    e.exch_rt as exch_rt_eur,
    (e.exch_rt / usd.exch_rt) as exch_rt_usd
from exch e,
    currency c,
    (select exch_rt from exch where currency_key = 1) usd
where c.currency_key = e.currency_key;

And then insert using values from that:

insert into detail_items
select i.doc,
    i.doc_currency,
    i.net_value,
    i.net_value / rt.exch_rt_usd AS net_value_in_usd,
    i.net_value / rt.exch_rt_eur as net_value_in_euro
from item i
join rt on i.doc_currency = rt.currency_cd;

TypeError: 'float' object is not callable

There is an operator missing, likely a *:

-3.7 need_something_here (prof[x])

The "is not callable" occurs because the parenthesis -- and lack of operator which would have switched the parenthesis into precedence operators -- make Python try to call the result of -3.7 (a float) as a function, which is not allowed.

The parenthesis are also not needed in this case, the following may be sufficient/correct:

-3.7 * prof[x]

As Legolas points out, there are other things which may need to be addressed:

2.25 * (1 - math.pow(math.e, (-3.7(prof[x])/2.25))) * (math.e, (0/2.25)))
                                  ^-- op missing
                                                    extra parenthesis --^
               valid but questionable float*tuple --^
                                     expression yields 0.0 always --^

Reset/remove CSS styles for element only

If you happen to be using sass in a build system, one way to do this that will work in all the major browsers is to wrap all your style imports with a :not() selector like so...

:not(.disable-all-styles) {
  @import 'my-sass-file';
  @import 'my-other-sass-file';
}

Then you can use the disable class on a container and the sub-content won't have any of your styles.

<div class="disable-all-styles">
  <p>Nothing in this div is affected by my sass styles.</p>
</div>

Of course all your styles will now be prepended with the :not() selector, so it's a little fugly, but works well.

Oracle select most recent date record

select *
from (select
  staff_id, site_id, pay_level, date, 
  rank() over (partition by staff_id order by date desc) r
  from owner.table
  where end_enrollment_date is null
)
where r = 1

How to Correctly Use Lists in R?

This is a very old question, but I think that a new answer might add some value since, in my opinion, no one directly addressed some of the concerns in the OP.

Despite what the accepted answer suggests, list objects in R are not hash maps. If you want to make a parallel with python, list are more like, you guess, python lists (or tuples actually).

It's better to describe how most R objects are stored internally (the C type of an R object is SEXP). They are made basically of three parts:

  • an header, which declares the R type of the object, the length and some other meta data;
  • the data part, which is a standard C heap-allocated array (contiguous block of memory);
  • the attributes, which are a named linked list of pointers to other R objects (or NULL if the object doesn't have attributes).

From an internal point of view, there is little difference between a list and a numeric vector for instance. The values they store are just different. Let's break two objects into the paradigm we described before:

x <- runif(10)
y <- list(runif(10), runif(3))

For x:

  • The header will say that the type is numeric (REALSXP in the C-side), the length is 10 and other stuff.
  • The data part will be an array containing 10 double values.
  • The attributes are NULL, since the object doesn't have any.

For y:

  • The header will say that the type is list (VECSXP in the C-side), the length is 2 and other stuff.
  • The data part will be an array containing 2 pointers to two SEXP types, pointing to the value obtained by runif(10) and runif(3) respectively.
  • The attributes are NULL, as for x.

So the only difference between a numeric vector and a list is that the numeric data part is made of double values, while for the list the data part is an array of pointers to other R objects.

What happens with names? Well, names are just some of the attributes you can assign to an object. Let's see the object below:

z <- list(a=1:3, b=LETTERS)
  • The header will say that the type is list (VECSXP in the C-side), the length is 2 and other stuff.
  • The data part will be an array containing 2 pointers to two SEXP types, pointing to the value obtained by 1:3 and LETTERS respectively.
  • The attributes are now present and are a names component which is a character R object with value c("a","b").

From the R level, you can retrieve the attributes of an object with the attributes function.

The key-value typical of an hash map in R is just an illusion. When you say:

z[["a"]]

this is what happens:

  • the [[ subset function is called;
  • the argument of the function ("a") is of type character, so the method is instructed to search such value from the names attribute (if present) of the object z;
  • if the names attribute isn't there, NULL is returned;
  • if present, the "a" value is searched in it. If "a" is not a name of the object, NULL is returned;
  • if present, the position of the first occurence is determined (1 in the example). So the first element of the list is returned, i.e. the equivalent of z[[1]].

The key-value search is rather indirect and is always positional. Also, useful to keep in mind:

  • in hash maps the only limit a key must have is that it must be hashable. names in R must be strings (character vectors);

  • in hash maps you cannot have two identical keys. In R, you can assign names to an object with repeated values. For instance:

      names(y) <- c("same", "same")
    

is perfectly valid in R. When you try y[["same"]] the first value is retrieved. You should know why at this point.

In conclusion, the ability to give arbitrary attributes to an object gives you the appearance of something different from an external point of view. But R lists are not hash maps in any way.

How to access model hasMany Relation with where condition?

If you want to apply condition on the relational table you may use other solutions as well.. This solution is working from my end.

public static function getAllAvailableVideos() {
        $result = self::with(['videos' => function($q) {
                        $q->select('id', 'name');
                        $q->where('available', '=', 1);
                    }])                    
                ->get();
        return $result;
    }

Regex to Match Symbols: !$%^&*()_+|~-=`{}[]:";'<>?,./

// The string must contain at least one special character, escaping reserved RegEx characters to avoid conflict
  const hasSpecial = password => {
    const specialReg = new RegExp(
      '^(?=.*[!@#$%^&*"\\[\\]\\{\\}<>/\\(\\)=\\\\\\-_´+`~\\:;,\\.€\\|])',
    );
    return specialReg.test(password);
  };

Checking password match while typing

The problem in this case is that onchange-event does not fire until the input looses focus, so you will probably want to listen for the keyup-event instead, which is fired on every keystroke.

Also, I would prefer not using inline-javascript, but rather catch the event using jQuery instead.

$("#txtConfirmPassword").keyup(checkPasswordMatch);

Simple Android RecyclerView example

To get started , just to view something in Recycler view

recycler view adapter can be something like this.

class CustomAdapter: RecyclerView.Adapter<CustomAdapter.ViewHolder>() {
    var data =  listOf<String>()
        set(value) {
            field = value
            notifyDataSetChanged()
        }
    override fun getItemCount() =data.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.txt.text= data[position]
    }
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(
            LayoutInflater.from(parent.context).inflate(R.layout.item_view, parent, false)
        )
    }


    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){
        val txt: TextView = itemView.findViewById(R.id.item_text_view)
    }
}

and to attach the adapter to the recycler view and to attach data to adapter

val view = findViewById<RecyclerView>(R.id.recycler_view)                                              
val adapter = CustomAdapter()                                                                          
val data = listOf("text1", "text2", "text3")
adapter.data = data                                                                             
view.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
view.adapter = adapter       
            

How to insert default values in SQL table?

Best practice it to list your columns so you're independent of table changes (new column or column order etc)

insert into table1 (field1, field3)  values (5,10)

However, if you don't want to do this, use the DEFAULT keyword

insert into table1 values (5, DEFAULT, 10, DEFAULT)

Calculating sum of repeated elements in AngularJS ng-repeat

You can use a custom Angular filter that takes the dataset object array and the key in each object to sum. The filter can then return the sum:

.filter('sumColumn', function(){
        return function(dataSet, columnToSum){
            let sum = 0;

            for(let i = 0; i < dataSet.length; i++){
                sum += parseFloat(dataSet[i][columnToSum]) || 0;
            }

            return sum;
        };
    })

Then in your table to sum a column you can use:

<th>{{ dataSet | sumColumn: 'keyInObjectToSum' }}</th>

"replace" function examples

Here's two simple examples

> x <- letters[1:4]
> replace(x, 3, 'Z') #replacing 'c' by 'Z'
[1] "a" "b" "Z" "d"
> 
> y <- 1:10
> replace(y, c(4,5), c(20,30)) # replacing 4th and 5th elements by 20 and 30
 [1]  1  2  3 20 30  6  7  8  9 10

how to compare the Java Byte[] array?

If you're trying to use the array as a generic HashMap key, that's not going to work. Consider creating a custom wrapper object that holds the array, and whose equals(...) and hashcode(...) method returns the results from the java.util.Arrays methods. For example...

import java.util.Arrays;

public class MyByteArray {
   private byte[] data;

   // ... constructors, getters methods, setter methods, etc...


   @Override
   public int hashCode() {
      return Arrays.hashCode(data);
   }

   @Override
   public boolean equals(Object obj) {
      if (this == obj)
         return true;
      if (obj == null)
         return false;
      if (getClass() != obj.getClass())
         return false;
      MyByteArray other = (MyByteArray) obj;
      if (!Arrays.equals(data, other.data))
         return false;
      return true;
   }


}

Objects of this wrapper class will work fine as a key for your HashMap<MyByteArray, OtherType> and will allow for clean use of equals(...) and hashCode(...) methods.

Cannot run emulator in Android Studio

I had the same error. The solution for me was change the ANDROID_HOME path. First I took a look into tools->android->sdk manager from Android Studio. In that window, we can see the path where Android Studio looks for the SDK: image

Then I opened a Windows CMD shell, executed:

echo %ANDROID_HOME%

but the path was different to the one in ANDROID STUDIO CONFIGURATION of the first step.

The solution was to change in user environment, the ANDROID_HOME, to the one of the first step: image

I finally closed the cmd shell, and opened another cmd shell to execute:

echo %ANDROID_HOME%

the path was updated, and I could run my emulator perfectly.

How to make code wait while calling asynchronous calls like Ajax

Use callbacks. Something like this should work based on your sample code.

function someFunc() {

callAjaxfunc(function() {
    console.log('Pass2');
});

}

function callAjaxfunc(callback) {
    //All ajax calls called here
    onAjaxSuccess: function() {
        callback();
    };
    console.log('Pass1');    
}

This will print Pass1 immediately (assuming ajax request takes atleast a few microseconds), then print Pass2 when the onAjaxSuccess is executed.

How can I query for null values in entity framework?

There is a slightly simpler workaround that works with LINQ to Entities:

var result = from entry in table
         where entry.something == value || (value == null && entry.something == null)
         select entry;

This works becasuse, as AZ noticed, LINQ to Entities special cases x == null (i.e. an equality comparison against the null constant) and translates it to x IS NULL.

We are currently considering changing this behavior to introduce the compensating comparisons automatically if both sides of the equality are nullable. There are a couple of challenges though:

  1. This could potentially break code that already depends on the existing behavior.
  2. The new translation could affect the performance of existing queries even when a null parameter is seldom used.

In any case, whether we get to work on this is going to depend greatly on the relative priority our customers assign to it. If you care about the issue, I encourage you to vote for it in our new Feature Suggestion site: https://data.uservoice.com.

Pandas concat: ValueError: Shape of passed values is blah, indices imply blah2

My problem were different indices, the following code solved my problem.

df1.reset_index(drop=True, inplace=True)
df2.reset_index(drop=True, inplace=True)
df = pd.concat([df1, df2], axis=1)

Converting Python dict to kwargs?

Here is a complete example showing how to use the ** operator to pass values from a dictionary as keyword arguments.

>>> def f(x=2):
...     print(x)
... 
>>> new_x = {'x': 4}
>>> f()        #    default value x=2
2
>>> f(x=3)     #   explicit value x=3
3
>>> f(**new_x) # dictionary value x=4 
4

Add a Progress Bar in WebView

You can try this code into your activity

    private void startWebView(WebView webView,String url) {
 webView.setWebViewClient(new WebViewClient() {
            ProgressDialog progressDialog;

            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return false;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            public void onLoadResource (WebView view, String url) {

                    if (progressDialog == null) {
                        progressDialog = new ProgressDialog(SponceredDetailsActivity.this);
                        progressDialog.setMessage("Loading...");
                        progressDialog.show();
                    }

            }
            public void onPageFinished(WebView view, String url) {
                try{
                    if (progressDialog.isShowing()) {
                        progressDialog.dismiss();
                        progressDialog = null;
                    }

                }catch(Exception exception){
                    exception.printStackTrace();
                }
            }

        });

        webView.getSettings().setJavaScriptEnabled(true);
        webView.loadUrl(url);
    }

Call this method using this way:

startWebView(web_view,"Your Url");

Sometimes if URL is dead it will redirected and it will come to onLoadResource() before onPageFinished method. For this reason progress bar will not dismis. To solve this issue see my this Answer.

Thanks :)

How can I get the order ID in WooCommerce?

As of woocommerce 3.0

$order->id;

will not work, it will generate notice, use getter function:

$order->get_id();

The same applies for other woocommerce objects like procut.

DateTime.Now.ToShortDateString(); replace month and day

Use DateTime.ToString with the specified format MM.dd.yyyy:

this.TextBox3.Text = DateTime.Now.ToString("MM.dd.yyyy");

Here, MM means the month from 01 to 12, dd means the day from 01 to 31 and yyyy means the year as a four-digit number.

Is there a way to break a list into columns?

Here is what I did

_x000D_
_x000D_
ul {_x000D_
      display: block;_x000D_
      width: 100%;_x000D_
}_x000D_
_x000D_
ul li{_x000D_
    display: block;_x000D_
    min-width: calc(30% - 10px);_x000D_
    float: left;_x000D_
}_x000D_
_x000D_
ul li:nth-child(2n + 1){_x000D_
    clear: left;_x000D_
}
_x000D_
<ul>_x000D_
  <li>1</li>_x000D_
  <li>2</li>_x000D_
  <li>3</li>_x000D_
  <li>4</li>_x000D_
  <li>5</li>_x000D_
  <li>6</li>_x000D_
  <li>7</li>_x000D_
  <li>8</li>_x000D_
  <li>9</li>_x000D_
  <li>0</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

python pandas: Remove duplicates by columns A, keeping the row with the highest value in column B

I am not going to give you the whole answer (I don't think you're looking for the parsing and writing to file part anyway), but a pivotal hint should suffice: use python's set() function, and then sorted() or .sort() coupled with .reverse():

>>> a=sorted(set([10,60,30,10,50,20,60,50,60,10,30]))
>>> a
[10, 20, 30, 50, 60]
>>> a.reverse()
>>> a
[60, 50, 30, 20, 10]

Swift performSelector:withObject:afterDelay: is unavailable

Swift is statically typed so the performSelector: methods are to fall by the wayside.

Instead, use GCD to dispatch a suitable block to the relevant queue — in this case it'll presumably be the main queue since it looks like you're doing UIKit work.

EDIT: the relevant performSelector: is also notably missing from the Swift version of the NSRunLoop documentation ("1 Objective-C symbol hidden") so you can't jump straight in with that. With that and its absence from the Swiftified NSObject I'd argue it's pretty clear what Apple is thinking here.

Tesseract OCR simple example

A simple example of testing Tesseract OCR in C#:

    public static string GetText(Bitmap imgsource)
    {
        var ocrtext = string.Empty;
        using (var engine = new TesseractEngine(@"./tessdata", "eng", EngineMode.Default))
        {
            using (var img = PixConverter.ToPix(imgsource))
            {
                using (var page = engine.Process(img))
                {
                    ocrtext = page.GetText();
                }
            }
        }

        return ocrtext;
    }

Info: The tessdata folder must exist in the repository: bin\Debug\

Set value for particular cell in pandas DataFrame using index

I too was searching for this topic and I put together a way to iterate through a DataFrame and update it with lookup values from a second DataFrame. Here is my code.

src_df = pd.read_sql_query(src_sql,src_connection)
for index1, row1 in src_df.iterrows():
    for index, row in vertical_df.iterrows():
        src_df.set_value(index=index1,col=u'etl_load_key',value=etl_load_key)
        if (row1[u'src_id'] == row['SRC_ID']) is True:
            src_df.set_value(index=index1,col=u'vertical',value=row['VERTICAL'])

JQuery Validate input file type

So, I had the same issue and sadly just adding to the rules didn't work. I found out that accept: and extension: are not part of JQuery validate.js by default and it requires an additional-Methods.js plugin to make it work.

So for anyone else who followed this thread and it still didn't work, you can try adding additional-Methods.js to your tag in addition to the answer above and it should work.

Check if value exists in enum in TypeScript

For anyone who comes here looking to validate if a string is one of the values of an enum and type convert it, I wrote this function that returns the proper type and returns undefined if the string is not in the enum.

function keepIfInEnum<T>(
  value: string,
  enumObject: { [key: string]: T }
) {
  if (Object.values(enumObject).includes((value as unknown) as T)) {
    return (value as unknown) as T;
  } else {
    return undefined;
  }
}

As an example:

enum StringEnum {
  value1 = 'FirstValue',
  value2 = 'SecondValue',
}
keepIfInEnum<StringEnum>('FirstValue', StringEnum)  // 'FirstValue'
keepIfInEnum<StringEnum>('OtherValue', StringEnum)  // undefined

SQL Error: ORA-01861: literal does not match format string 01861

ORA-01861: literal does not match format string

This happens because you have tried to enter a literal with a format string, but the length of the format string was not the same length as the literal.

You can overcome this issue by carrying out following alteration.

TO_DATE('1989-12-09','YYYY-MM-DD')

As a general rule, if you are using the TO_DATE function, TO_TIMESTAMP function, TO_CHAR function, and similar functions, make sure that the literal that you provide matches the format string that you've specified

bootstrap button shows blue outline when clicked

Override the exact bootstrap statements:

.btn-primary.focus, .btn-primary:focus, .btn-primary:not(:disabled):not(.disabled).active:focus,.btn-primary:not(:disabled):not(.disabled):active:focus,.show>.btn-primary.dropdown-toggle:focus{
 box-shadow: none;
}

What is external linkage and internal linkage?

Linkage determines whether identifiers that have identical names refer to the same object, function, or other entity, even if those identifiers appear in different translation units. The linkage of an identifier depends on how it was declared. There are three types of linkages:

  1. Internal linkage : identifiers can only be seen within a translation unit.
  2. External linkage : identifiers can be seen (and referred to) in other translation units.
  3. No linkage : identifiers can only be seen in the scope in which they are defined. Linkage does not affect scoping

C++ only : You can also have linkage between C++ and non-C++ code fragments, which is called language linkage.

Source :IBM Program Linkage

Why can't Visual Studio find my DLL?

try "configuration properties -> debugging -> environment" and set the PATH variable in run-time

Why an inline "background-image" style doesn't work in Chrome 10 and Internet Explorer 8?

it is working in my google chrome browser version 11.0.696.60

I created a simple page with no other items just basic tags and no separate CSS file and got an image

this is what i setup:

<div id="placeholder" style="width: 60px; height: 60px; border: 1px solid black; background-image: url('http://www.mypicx.com/uploadimg/1312875436_05012011_2.png')"></div>

I put an id just in case there was a hidden id tag and it works

HTML: How to limit file upload to be only images?

Edited

If things were as they SHOULD be, you could do this via the "Accept" attribute.

http://www.webmasterworld.com/forum21/6310.htm

However, browsers pretty much ignore this, so this is irrelavant. The short answer is, i don't think there is a way to do it in HTML. You'd have to check it server-side instead.

The following older post has some information that could help you with alternatives.

File input 'accept' attribute - is it useful?

How do you determine a processing time in Python?

I also got a requirement to calculate the process time of some code lines. So I tried the approved answer and I got this warning.

DeprecationWarning: time.clock has been deprecated in Python 3.3 and will be removed from Python 3.8: use time.perf_counter or time.process_time instead

So python will remove time.clock() from Python 3.8. You can see more about it from issue #13270. This warning suggest two function instead of time.clock(). In the documentation also mention about this warning in-detail in time.clock() section.

Deprecated since version 3.3, will be removed in version 3.8: The behaviour of this function depends on the platform: use perf_counter() or process_time() instead, depending on your requirements, to have a well defined behaviour.

Let's look at in-detail both functions.


Return the value (in fractional seconds) of a performance counter, i.e. a clock with the highest available resolution to measure a short duration. It does include time elapsed during sleep and is system-wide. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid.

New in version 3.3.

So if you want it as nanoseconds, you can use time.perf_counter_ns() and if your code consist with time.sleep(secs), it will also count. Ex:-

import time


def func(x):
    time.sleep(5)
    return x * x


lst = [1, 2, 3]
tic = time.perf_counter()
print([func(x) for x in lst])
toc = time.perf_counter()
print(toc - tic)

# [1, 4, 9]
# 15.0041916 --> output including 5 seconds sleep time

Return the value (in fractional seconds) of the sum of the system and user CPU time of the current process. It does not include time elapsed during sleep. It is process-wide by definition. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid.

New in version 3.3.

So if you want it as nanoseconds, you can use time.process_time_ns() and if your code consist with time.sleep(secs), it won't count. Ex:-

import time


def func(x):
    time.sleep(5)
    return x * x


lst = [1, 2, 3]
tic = time.process_time()
print([func(x) for x in lst])
toc = time.process_time()
print(toc - tic)

# [1, 4, 9]
# 0.0 --> output excluding 5 seconds sleep time

Please note both time.perf_counter_ns() and time.process_time_ns() come up with Python 3.7 onward.

Removing address bar from browser (to view on Android)

If you've loaded jQuery, you can see if the height of the content is greater than the viewport height. If not, then you can make it that height (or a little less). I ran the following code in WVGA800 mode in the Android emulator, and then ran it on my Samsung Galaxy Tab, and in both cases it hid the addressbar.

$(document).ready(function() {

  if (navigator.userAgent.match(/Android/i)) {
    window.scrollTo(0,0); // reset in case prev not scrolled  
    var nPageH = $(document).height();
    var nViewH = window.outerHeight;
    if (nViewH > nPageH) {
      nViewH -= 250;
      $('BODY').css('height',nViewH + 'px');
    }
    window.scrollTo(0,1);
  }

});

Failed to add a service. Service metadata may not be accessible. Make sure your service is running and exposing metadata.`

changing the Binding Type from wsHttpbinding to basichttp binding in the endpoint tag and from wsHttpbinding to mexhttpbinginding in metadata endpoint tag helped to overcome the error. Thank you...

tSQL - Conversion from varchar to numeric works for all but integer

Try this query:

SELECT cast(column_name as type) as col_identifier FROM tableName WHERE 1=1

Before comparing, the cast function will convert varchar type value to integer type.

c# razor url parameter from view

If you're doing the check inside the View, put the value in the ViewBag.

In your controller:

ViewBag["parameterName"] = Request["parameterName"];

It's worth noting that the Request and Response properties are exposed by the Controller class. They have the same semantics as HttpRequest and HttpResponse.

How to scroll up or down the page to an anchor using jQuery?

My approach with jQuery to just make all of the embedded anchor links slide instead of jump instantly

It's really similar to the answer by Santi Nunez but it's more reliable.

Support

  • Multi-framework environment.
  • Before the page has finished loading.
<a href="#myid">Go to</a>
<div id="myid"></div>
// Slow scroll with anchors
(function($){
    $(document).on('click', 'a[href^=#]', function(e){
        e.preventDefault();
        var id = $(this).attr('href');
        $('html,body').animate({scrollTop: $(id).offset().top}, 500);
    });
})(jQuery);

Error inflating class fragment

Here is my solution to this problem.

Caused by: android.view.InflateException: Binary XML file line #31: Error inflating class fragment
Caused by: java.lang.IllegalArgumentException: Binary XML file line #31: Duplicate id 0x7f09006d, tag null, or parent id 0xffffffff with another fragment for com.example.eduardf.audit.DateTime

In my case, the error occurred when re-opening the DialogFragment with a Fragment.

<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:drawableStart="@drawable/ic_black_edit_24px"
            android:singleLine="true" />
        <fragment
            android:id="@+id/fragment_date"
            android:name="com.example.eduardf.audit.DateTime"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            tools:layout="@layout/fragment_date_time" />
    </LinearLayout>
</android.support.constraint.ConstraintLayout>

DailogFragment stores the fragment after the first inflate. To prevent this from happening, I forcibly deleted the fragment.

@Override
public void onDestroyView () {
    if (!(afterRotate || getActivity() == null)) {
        final FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
        final Fragment fragment = fragmentManager.findFragmentById(R.id.fragment_date);
        if (fragment != null)
            fragmentManager.beginTransaction().remove(fragment).commit();
    }
    super.onDestroyView();
}

Also had to take care of unnecessary removal of the fragment, for example, when you rotate the screen.

private boolean afterRotate = false;
...
@Override
public void onSaveInstanceState (Bundle outState) {
    super.onSaveInstanceState(outState);
    afterRotate = true;
}

Xcode Objective-C | iOS: delay function / NSTimer help?

Try

NSDate *future = [NSDate dateWithTimeIntervalSinceNow: 0.06 ];
[NSThread sleepUntilDate:future];

Update multiple tables in SQL Server using INNER JOIN

You can't update more that one table in a single statement, however the error message you get is because of the aliases, you could try this :

BEGIN TRANSACTION

update A
set A.ORG_NAME =  @ORG_NAME
from table1 A inner join table2 B
on B.ORG_ID = A.ORG_ID
and A.ORG_ID = @ORG_ID

update B
set B.REF_NAME = @REF_NAME
from table2 B inner join table1 A
    on B.ORG_ID = A.ORG_ID
    and A.ORG_ID = @ORG_ID

COMMIT

What is the Oracle equivalent of SQL Server's IsNull() function?

Also use NVL2 as below if you want to return other value from the field_to_check:

NVL2( field_to_check, value_if_NOT_null, value_if_null )

Usage: ORACLE/PLSQL: NVL2 FUNCTION

dismissModalViewControllerAnimated deprecated

The warning is still there. In order to get rid of it I put it into a selector like this:

if ([self respondsToSelector:@selector(dismissModalViewControllerAnimated:)]) {
    [self performSelector:@selector(dismissModalViewControllerAnimated:) withObject:[NSNumber numberWithBool:YES]];
} else {
    [self dismissViewControllerAnimated:YES completion:nil];
}

It benefits people with OCD like myself ;)

How do I print the content of a .txt file in Python?

This will give you the contents of a file separated, line-by-line in a list:

with open('xyz.txt') as f_obj:
    f_obj.readlines()

TypeError: only integer scalar arrays can be converted to a scalar index with 1D numpy indices array

Another case that could cause this error is

>>> np.ndindex(np.random.rand(60,60))
TypeError: only integer scalar arrays can be converted to a scalar index

Using the actual shape will fix it.

>>> np.ndindex(np.random.rand(60,60).shape)
<numpy.ndindex object at 0x000001B887A98880>

How do I set the default font size in Vim?

Try a \<Space> before 12, like so:

:set guifont=Monospace\ 12

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

Finally, with Java 9+ it is possible with ProcessHandle:

public static void main(String[] args) {
    ProcessHandle.allProcesses()
            .forEach(process -> System.out.println(processDetails(process)));
}

private static String processDetails(ProcessHandle process) {
    return String.format("%8d %8s %10s %26s %-40s",
            process.pid(),
            text(process.parent().map(ProcessHandle::pid)),
            text(process.info().user()),
            text(process.info().startInstant()),
            text(process.info().commandLine()));
}

private static String text(Optional<?> optional) {
    return optional.map(Object::toString).orElse("-");
}

Output:

    1        -       root   2017-11-19T18:01:13.100Z /sbin/init
  ...
  639     1325   www-data   2018-12-04T06:35:58.680Z /usr/sbin/apache2 -k start
  ...
23082    11054    huguesm   2018-12-04T10:24:22.100Z /.../java ProcessListDemo

assign multiple variables to the same value in Javascript

Nothing stops you from doing the above, but hold up!

There are some gotchas. Assignment in Javascript is from right to left so when you write:

var moveUp = moveDown = moveLeft = moveRight = mouseDown = touchDown = false;

it effectively translates to:

var moveUp = (moveDown = (moveLeft = (moveRight = (mouseDown = (touchDown = false)))));

which effectively translates to:

var moveUp = (window.moveDown = (window.moveLeft = (window.moveRight = (window.mouseDown = (window.touchDown = false)))));

Inadvertently, you just created 5 global variables--something I'm pretty sure you didn't want to do.

Note: My above example assumes you are running your code in the browser, hence window. If you were to be in a different environment these variables would attach to whatever the global context happens to be for that environment (i.e., in Node.js, it would attach to global which is the global context for that environment).

Now you could first declare all your variables and then assign them to the same value and you could avoid the problem.

var moveUp, moveDown, moveLeft, moveRight, mouseDown, touchDown;
moveUp = moveDown = moveLeft = moveRight = mouseDown = touchDown = false;

Long story short, both ways would work just fine, but the first way could potentially introduce some pernicious bugs in your code. Don't commit the sin of littering the global namespace with local variables if not absolutely necessary.


Sidenote: As pointed out in the comments (and this is not just in the case of this question), if the copied value in question was not a primitive value but instead an object, you better know about copy by value vs copy by reference. Whenever assigning objects, the reference to the object is copied instead of the actual object. All variables will still point to the same object so any change in one variable will be reflected in the other variables and will cause you a major headache if your intention was to copy the object values and not the reference.

How to get Rails.logger printing to the console/stdout when running rspec?

A solution that I like, because it keeps rspec output separate from actual rails log output, is to do the following:

  • Open a second terminal window or tab, and arrange it so that you can see both the main terminal you're running rspec on as well as the new one.
  • Run a tail command in the second window so you see the rails log in the test environment. By default this can be like $ tail -f $RAILS_APP_DIR/logs/test.log or tail -f $RAILS_APP_DIR\logs\test.log for Window users
  • Run your rspec suites

If you are running a multi-pane terminal like iTerm, this becomes even more fun and you have rspec and the test.log output side by side.

Time complexity of Euclid's Algorithm

Gabriel Lame's Theorem bounds the number of steps by log(1/sqrt(5)*(a+1/2))-2, where the base of the log is (1+sqrt(5))/2. This is for the the worst case scenerio for the algorithm and it occurs when the inputs are consecutive Fibanocci numbers.

A slightly more liberal bound is: log a, where the base of the log is (sqrt(2)) is implied by Koblitz.

For cryptographic purposes we usually consider the bitwise complexity of the algorithms, taking into account that the bit size is given approximately by k=loga.

Here is a detailed analysis of the bitwise complexity of Euclid Algorith:

Although in most references the bitwise complexity of Euclid Algorithm is given by O(loga)^3 there exists a tighter bound which is O(loga)^2.

Consider; r0=a, r1=b, r0=q1.r1+r2 . . . ,ri-1=qi.ri+ri+1, . . . ,rm-2=qm-1.rm-1+rm rm-1=qm.rm

observe that: a=r0>=b=r1>r2>r3...>rm-1>rm>0 ..........(1)

and rm is the greatest common divisor of a and b.

By a Claim in Koblitz's book( A course in number Theory and Cryptography) is can be proven that: ri+1<(ri-1)/2 .................(2)

Again in Koblitz the number of bit operations required to divide a k-bit positive integer by an l-bit positive integer (assuming k>=l) is given as: (k-l+1).l ...................(3)

By (1) and (2) the number of divisons is O(loga) and so by (3) the total complexity is O(loga)^3.

Now this may be reduced to O(loga)^2 by a remark in Koblitz.

consider ki= logri +1

by (1) and (2) we have: ki+1<=ki for i=0,1,...,m-2,m-1 and ki+2<=(ki)-1 for i=0,1,...,m-2

and by (3) the total cost of the m divisons is bounded by: SUM [(ki-1)-((ki)-1))]*ki for i=0,1,2,..,m

rearranging this: SUM [(ki-1)-((ki)-1))]*ki<=4*k0^2

So the bitwise complexity of Euclid's Algorithm is O(loga)^2.

Fastest way to add an Item to an Array

It depends on how often you insert or read. You can increase the array by more than one if needed.

numberOfItems = ??

' ...

If numberOfItems+1 >= arr.Length Then
    Array.Resize(arr, arr.Length + 10)
End If

arr(numberOfItems) = newItem
numberOfItems += 1

Also for A, you only need to get the array if needed.

Dim list As List(Of Integer)(arr) ' Do this only once, keep a reference to the list
                                  ' If you create a new List everything you add an item then this will never be fast

'...

list.Add(newItem)
arrayWasModified = True

' ...

Function GetArray()

    If arrayWasModified Then
        arr = list.ToArray()
    End If

    Return Arr
End Function

If you have the time, I suggest you convert it all to List and remove arrays.

* My code might not compile

Notice: Trying to get property of non-object error

The response is an array.

var_dump($pjs[0]->{'player_name'});

OkHttp Post Body as JSON

You can create your own JSONObject then toString().

Remember run it in the background thread like doInBackground in AsyncTask.

OkHttp version > 4:

// create your json here
JSONObject jsonObject = new JSONObject();
try {
    jsonObject.put("KEY1", "VALUE1");
    jsonObject.put("KEY2", "VALUE2");
} catch (JSONException e) {
    e.printStackTrace();
}

val client = OkHttpClient()
val mediaType = "application/json; charset=utf-8".toMediaType()
val body = jsonObject.toString().toRequestBody(mediaType)
val request: Request = Request.Builder()
            .url("https://YOUR_URL/")
            .post(body)
            .build()

var response: Response? = null
try {
    response = client.newCall(request).execute()
    val resStr = response.body!!.string()
} catch (e: IOException) {
    e.printStackTrace()
}
   

OkHttp version 3:

// create your json here
JSONObject jsonObject = new JSONObject();
try {
    jsonObject.put("KEY1", "VALUE1");
    jsonObject.put("KEY2", "VALUE2");
} catch (JSONException e) {
    e.printStackTrace();
}

  OkHttpClient client = new OkHttpClient();
  MediaType JSON = MediaType.parse("application/json; charset=utf-8");
  // put your json here
  RequestBody body = RequestBody.create(JSON, jsonObject.toString());
  Request request = new Request.Builder()
                    .url("https://YOUR_URL/")
                    .post(body)
                    .build();

  Response response = null;
  try {
      response = client.newCall(request).execute();
      String resStr = response.body().string();
  } catch (IOException e) {
      e.printStackTrace();
  }

Sort an Array by keys based on another Array?

IF you have array in your array, you'll have to adapt the function by Eran a little bit...

function sortArrayByArray($array,$orderArray) {
    $ordered = array();
    foreach($orderArray as $key => $value) {
        if(array_key_exists($key,$array)) {
                $ordered[$key] = $array[$key];
                unset($array[$key]);
        }
    }
    return $ordered + $array;
}

How to escape comma and double quote at same time for CSV file?

If you're using CSVWriter. Check that you don't have the option

.withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)

When I removed it the comma was showing as expected and not treating it as new column

Get the filename of a fileupload in a document through JavaScript

Using code like this in a form I can capture the original source upload filename, copy it to a second simple input field. This is so user can provide an alternate upload filename in submit request since the file upload filename is immutable.

    <input type="file" id="imgup1" name="imagefile">
      onchange="document.getElementsByName('imgfn1')[0].value = document.getElementById('imgup1').value;">
    <input type="text" name="imgfn1" value="">

How can I view an old version of a file with Git?

You can use git show with a path from the root of the repository (./ or ../ for relative pathing):

$ git show REVISION:path/to/file

Replace REVISION with your actual revision (could be a Git commit SHA, a tag name, a branch name, a relative commit name, or any other way of identifying a commit in Git)

For example, to view the version of file <repository-root>/src/main.c from 4 commits ago, use:

$ git show HEAD~4:src/main.c

Git for Windows requires forward slashes even in paths relative to the current directory. For more information, check out the man page for git-show.

How to display image with JavaScript?

You could make use of the Javascript DOM API. In particular, look at the createElement() method.

You could create a re-usable function that will create an image like so...

function show_image(src, width, height, alt) {
    var img = document.createElement("img");
    img.src = src;
    img.width = width;
    img.height = height;
    img.alt = alt;

    // This next line will just add it to the <body> tag
    document.body.appendChild(img);
}

Then you could use it like this...

<button onclick=
    "show_image('http://google.com/images/logo.gif', 
                 276, 
                 110, 
                 'Google Logo');">Add Google Logo</button> 

See a working example on jsFiddle: http://jsfiddle.net/Bc6Et/

How to check if a process is running via a batch script

Here's how I've worked it out:

tasklist /FI "IMAGENAME eq notepad.exe" /FO CSV > search.log

FOR /F %%A IN (search.log) DO IF %%~zA EQU 0 GOTO end

start notepad.exe

:end

del search.log

The above will open Notepad if it is not already running.

Edit: Note that this won't find applications hidden from the tasklist. This will include any scheduled tasks running as a different user, as these are automatically hidden.

See whether an item appears more than once in a database column

It should be:

SELECT SalesID, COUNT(*)
FROM AXDelNotesNoTracking
GROUP BY SalesID
HAVING COUNT(*) > 1

Regarding your initial query:

  1. You cannot do a SELECT * since this operation requires a GROUP BY and columns need to either be in the GROUP BY or in an aggregate function (i.e. COUNT, SUM, MIN, MAX, AVG, etc.)
  2. As this is a GROUP BY operation, a HAVING clause will filter it instead of a WHERE

Edit:

And I just thought of this, if you want to see WHICH items are in there more than once (but this depends on which database you are using):

;WITH cte AS (
    SELECT  *, ROW_NUMBER() OVER (PARTITION BY SalesID ORDER BY SalesID) AS [Num]
    FROM    AXDelNotesNoTracking
)
SELECT  *
FROM    cte
WHERE   cte.Num > 1

Of course, this just shows the rows that have appeared with the same SalesID but does not show the initial SalesID value that has appeared more than once. Meaning, if a SalesID shows up 3 times, this query will show instances 2 and 3 but not the first instance. Still, it might help depending on why you are looking for multiple SalesID values.

Edit2:

The following query was posted by APC below and is better than the CTE I mention above in that it shows all rows in which a SalesID has appeared more than once. I am including it here for completeness. I merely added an ORDER BY to keep the SalesID values grouped together. The ORDER BY might also help in the CTE above.

SELECT *
FROM AXDelNotesNoTracking
WHERE SalesID IN
    (     SELECT SalesID
          FROM AXDelNotesNoTracking
          GROUP BY SalesID
          HAVING COUNT(*) > 1
    )
ORDER BY SalesID

How can I pass an argument to a PowerShell script?

Create a PowerShell script with the following code in the file.

param([string]$path)
Get-ChildItem $path | Where-Object {$_.LinkType -eq 'SymbolicLink'} | select name, target

This creates a script with a path parameter. It will list all symbolic links within the path provided as well as the specified target of the symbolic link.

How to import NumPy in the Python shell

The message is fairly self-explanatory; your working directory should not be the NumPy source directory when you invoke Python; NumPy should be installed and your working directory should be anything but the directory where it lives.

dyld: Library not loaded: /usr/local/lib/libpng16.16.dylib with anything php related

I know this question has already an answer that gives a solution. But I want to give you my two cents to help people to understand the problem. Getting same issue I've created a specific question. I got same problem, but only with PHPStorm. And exactly when I try to run test from the editor.

dyld is the dynamic linker

I sow that dyld was looking for /usr/local/lib/libpng15.15.dylib but inside my /usr/local/lib/ there was not. In that folder, I got libpng16.16.dylib.

Thanks to a comment, I undestand that my /usr/bin/php was a pointer to php 5.5.8. Instead, ... /usr/local/bin/php was 5.5.14. PHPStorm worked with /usr/bin/php that is default configuration. When I run php via console, I run /urs/local/bin/php.

So, ... If you get some dyld error, maybe you have some wrong php configuration. That's the reason because

$ brew update && brew upgrade
$ brew reinstall php55

But I dont know why this do not solve the problem to me. Maybe because I have

Adding Jar files to IntellijIdea classpath

If, as I just encountered, you happen to have a jar file listed in the Project Structures->Libraries that is not in your classpath, the correct answer can be found by following the link given by @CrazyCoder above: Look here http://www.jetbrains.com/idea/webhelp/configuring-module-dependencies-and-libraries.html

This says that to add the jar file as a module dependency within the Project Structure dialog:

  1. Open Project Structure
  2. Select Modules, then click on the module for which you want the dependency
  3. Choose the Dependencies tab
  4. Click the '+' at the bottom of the page and choose the appropriate way to connect to the library file. If the jar file is already listed in Libraries, then select 'Library'.

Get the IP Address of local computer

The problem with all the approaches based on gethostbyname is that you will not get all IP addresses assigned to a particular machine. Servers usually have more than one adapter.

Here is an example of how you can iterate through all Ipv4 and Ipv6 addresses on the host machine:

void ListIpAddresses(IpAddresses& ipAddrs)
{
  IP_ADAPTER_ADDRESSES* adapter_addresses(NULL);
  IP_ADAPTER_ADDRESSES* adapter(NULL);

  // Start with a 16 KB buffer and resize if needed -
  // multiple attempts in case interfaces change while
  // we are in the middle of querying them.
  DWORD adapter_addresses_buffer_size = 16 * KB;
  for (int attempts = 0; attempts != 3; ++attempts)
  {
    adapter_addresses = (IP_ADAPTER_ADDRESSES*)malloc(adapter_addresses_buffer_size);
    assert(adapter_addresses);

    DWORD error = ::GetAdaptersAddresses(
      AF_UNSPEC, 
      GAA_FLAG_SKIP_ANYCAST | 
        GAA_FLAG_SKIP_MULTICAST | 
        GAA_FLAG_SKIP_DNS_SERVER |
        GAA_FLAG_SKIP_FRIENDLY_NAME, 
      NULL, 
      adapter_addresses,
      &adapter_addresses_buffer_size);

    if (ERROR_SUCCESS == error)
    {
      // We're done here, people!
      break;
    }
    else if (ERROR_BUFFER_OVERFLOW == error)
    {
      // Try again with the new size
      free(adapter_addresses);
      adapter_addresses = NULL;

      continue;
    }
    else
    {
      // Unexpected error code - log and throw
      free(adapter_addresses);
      adapter_addresses = NULL;

      // @todo
      LOG_AND_THROW_HERE();
    }
  }

  // Iterate through all of the adapters
  for (adapter = adapter_addresses; NULL != adapter; adapter = adapter->Next)
  {
    // Skip loopback adapters
    if (IF_TYPE_SOFTWARE_LOOPBACK == adapter->IfType)
    {
      continue;
    }

    // Parse all IPv4 and IPv6 addresses
    for (
      IP_ADAPTER_UNICAST_ADDRESS* address = adapter->FirstUnicastAddress; 
      NULL != address;
      address = address->Next)
    {
      auto family = address->Address.lpSockaddr->sa_family;
      if (AF_INET == family)
      {
        // IPv4
        SOCKADDR_IN* ipv4 = reinterpret_cast<SOCKADDR_IN*>(address->Address.lpSockaddr);

        char str_buffer[INET_ADDRSTRLEN] = {0};
        inet_ntop(AF_INET, &(ipv4->sin_addr), str_buffer, INET_ADDRSTRLEN);
        ipAddrs.mIpv4.push_back(str_buffer);
      }
      else if (AF_INET6 == family)
      {
        // IPv6
        SOCKADDR_IN6* ipv6 = reinterpret_cast<SOCKADDR_IN6*>(address->Address.lpSockaddr);

        char str_buffer[INET6_ADDRSTRLEN] = {0};
        inet_ntop(AF_INET6, &(ipv6->sin6_addr), str_buffer, INET6_ADDRSTRLEN);

        std::string ipv6_str(str_buffer);

        // Detect and skip non-external addresses
        bool is_link_local(false);
        bool is_special_use(false);

        if (0 == ipv6_str.find("fe"))
        {
          char c = ipv6_str[2];
          if (c == '8' || c == '9' || c == 'a' || c == 'b')
          {
            is_link_local = true;
          }
        }
        else if (0 == ipv6_str.find("2001:0:"))
        {
          is_special_use = true;
        }

        if (! (is_link_local || is_special_use))
        {
          ipAddrs.mIpv6.push_back(ipv6_str);
        }
      }
      else
      {
        // Skip all other types of addresses
        continue;
      }
    }
  }

  // Cleanup
  free(adapter_addresses);
  adapter_addresses = NULL;

  // Cheers!
}

AWS S3 - How to fix 'The request signature we calculated does not match the signature' error?

Just to add to the many different ways this can show up.

If you using safari on iOS and you are connected to the Safari Technology Preview console - you will see the same problem. If you disconnect from the console - the problem will go away.

Of course it makes troubleshooting other issues difficult but it is a 100% repro.

I am trying to figure out what I can change in STP to stop it from doing this but have not found it yet.

jQuery: Get height of hidden element in jQuery

I've actually resorted to a bit of trickery to deal with this at times. I developed a jQuery scrollbar widget where I encountered the problem that I don't know ahead of time if the scrollable content is a part of a hidden piece of markup or not. Here's what I did:

// try to grab the height of the elem
if (this.element.height() > 0) {
    var scroller_height = this.element.height();
    var scroller_width = this.element.width();

// if height is zero, then we're dealing with a hidden element
} else {
    var copied_elem = this.element.clone()
                      .attr("id", false)
                      .css({visibility:"hidden", display:"block", 
                               position:"absolute"});
    $("body").append(copied_elem);
    var scroller_height = copied_elem.height();
    var scroller_width = copied_elem.width();
    copied_elem.remove();
}

This works for the most part, but there's an obvious problem that can potentially come up. If the content you are cloning is styled with CSS that includes references to parent markup in their rules, the cloned content will not contain the appropriate styling, and will likely have slightly different measurements. To get around this, you can make sure that the markup you are cloning has CSS rules applied to it that do not include references to parent markup.

Also, this didn't come up for me with my scroller widget, but to get the appropriate height of the cloned element, you'll need to set the width to the same width of the parent element. In my case, a CSS width was always applied to the actual element, so I didn't have to worry about this, however, if the element doesn't have a width applied to it, you may need to do some kind of recursive traversal of the element's DOM ancestry to find the appropriate parent element's width.

Working with $scope.$emit and $scope.$on

First of all, parent-child scope relation does matter. You have two possibilities to emit some event:

  • $broadcast -- dispatches the event downwards to all child scopes,
  • $emit -- dispatches the event upwards through the scope hierarchy.

I don't know anything about your controllers (scopes) relation, but there are several options:

  1. If scope of firstCtrl is parent of the secondCtrl scope, your code should work by replacing $emit by $broadcast in firstCtrl:

    function firstCtrl($scope)
    {
        $scope.$broadcast('someEvent', [1,2,3]);
    }
    
    function secondCtrl($scope)
    {
        $scope.$on('someEvent', function(event, mass) { console.log(mass); });
    }
    
  2. In case there is no parent-child relation between your scopes you can inject $rootScope into the controller and broadcast the event to all child scopes (i.e. also secondCtrl).

    function firstCtrl($rootScope)
    {
        $rootScope.$broadcast('someEvent', [1,2,3]);
    }
    
  3. Finally, when you need to dispatch the event from child controller to scopes upwards you can use $scope.$emit. If scope of firstCtrl is parent of the secondCtrl scope:

    function firstCtrl($scope)
    {
        $scope.$on('someEvent', function(event, data) { console.log(data); });
    }
    
    function secondCtrl($scope)
    {
        $scope.$emit('someEvent', [1,2,3]);
    }
    

How do I merge a git tag onto a branch

This is the only comprehensive and reliable way I've found to do this.

Assume you want to merge "tag_1.0" into "mybranch".

    $git checkout tag_1.0 (will create a headless branch)
    $git branch -D tagbranch (make sure this branch doesn't already exist locally)
    $git checkout -b tagbranch
    $git merge -s ours mybranch
    $git commit -am "updated mybranch with tag_1.0"
    $git checkout mybranch
    $git merge tagbranch

How to stop VMware port error of 443 on XAMPP Control Panel v3.2.1

On Xampp edit apache config

  1. Click Apache 'config'
  2. Select 'httpd-ssl.conf'
  3. Look for 'Listen 443', change it to 'Listen 4430'

How to read a list of files from a folder using PHP?

There is this function scandir():

$dir = 'dir';
$files = scandir($dir, 0);
for($i = 2; $i < count($files); $i++)
    print $files[$i]."<br>";

More here in the php.net manual

How can I center text (horizontally and vertically) inside a div block?

Apply style:

position: absolute;
top: 50%;
left: 0;
right: 0;

Your text would be centered irrespective of its length.

CSS image overlay with color and transparency

JSFiddle Demo

HTML:

<div class="image-holder">
    <img src="http://codemancers.com/img/who-we-are-bg.png" />
</div>

CSS:

.image-holder {
    display:inline-block;
    position: relative;
}
.image-holder:after {
    content:'';
    top: 0;
    left: 0;
    z-index: 10;
    width: 100%;
    height: 100%;
    display: block;
    position: absolute;
    background: blue;
    opacity: 0.1;
}
.image-holder:hover:after {
    opacity: 0;
}

How to find numbers from a string?

Expanding on brettdj's answer, in order to parse disjoint embedded digits into separate numbers:

Sub TestNumList()
    Dim NumList As Variant  'Array

    NumList = GetNums("34d1fgd43g1 dg5d999gdg2076")

    Dim i As Integer
    For i = LBound(NumList) To UBound(NumList)
        MsgBox i + 1 & ": " & NumList(i)
    Next i
End Sub

Function GetNums(ByVal strIn As String) As Variant  'Array of numeric strings
    Dim RegExpObj As Object
    Dim NumStr As String

    Set RegExpObj = CreateObject("vbscript.regexp")
    With RegExpObj
        .Global = True
        .Pattern = "[^\d]+"
        NumStr = .Replace(strIn, " ")
    End With

    GetNums = Split(Trim(NumStr), " ")
End Function

Firefox 'Cross-Origin Request Blocked' despite headers

I've found solution after 2 days :(.

Important note: when responding to a credentialed request, server must specify a domain, and cannot use wild carding.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials

What is the proof of of (N–1) + (N–2) + (N–3) + ... + 1= N*(N–1)/2

(N-1) + (N-2) +...+ 2 + 1 is a sum of N-1 items. Now reorder the items so, that after the first comes the last, then the second, then the second to last, i.e. (N-1) + 1 + (N-2) + 2 +... The way the items are ordered now you can see that each of those pairs is equal to N (N-1+1 is N, N-2+2 is N). Since there are N-1 items, there are (N-1)/2 such pairs. So you're adding N (N-1)/2 times, so the total value is N*(N-1)/2.

git: fatal unable to auto-detect email address

If git config --global user.email "[email protected]" git config --global user.name "github_username"

Dont work like in my case, you can use:

git config --replace-all user.email "[email protected]"
git config --replace-all user.name "github_username"

How do I add a library (android-support-v7-appcompat) in IntelliJ IDEA

Another yet simple solution is to paste these line into the build.gradle file

dependencies {

    //import of gridlayout
    compile 'com.android.support:gridlayout-v7:19.0.0'
    compile 'com.android.support:appcompat-v7:+'
}

Open Facebook page from Android app?

Answering this in October 2018. The working code is the one using the pageID. I just tested it and it is functional.

public static void openUrl(Context ctx, String url){
    Uri uri = Uri.parse(url);
    if (url.contains(("facebook"))){
        try {
            ApplicationInfo applicationInfo = ctx.getPackageManager().getApplicationInfo("com.facebook.katana", 0);
            if (applicationInfo.enabled) {
                uri = Uri.parse("fb://page/<page_id>");
                openURI(ctx, uri);
                return;
            }
        } catch (PackageManager.NameNotFoundException ignored) {
            openURI(ctx, uri);
            return;
        }
    }

What is 0x10 in decimal?

Notice that '10' is the representation of the base in that base:

10 is 2(decimal) in base-2

10 is 3(decimal) in base-3

...

10 is 10(decimal) in base-10

...

10 is 16(decimal) in base-16 (hexadecimal)

...

10 is 1024(decimal) in base-1024

...and so on

Regular expression for floating point numbers

For those who searching a regex which would validate an entire input that should be a signed float point number on every single character typed by a user.

I.e. a sign goes first (should match and be valid), then all the digits (still match and valid) and its optional decimal part.

In JS, we use onkeydown/oninput event to do that + the following regex:

^[+-]?[0-9]*([\.][0-9]*)?$

Is there a template engine for Node.js?

WARNING : JinJs is not maintained anymore. It is still working but not compatible with the lastest version of express.

You could try using jinjs. It is a port of the Jinja, a very good Python templating system. You can install it with npm like this :

npm install jinjs

in template.tpl :

I say : "{{ sentence }}"

in your template.js :

jinjs = require('jinjs');
jinjs.registerExtension('.tpl');
tpl = require('./template');
str = tpl.render ({sentence : 'Hello, World!'});
console.log(str);

The output will be :

I say : "Hello, World!"

We are actively developing it, a good documentation should come pretty soon.

javascript close current window

To close your current window using JS, do this. First open the current window to trick your current tab into thinking it has been opened by a script. Then close it using window.close(). The below script should go into the parent window, not the child window. You could run this after running the script to open the child.

<script type="text/javascript">
    window.open('','_parent',''); 
    window.close();
</script>

python's re: return True if string contains regex pattern

Here's a function that does what you want:

import re

def is_match(regex, text):
    pattern = re.compile(regex, text)
    return pattern.search(text) is not None

The regular expression search method returns an object on success and None if the pattern is not found in the string. With that in mind, we return True as long as the search gives us something back.

Examples:

>>> is_match('ba[rzd]', 'foobar')
True
>>> is_match('ba[zrd]', 'foobaz')
True
>>> is_match('ba[zrd]', 'foobad')
True
>>> is_match('ba[zrd]', 'foobam')
False

Make column fixed position in bootstrap

in Bootstrap 3 class="affix" works, but in Bootstrap 4 it does not. I solved this problem in Bootstrap 4 with class="sticky-top" (using position: fixed in CSS has its own problems)

code will be something like this:

<div class="row">
    <div class="col-lg-3">
        <div class="sticky-top">
            Fixed content
        </div>
    </div>
    <div class="col-lg-9">
        Normal scrollable content
    </div>
</div>

How to drop all tables from a database with one SQL query?

Use the following script to drop all constraints:

DECLARE @sql NVARCHAR(max)=''

SELECT @sql += ' ALTER TABLE ' + QUOTENAME(TABLE_SCHEMA) + '.'+ QUOTENAME(TABLE_NAME) +    ' NOCHECK CONSTRAINT all; '
FROM   INFORMATION_SCHEMA.TABLES
WHERE  TABLE_TYPE = 'BASE TABLE'

Exec Sp_executesql @sql

Then run the following to drop all tables:

select @sql='';

SELECT @sql += ' Drop table ' + QUOTENAME(TABLE_SCHEMA) + '.'+ QUOTENAME(TABLE_NAME) + '; '
FROM   INFORMATION_SCHEMA.TABLES
WHERE  TABLE_TYPE = 'BASE TABLE'

Exec Sp_executesql @sql

This worked for me in Azure SQL Database where 'sp_msforeachtable' was not available!

How to unblock with mysqladmin flush hosts

mysqladmin is not a SQL statement. It's a little helper utility program you'll find on your MySQL server... and "flush-hosts" is one of the things it can do. ("status" and "shutdown" are a couple of other things that come to mind).

You type that command from a shell prompt.

Alternately, from your query browser (such as phpMyAdmin), the SQL statement you're looking for is simply this:

FLUSH HOSTS;

http://dev.mysql.com/doc/refman/5.6/en/flush.html

http://dev.mysql.com/doc/refman/5.6/en/mysqladmin.html

Why use 'virtual' for class properties in Entity Framework model definitions?

It allows the Entity Framework to create a proxy around the virtual property so that the property can support lazy loading and more efficient change tracking. See What effect(s) can the virtual keyword have in Entity Framework 4.1 POCO Code First? for a more thorough discussion.

Edit to clarify "create a proxy around": By "create a proxy around" I'm referring specifically to what the Entity Framework does. The Entity Framework requires your navigation properties to be marked as virtual so that lazy loading and efficient change tracking are supported. See Requirements for Creating POCO Proxies.
The Entity Framework uses inheritance to support this functionality, which is why it requires certain properties to be marked virtual in your base class POCOs. It literally creates new types that derive from your POCO types. So your POCO is acting as a base type for the Entity Framework's dynamically created subclasses. That's what I meant by "create a proxy around".

The dynamically created subclasses that the Entity Framework creates become apparent when using the Entity Framework at runtime, not at static compilation time. And only if you enable the Entity Framework's lazy loading or change tracking features. If you opt to never use the lazy loading or change tracking features of the Entity Framework (which is not the default) then you needn't declare any of your navigation properties as virtual. You are then responsible for loading those navigation properties yourself, either using what the Entity Framework refers to as "eager loading", or manually retrieving related types across multiple database queries. You can and should use lazy loading and change tracking features for your navigation properties in many scenarios though.

If you were to create a standalone class and mark properties as virtual, and simply construct and use instances of those classes in your own application, completely outside of the scope of the Entity Framework, then your virtual properties wouldn't gain you anything on their own.

Edit to describe why properties would be marked as virtual

Properties such as:

 public ICollection<RSVP> RSVPs { get; set; }

Are not fields and should not be thought of as such. These are called getters and setters and at compilation time, they are converted into methods.

//Internally the code looks more like this:
public ICollection<RSVP> get_RSVPs()
{
    return _RSVPs;
}

public void set_RSVPs(RSVP value)
{
    _RSVPs = value;
}

private RSVP _RSVPs;

That's why they're marked as virtual for use in the Entity Framework, it allows the dynamically created classes to override the internally generated get and set functions. If your navigation property getter/setters are working for you in your Entity Framework usage, try revising them to just properties, recompile, and see if the Entity Framework is able to still function properly:

 public virtual ICollection<RSVP> RSVPs;

Find and replace - Add carriage return OR Newline

If you want to avoid the hassle of escaping the special characters in your search and replacement string when using regular expressions, do the following steps:

  1. Search for your original string, and replace it with "UniqueString42", with regular expressions off.
  2. Search for "UniqueString42" and replace it with "UniqueString42\nUniqueString1337", with regular expressions on
  3. Search for "UniqueString42" and replace it with the first line of your replacement (often your original string), with regular expressions off.
  4. Search for "UniqueString42" and replace it with the second line of your replacement, with regular expressions off.

Note that even if you want to manually pich matches for the first search and replace, you can safely use "replace all" for the three last steps.

Example

For example, if you want to replace this:

public IFoo SomeField { get { return this.SomeField; } }

with that:

public IFoo Foo { get { return this.MyFoo; } }
public IBar Bar { get { return this.MyBar; } }

You would do the following substitutions:

  1. public IFoo SomeField { get { return this.SomeField; } } ? XOXOXOXO (regex off).
  2. XOXOXOXO ? XOXOXOXO\nHUHUHUHU (regex on).
  3. XOXOXOXO ? public IFoo Foo { get { return this.MyFoo; } } (regex off).
  4. HUHUHUHU ? public IFoo Bar { get { return this.MyBar; } } (regex off).

How to append multiple items in one line in Python

Use this :

#Inputs
L1 = [1, 2]
L2 = [3,4,5]

#Code
L1+L2

#Output
[1, 2, 3, 4, 5]

By using the (+) operator you can skip the multiple append & extend operators in just one line of code and this is valid for more then two of lists by L1+L2+L3+L4.......etc.

Happy Learning...:)

Why is Android Studio reporting "URI is not registered"?

i had the same error. I solved it by importing the project again to the android studio.

DateTime vs DateTimeOffset

The only negative side of DateTimeOffset I see is that Microsoft "forgot" (by design) to support it in their XmlSerializer class. But it has since been added to the XmlConvert utility class.

XmlConvert.ToDateTimeOffset

XmlConvert.ToString

I say go ahead and use DateTimeOffset and TimeZoneInfo because of all the benefits, just beware when creating entities which will or may be serialized to or from XML (all business objects then).

Display milliseconds in Excel

I did this in Excel 2000.

This statement should be: ms = Round(temp - Int(temp), 3) * 1000

You need to create a custom format for the result cell of [h]:mm:ss.000

Is it possible to preview stash contents in git?

I like how gitk can show you exactly what was untracked or sitting in the index, but by default it will show those stash "commits" in the middle of all your other commits on the current branch.

The trick is to run gitk as follows:

gitk "stash@{0}^!"

(The quoting is there to make it work in Powershell but this way it should still work in other shells as well.)

If you look up this syntax in the gitrevisions help page you'll find the following:

The r1^! notation includes commit r1 but excludes all of its parents. By itself, this notation denotes the single commit r1.

This will apparently put gitk in such a mode that only the immediate parents of the selected commit are shown, which is exactly what I like.


If you want to take this further and list all stashes then you can run this:

gitk `git stash list '--pretty=format:%gd^!'`

(Those single quotes inside the backticks are necessary to appease Bash, otherwise it complains about the exclamation mark)

If you are on Windows and using cmd or Powershell:

gitk "--argscmd=git stash list --pretty=format:%gd^!"

How do I change the background color of the ActionBar of an ActionBarActivity using XML?

If you are using androidx AppCompact. Use below code.

androidx.appcompat.app.ActionBar actionBar = getSupportActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable("Color"));

Fill drop down list on selection of another drop down list

enter image description here

enter image description here

enter image description here

Model:

namespace MvcApplicationrazor.Models
{
    public class CountryModel
    {
        public List<State> StateModel { get; set; }
        public SelectList FilteredCity { get; set; }
    }
    public class State
    {
        public int Id { get; set; }
        public string StateName { get; set; }
    }
    public class City
    {
        public int Id { get; set; }
        public int StateId { get; set; }
        public string CityName { get; set; }
    }
}   

Controller:

public ActionResult Index()
        {
            CountryModel objcountrymodel = new CountryModel();
            objcountrymodel.StateModel = new List<State>();
            objcountrymodel.StateModel = GetAllState();
            return View(objcountrymodel);
        }


        //Action result for ajax call
        [HttpPost]
        public ActionResult GetCityByStateId(int stateid)
        {
            List<City> objcity = new List<City>();
            objcity = GetAllCity().Where(m => m.StateId == stateid).ToList();
            SelectList obgcity = new SelectList(objcity, "Id", "CityName", 0);
            return Json(obgcity);
        }
        // Collection for state
        public List<State> GetAllState()
        {
            List<State> objstate = new List<State>();
            objstate.Add(new State { Id = 0, StateName = "Select State" });
            objstate.Add(new State { Id = 1, StateName = "State 1" });
            objstate.Add(new State { Id = 2, StateName = "State 2" });
            objstate.Add(new State { Id = 3, StateName = "State 3" });
            objstate.Add(new State { Id = 4, StateName = "State 4" });
            return objstate;
        }
        //collection for city
        public List<City> GetAllCity()
        {
            List<City> objcity = new List<City>();
            objcity.Add(new City { Id = 1, StateId = 1, CityName = "City1-1" });
            objcity.Add(new City { Id = 2, StateId = 2, CityName = "City2-1" });
            objcity.Add(new City { Id = 3, StateId = 4, CityName = "City4-1" });
            objcity.Add(new City { Id = 4, StateId = 1, CityName = "City1-2" });
            objcity.Add(new City { Id = 5, StateId = 1, CityName = "City1-3" });
            objcity.Add(new City { Id = 6, StateId = 4, CityName = "City4-2" });
            return objcity;
        }

View:

@model MvcApplicationrazor.Models.CountryModel
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script language="javascript" type="text/javascript">
    function GetCity(_stateId) {
        var procemessage = "<option value='0'> Please wait...</option>";
        $("#ddlcity").html(procemessage).show();
        var url = "/Test/GetCityByStateId/";

        $.ajax({
            url: url,
            data: { stateid: _stateId },
            cache: false,
            type: "POST",
            success: function (data) {
                var markup = "<option value='0'>Select City</option>";
                for (var x = 0; x < data.length; x++) {
                    markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
                }
                $("#ddlcity").html(markup).show();
            },
            error: function (reponse) {
                alert("error : " + reponse);
            }
        });

    }
</script>
<h4>
 MVC Cascading Dropdown List Using Jquery</h4>
@using (Html.BeginForm())
{
    @Html.DropDownListFor(m => m.StateModel, new SelectList(Model.StateModel, "Id", "StateName"), new { @id = "ddlstate", @style = "width:200px;", @onchange = "javascript:GetCity(this.value);" })
    <br />
    <br />
    <select id="ddlcity" name="ddlcity" style="width: 200px">

    </select>

    <br /><br />
  }

How can I divide one column of a data frame through another?

Hadley Wickham

dplyr

packages is always a saver in case of data wrangling. To add the desired division as a third variable I would use mutate()

d <- mutate(d, new = min / count2.freq)

Get pixel's RGB using PIL

With numpy :

im = Image.open('image.gif')
im_matrix = np.array(im)
print(im_matrix[0][0])

Give RGB vector of the pixel in position (0,0)

XSLT counting elements with a given value

Your xpath is just a little off:

count(//Property/long[text()=$parPropId])

Edit: Cerebrus quite rightly points out that the code in your OP (using the implicit value of a node) is absolutely fine for your purposes. In fact, since it's quite likely you want to work with the "Property" node rather than the "long" node, it's probably superior to ask for //Property[long=$parPropId] than the text() xpath, though you could make a case for the latter on readability grounds.

What can I say, I'm a bit tired today :)

How do I set/unset a cookie with jQuery?

<script type="text/javascript">
    function setCookie(key, value, expiry) {
        var expires = new Date();
        expires.setTime(expires.getTime() + (expiry * 24 * 60 * 60 * 1000));
        document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
    }

    function getCookie(key) {
        var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
        return keyValue ? keyValue[2] : null;
    }

    function eraseCookie(key) {
        var keyValue = getCookie(key);
        setCookie(key, keyValue, '-1');
    }

</script>

You can set the cookies as like

setCookie('test','1','1'); //(key,value,expiry in days)

You can get the cookies as like

getCookie('test');

And finally you can erase the cookies like this one

eraseCookie('test');

Hope it will helps to someone :)

EDIT:

If you want to set the cookie to all the path/page/directory then set path attribute to the cookie

function setCookie(key, value, expiry) {
        var expires = new Date();
        expires.setTime(expires.getTime() + (expiry * 24 * 60 * 60 * 1000));
        document.cookie = key + '=' + value + ';path=/' + ';expires=' + expires.toUTCString();
}

Thanks, vicky

d3.select("#element") not working when code above the html element

just add your <script src="./custom.js"></script> before </bod> tag. that is supply time to d3.select(#chart) detect your #chart element in html body

How can I style an Android Switch?

It's an awesome detailed reply by Janusz. But just for the sake of people who are coming to this page for answers, the easier way is at http://android-holo-colors.com/ (dead link) linked from Android Asset Studio

A good description of all the tools are at AndroidOnRocks.com (site offline now)

However, I highly recommend everybody to read the reply from Janusz as it will make understanding clearer. Use the tool to do stuffs real quick

Twitter Bootstrap 3 Sticky Footer

Referring to the official Boostrap3 sticky footer example, there is no need to add <div id="push"></div>, and the CSS is simpler.

The CSS used in the official example is:

/* Sticky footer styles
-------------------------------------------------- */

html,
body {
  height: 100%;
  /* The html and body elements cannot have any padding or margin. */
}

/* Wrapper for page content to push down footer */
#wrap {
  min-height: 100%;
  height: auto;
  /* Negative indent footer by its height */
  margin: 0 auto -60px;
  /* Pad bottom by footer height */
  padding: 0 0 60px;
}

/* Set the fixed height of the footer here */
#footer {
  height: 60px;
  background-color: #f5f5f5;
}

and the essential HTML:

<body>

    <!-- Wrap all page content here -->
    <div id="wrap">

      <!-- Begin page content -->
      <div class="container">

      </div>
    </div>

    <div id="footer">
      <div class="container">

      </div>
    </div>
</body>

You can find the link for this css in the sticky-footer example's source code.

<!-- Custom styles for this template -->
<link href="sticky-footer.css" rel="stylesheet">

Full URL : http://getbootstrap.com/examples/sticky-footer/sticky-footer.css

Post-increment and pre-increment within a 'for' loop produce same output

After evaluating i++ or ++i, the new value of i will be the same in both cases. The difference between pre- and post-increment is in the result of evaluating the expression itself.

++i increments i and evaluates to the new value of i.

i++ evaluates to the old value of i, and increments i.

The reason this doesn't matter in a for loop is that the flow of control works roughly like this:

  1. test the condition
  2. if it is false, terminate
  3. if it is true, execute the body
  4. execute the incrementation step

Because (1) and (4) are decoupled, either pre- or post-increment can be used.

How to use the pass statement?

as the book said, I only ever use it as a temporary placeholder, ie,

# code that does something to to a variable, var
if var == 2000:
    pass
else:
    var += 1

and then later fill in the scenario where var == 2000

Get last 5 characters in a string

Dim a As String = Microsoft.VisualBasic.right("I will be going to school in 2011!", 5)
MsgBox("the value is:" & a)

How can a query multiply 2 cell for each row MySQL?

Use this:

SELECT 
    Pieces, Price, 
    Pieces * Price as 'Total' 
FROM myTable

How to get character for a given ascii value

There are a few ways to do this.

Using char struct (to string and back again)

string _stringOfA = char.ConvertFromUtf32(65);

int _asciiOfA = char.ConvertToUtf32("A", 0);

Simply casting the value (char and string shown)

char _charA = (char)65;

string _stringA = ((char)65).ToString();

Using ASCIIEncoding.
This can be used in a loop to do a whole array of bytes

var _bytearray = new byte[] { 65 };

ASCIIEncoding _asiiencode = new ASCIIEncoding();

string _alpha = _asiiencode .GetString(_newByte, 0, 1);

You can override the type converter class, this would allow you to do some fancy validation of the values:

var _converter = new ASCIIConverter();

string _stringA = (string)_converter.ConvertFrom(65);

int _intOfA = (int)_converter.ConvertTo("A", typeof(int));

Here is the Class:

public class ASCIIConverter : TypeConverter
{
    // Overrides the CanConvertFrom method of TypeConverter.
    // The ITypeDescriptorContext interface provides the context for the
    // conversion. Typically, this interface is used at design time to 
    // provide information about the design-time container.
    public override bool CanConvertFrom(ITypeDescriptorContext context,
       Type sourceType)
    {
        if (sourceType == typeof(string))
        {
            return true;
        }
        return base.CanConvertFrom(context, sourceType);
    }

    public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
    {
        if (destinationType == typeof(int))
        {
            return true;
        }
        return base.CanConvertTo(context, destinationType);
    }


    // Overrides the ConvertFrom method of TypeConverter.
    public override object ConvertFrom(ITypeDescriptorContext context,
       CultureInfo culture, object value)
    {

        if (value is int)
        {
            //you can validate a range of int values here
            //for instance 
            //if (value >= 48 && value <= 57)
            //throw error
            //end if

            return char.ConvertFromUtf32(65);
        }
        return base.ConvertFrom(context, culture, value);
    }

    // Overrides the ConvertTo method of TypeConverter.
    public override object ConvertTo(ITypeDescriptorContext context,
       CultureInfo culture, object value, Type destinationType)
    {
        if (destinationType == typeof(int))
        {
            return char.ConvertToUtf32((string)value, 0);
        }
        return base.ConvertTo(context, culture, value, destinationType);
    }
}

Add horizontal scrollbar to html table

The 'more than 100% width' on the table really made it work for me.

_x000D_
_x000D_
.table-wrap {_x000D_
    width: 100%;_x000D_
    overflow: auto;_x000D_
}_x000D_
_x000D_
table {_x000D_
    table-layout: fixed;_x000D_
    width: 200%;_x000D_
}
_x000D_
_x000D_
_x000D_

SpringMVC RequestMapping for GET parameters

You should write a kind of template into the @RequestMapping:

http://localhost:8080/userGrid?_search=${search}&nd=${nd}&rows=${rows}&page=${page}&sidx=${sidx}&sord=${sord}

Now define your business method like following:

@RequestMapping("/userGrid?_search=${search}&nd=${nd}&rows=${rows}&page=${page}&sidx=${sidx}&sord=${sord}")
public @ResponseBody GridModel getUsersForGrid(
@RequestParam(value = "search") String search, 
@RequestParam(value = "nd") int nd, 
@RequestParam(value = "rows") int rows, 
@RequestParam(value = "page") int page, 
@RequestParam(value = "sidx") int sidx, 
@RequestParam(value = "sort") Sort sort) {
...............
}

So, framework will map ${foo} to appropriate @RequestParam.

Since sort may be either asc or desc I'd define it as a enum:

public enum Sort {
    asc, desc
}

Spring deals with enums very well.

Meaning of delta or epsilon argument of assertEquals for double values

Epsilon is a difference between expected and actual values which you can accept thinking they are equal. You can set .1 for example.

How to create an XML document using XmlDocument?

What about:

#region Using Statements
using System;
using System.Xml;
#endregion 

class Program {
    static void Main( string[ ] args ) {
        XmlDocument doc = new XmlDocument( );

        //(1) the xml declaration is recommended, but not mandatory
        XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration( "1.0", "UTF-8", null );
        XmlElement root = doc.DocumentElement;
        doc.InsertBefore( xmlDeclaration, root );

        //(2) string.Empty makes cleaner code
        XmlElement element1 = doc.CreateElement( string.Empty, "body", string.Empty );
        doc.AppendChild( element1 );

        XmlElement element2 = doc.CreateElement( string.Empty, "level1", string.Empty );
        element1.AppendChild( element2 );

        XmlElement element3 = doc.CreateElement( string.Empty, "level2", string.Empty );
        XmlText text1 = doc.CreateTextNode( "text" );
        element3.AppendChild( text1 );
        element2.AppendChild( element3 );

        XmlElement element4 = doc.CreateElement( string.Empty, "level2", string.Empty );
        XmlText text2 = doc.CreateTextNode( "other text" );
        element4.AppendChild( text2 );
        element2.AppendChild( element4 );

        doc.Save( "D:\\document.xml" );
    }
}

(1) Does a valid XML file require an xml declaration?
(2) What is the difference between String.Empty and “” (empty string)?


The result is:

<?xml version="1.0" encoding="UTF-8"?>
<body>
  <level1>
    <level2>text</level2>
    <level2>other text</level2>
  </level1>
</body>

But I recommend you to use LINQ to XML which is simpler and more readable like here:

#region Using Statements
using System;
using System.Xml.Linq;
#endregion 

class Program {
    static void Main( string[ ] args ) {
        XDocument doc = new XDocument( new XElement( "body", 
                                           new XElement( "level1", 
                                               new XElement( "level2", "text" ), 
                                               new XElement( "level2", "other text" ) ) ) );
        doc.Save( "D:\\document.xml" );
    }
}

The transaction manager has disabled its support for remote/network transactions

I was having this issue with a linked server in SSMS while trying to create a stored procedure.

On the linked server, I changed the server option "Enable Promotion on Distributed Transaction" to False.

Screenshot of Server Options

Create a table without a header in Markdown

@thamme-gowda's solution works for images too!

| | |:----------------------------------------------------------------------------:| | ![](https://gravatar.com/avatar/4cc702785290b4934c531c56f6061e5e "Tonejito") |

You can check this out on a gist I made for that. Here is a render of the table hack on GitHub and GitLab:

How to convert string to long

String s = "1";

try {
   long l = Long.parseLong(s);       
} catch (NumberFormatException e) {
   System.out.println("NumberFormatException: " + e.getMessage());
}

How to initialize a two-dimensional array in Python?

Usually when you want multidimensional arrays you don't want a list of lists, but rather a numpy array or possibly a dict.

For example, with numpy you would do something like

import numpy
a = numpy.empty((10, 10))
a.fill(foo)

Can't install via pip because of egg_info error

See this : What Python version can I use with Django?¶ https://docs.djangoproject.com/en/2.0/faq/install/

if you are using python27 you must to set django version :

try: $pip install django==1.9

Count the number of occurrences of each letter in string

//c code for count the occurence of each character in a string.

void main()
   {
   int i,j; int c[26],count=0; char a[]="shahid";
   clrscr();
   for(i=0;i<26;i++)
    {
        count=0;
          for(j=0;j<strlen(a);j++)
                {
                 if(a[j]==97+i)
                    {
                     count++;
                         }
                           }
                  c[i]=count;
               }
              for(i=0;i<26;i++)
               {
              j=97+i;
          if(c[i]!=0) {  printf("%c of %d times\n",j,c[i]);
                 }
              }
           getch();
           }

'AND' vs '&&' as operator

I guess it's a matter of taste, although (mistakenly) mixing them up might cause some undesired behaviors:

true && false || false; // returns false

true and false || false; // returns true

Hence, using && and || is safer for they have the highest precedence. In what regards to readability, I'd say these operators are universal enough.

UPDATE: About the comments saying that both operations return false ... well, in fact the code above does not return anything, I'm sorry for the ambiguity. To clarify: the behavior in the second case depends on how the result of the operation is used. Observe how the precedence of operators comes into play here:

var_dump(true and false || false); // bool(false)

$a = true and false || false; var_dump($a); // bool(true)

The reason why $a === true is because the assignment operator has precedence over any logical operator, as already very well explained in other answers.

CSS: Set Div height to 100% - Pixels

The best way to do this is to use view port styles. It just does the work and no other techniques needed.

Code:

_x000D_
_x000D_
div{_x000D_
  height:100vh;_x000D_
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

How to iterate object in JavaScript?

You can do it with the below code. You first get the data array using dictionary.data and assign it to the data variable. After that you can iterate it using a normal for loop. Each row will be a row object in the array.

var data = dictionary.data;

for (var i in data)
{
     var id = data[i].id;
     var name = data[i].name;
}

You can follow similar approach to iterate the image array.

How to convert a unix timestamp (seconds since epoch) to Ruby DateTime?

DateTime.strptime can handle seconds since epoch. The number must be converted to a string:

require 'date'
DateTime.strptime("1318996912",'%s')

findViewByID returns null

findViewById also can return null if you're inside a Fragment. As described here: findViewById in Fragment

You should call getView() to return the top level View inside a Fragment. Then you can find the layout items (buttons, textviews, etc)

How do I see all foreign keys to a table or column?

EDIT: As pointed out in the comments, this is not the correct answer to the OPs question, but it is useful to know this command. This question showed up in Google for what I was looking for, and figured I'd leave this answer for the others to find.

SHOW CREATE TABLE `<yourtable>`;

I found this answer here: MySQL : show constraints on tables command

I needed this way because I wanted to see how the FK functioned, rather than just see if it existed or not.

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

You can also load the content with cURL, if file_get_contents insn't enabled on your server.

Example:

$ch = curl_init();  

curl_setopt($ch,CURLOPT_URL,"http://feeds.bbci.co.uk/sport/0/football/rss.xml?edition=int");
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);

$output = curl_exec($ch);

curl_close($ch);

$items = simplexml_load_string($output);

What is Python used for?

Why should you learn Python Programming Language?

Python offers a stepping stone into the world of programming. Even though Python Programming Language has been around for 25 years, it is still rising in popularity. Some of the biggest advantage of Python are it's

  • Easy to Read & Easy to Learn
  • Very productive or small as well as big projects
  • Big libraries for many things

enter image description here

What is Python Programming Language used for?

As a general purpose programming language, Python can be used for multiple things. Python can be easily used for small, large, online and offline projects. The best options for utilizing Python are web development, simple scripting and data analysis. Below are a few examples of what Python will let you do:

Web Development:

You can use Python to create web applications on many levels of complexity. There are many excellent Python web frameworks including, Pyramid, Django and Flask, to name a few.

Data Analysis:

Python is the leading language of choice for many data scientists. Python has grown in popularity, within this field, due to its excellent libraries including; NumPy and Pandas and its superb libraries for data visualisation like Matplotlib and Seaborn.

Machine Learning:

What if you could predict customer satisfaction or analyse what factors will affect household pricing or to predict stocks over the next few days, based on previous years data? There are many wonderful libraries implementing machine learning algorithms such as Scikit-Learn, NLTK and TensorFlow.

Computer Vision:

You can do many interesting things such as Face detection, Color detection while using Opencv and Python.

Internet Of Things With Raspberry Pi:

Raspberry Pi is a very tiny and affordable computer which was developed for education and has gained enormous popularity among hobbyists with do-it-yourself hardware and automation. You can even build a robot and automate your entire home. Raspberry Pi can be used as the brain for your robot in order to perform various actions and/or react to the environment. The coding on a Raspberry Pi can be performed using Python. The Possibilities are endless!

Game Development:

Create a video game using module Pygame. Basically, you use Python to write the logic of the game. PyGame applications can run on Android devices.

Web Scraping:

If you need to grab data from a website but the site does not have an API to expose data, use Python to scraping data.

Writing Scripts:

If you're doing something manually and want to automate repetitive stuff, such as emails, it's not difficult to automate once you know the basics of this language.

Browser Automation:

Perform some neat things such as opening a browser and posting a Facebook status, you can do it with Selenium with Python.

GUI Development:

Build a GUI application (desktop app) using Python modules Tkinter, PyQt to support it.

Rapid Prototyping:

Python has libraries for just about everything. Use it to quickly built a (lower-performance, often less powerful) prototype. Python is also great for validating ideas or products for established companies and start-ups alike.

Python can be used in so many different projects. If you're a programmer looking for a new language, you want one that is growing in popularity. As a newcomer to programming, Python is the perfect choice for learning quickly and easily.

HTML-5 date field shows as "mm/dd/yyyy" in Chrome, even when valid date is set

I have same problem and i found solution which is given below with full datepicker using simple HTML,Javascript and CSS. In this code i prepare formate like dd/mm/yyyy but you can work any.

HTML Code:

    <body>
<input type="date" id="dt" onchange="mydate1();" hidden/>
<input type="text" id="ndt"  onclick="mydate();" hidden />
<input type="button" Value="Date" onclick="mydate();" />
</body>

CSS Code:

#dt{text-indent: -500px;height:25px; width:200px;}

Javascript Code :

function mydate()
{
  //alert("");
document.getElementById("dt").hidden=false;
document.getElementById("ndt").hidden=true;
}
function mydate1()
{
 d=new Date(document.getElementById("dt").value);
dt=d.getDate();
mn=d.getMonth();
mn++;
yy=d.getFullYear();
document.getElementById("ndt").value=dt+"/"+mn+"/"+yy
document.getElementById("ndt").hidden=false;
document.getElementById("dt").hidden=true;
}

Output:

enter image description here

jquery stop child triggering parent event

Do this:

$(document).ready(function(){
    $(".header").click(function(){
        $(this).children(".children").toggle();
    });
   $(".header a").click(function(e) {
        e.stopPropagation();
   });
});

If you want to read more on .stopPropagation(), look here.

Go doing a GET request and building the Querystring

As a commenter mentioned you can get Values from net/url which has an Encode method. You could do something like this (req.URL.Query() returns the existing url.Values)

package main

import (
    "fmt"
    "log"
    "net/http"
    "os"
)

func main() {
    req, err := http.NewRequest("GET", "http://api.themoviedb.org/3/tv/popular", nil)
    if err != nil {
        log.Print(err)
        os.Exit(1)
    }

    q := req.URL.Query()
    q.Add("api_key", "key_from_environment_or_flag")
    q.Add("another_thing", "foo & bar")
    req.URL.RawQuery = q.Encode()

    fmt.Println(req.URL.String())
    // Output:
    // http://api.themoviedb.org/3/tv/popular?another_thing=foo+%26+bar&api_key=key_from_environment_or_flag
}

http://play.golang.org/p/L5XCrw9VIG

Graphviz: How to go from .dot to a graph?

dot -Tps input.dot > output.eps
dot -Tpng input.dot > output.png

PostScript output seems always there. I am not sure if dot has PNG output by default. This may depend on how you have built it.

css selector to match an element without attribute x

For a more cross-browser solution you could style all inputs the way you want the non-typed, text, and password then another style the overrides that style for radios, checkboxes, etc.

input { border:solid 1px red; }

input[type=radio], 
input[type=checkbox], 
input[type=submit], 
input[type=reset], 
input[type=file] 
      { border:none; }

- Or -

could whatever part of your code that is generating the non-typed inputs give them a class like .no-type or simply not output at all? Additionally this type of selection could be done with jQuery.

How to find the foreach index?

Jonathan is correct. PHP arrays act as a map table mapping keys to values. in some cases you can get an index if your array is defined, such as

$var = array(2,5);

for ($i = 0; $i < count($var); $i++) {
    echo $var[$i]."\n";
}

your output will be

2
5

in which case each element in the array has a knowable index, but if you then do something like the following

$var = array_push($var,10);

for ($i = 0; $i < count($var); $i++) {
    echo $var[$i]."\n";
}

you get no output. This happens because arrays in PHP are not linear structures like they are in most languages. They are more like hash tables that may or may not have keys for all stored values. Hence foreach doesn't use indexes to crawl over them because they only have an index if the array is defined. If you need to have an index, make sure your arrays are fully defined before crawling over them, and use a for loop.

jQuery form validation on button click

Within your click handler, the mistake is the .validate() method; it only initializes the plugin, it does not validate the form.

To eliminate the need to have a submit button within the form, use .valid() to trigger a validation check...

$('#btn').on('click', function() {
    $("#form1").valid();
});

jsFiddle Demo

.validate() - to initialize the plugin (with options) once on DOM ready.

.valid() - to check validation state (boolean value) or to trigger a validation test on the form at any time.

Otherwise, if you had a type="submit" button within the form container, you would not need a special click handler and the .valid() method, as the plugin would capture that automatically.

Demo without click handler


EDIT:

You also have two issues within your HTML...

<input id="field1" type="text" class="required">
  • You don't need class="required" when declaring rules within .validate(). It's redundant and superfluous.

  • The name attribute is missing. Rules are declared within .validate() by their name. The plugin depends upon unique name attributes to keep track of the inputs.

Should be...

<input name="field1" id="field1" type="text" />

What is the difference between rb and r+b modes in file objects

My understanding is that adding r+ opens for both read and write (just like w+, though as pointed out in the comment, will truncate the file). The b just opens it in binary mode, which is supposed to be less aware of things like line separators (at least in C++).

ImportError: No module named - Python

make sure to include __init__.py, which makes Python know that those directories containpackages

How to sleep the thread in node.js without affecting other threads?

If you are referring to the npm module sleep, it notes in the readme that sleep will block execution. So you are right - it isn't what you want. Instead you want to use setTimeout which is non-blocking. Here is an example:

setTimeout(function() {
  console.log('hello world!');
}, 5000);

For anyone looking to do this using es7 async/await, this example should help:

const snooze = ms => new Promise(resolve => setTimeout(resolve, ms));

const example = async () => {
  console.log('About to snooze without halting the event loop...');
  await snooze(1000);
  console.log('done!');
};

example();

Remove trailing comma from comma-separated string

public static String removeExtraCommas(String entry) {
    if(entry==null)
        return null;

    String ret="";
    entry=entry.replaceAll("\\s","");
    String arr[]=entry.split(",");
    boolean start=true;
    for(String str:arr) {
        if(!"".equalsIgnoreCase(str)) {
            if(start) {
                ret=str;
                start=false;
            }
            else {
            ret=ret+","+str;
            }
        }
    }               
    return ret;

}

Check if String contains only letters

While there are many ways to skin this cat, I prefer to wrap such code into reusable extension methods that make it trivial to do going forward. When using extension methods, you can also avoid RegEx as it is slower than a direct character check. I like using the extensions in the Extensions.cs NuGet package. It makes this check as simple as:

  1. Add the https://www.nuget.org/packages/Extensions.cs package to your project.
  2. Add "using Extensions;" to the top of your code.
  3. "smith23".IsAlphabetic() will return False whereas "john smith".IsAlphabetic() will return True. By default the .IsAlphabetic() method ignores spaces, but it can also be overridden such that "john smith".IsAlphabetic(false) will return False since the space is not considered part of the alphabet.
  4. Every other check in the rest of the code is simply MyString.IsAlphabetic().

How to get distinct results in hibernate with joins and row-based limiting (paging)?

I will now explain a different solution, where you can use the normal query and pagination method without having the problem of possibly duplicates or suppressed items.

This Solution has the advance that it is:

  • faster than the PK id solution mentioned in this article
  • preserves the Ordering and don’t use the 'in clause' on a possibly large Dataset of PK’s

The complete Article can be found on my blog

Hibernate gives the possibility to define the association fetching method not only at design time but also at runtime by a query execution. So we use this aproach in conjunction with a simple relfection stuff and can also automate the process of changing the query property fetching algorithm only for collection properties.

First we create a method which resolves all collection properties from the Entity Class:

public static List<String> resolveCollectionProperties(Class<?> type) {
  List<String> ret = new ArrayList<String>();
  try {
   BeanInfo beanInfo = Introspector.getBeanInfo(type);
   for (PropertyDescriptor pd : beanInfo.getPropertyDescriptors()) {
     if (Collection.class.isAssignableFrom(pd.getPropertyType()))
     ret.add(pd.getName());
   }
  } catch (IntrospectionException e) {
    e.printStackTrace();
  }
  return ret;
}

After doing that you can use this little helper method do advise your criteria object to change the FetchMode to SELECT on that query.

Criteria criteria = …

//    … add your expression here  …

// set fetchmode for every Collection Property to SELECT
for (String property : ReflectUtil.resolveCollectionProperties(YourEntity.class)) {
  criteria.setFetchMode(property, org.hibernate.FetchMode.SELECT);
}
criteria.setFirstResult(firstResult);
criteria.setMaxResults(maxResults);
criteria.list();

Doing that is different from define the FetchMode of your entities at design time. So you can use the normal join association fetching on paging algorithms in you UI, because this is most of the time not the critical part and it is more important to have your results as quick as possible.

pandas: merge (join) two data frames on multiple columns

the problem here is that by using the apostrophes you are setting the value being passed to be a string, when in fact, as @Shijo stated from the documentation, the function is expecting a label or list, but not a string! If the list contains each of the name of the columns beings passed for both the left and right dataframe, then each column-name must individually be within apostrophes. With what has been stated, we can understand why this is inccorect:

new_df = pd.merge(A_df, B_df,  how='left', left_on='[A_c1,c2]', right_on = '[B_c1,c2]')

And this is the correct way of using the function:

new_df = pd.merge(A_df, B_df,  how='left', left_on=['A_c1','c2'], right_on = ['B_c1','c2'])

"SyntaxError: Unexpected token < in JSON at position 0"

Protip: Testing json on a local Node.js server? Make sure you don't already have something routing to that path

'/:url(app|assets|stuff|etc)';

How can I one hot encode in Python?

Here i tried with this approach :

import numpy as np
#converting to one_hot





def one_hot_encoder(value, datal):

    datal[value] = 1

    return datal


def _one_hot_values(labels_data):
    encoded = [0] * len(labels_data)

    for j, i in enumerate(labels_data):
        max_value = [0] * (np.max(labels_data) + 1)

        encoded[j] = one_hot_encoder(i, max_value)

    return np.array(encoded)

Launch iOS simulator from Xcode and getting a black screen, followed by Xcode hanging and unable to stop tasks

This could result from not setting the correct deployment info. (i.e. if your storyboard isn't set as the main interface)

Getting "Lock wait timeout exceeded; try restarting transaction" even though I'm not using a transaction

Make sure the database tables are using InnoDB storage engine and READ-COMMITTED transaction isolation level.

You can check it by SELECT @@GLOBAL.tx_isolation, @@tx_isolation; on mysql console.

If it is not set to be READ-COMMITTED then you must set it. Make sure before setting it that you have SUPER privileges in mysql.

You can take help from http://dev.mysql.com/doc/refman/5.0/en/set-transaction.html.

By setting this I think your problem will be get solved.


You might also want to check you aren't attempting to update this in two processes at once. Users ( @tala ) have encountered similar error messages in this context, maybe double-check that...

How to load a text file into a Hive table stored as sequence files

The simple way is to create table as textfile and move the file to the appropriate location

CREATE EXTERNAL TABLE mytable(col1 string, col2 string)
row format delimited fields terminated by '|' stored as textfile;

Copy the file to the HDFS Location where table is created.
Hope this helps!!!

Convert String to Integer in XSLT 1.0

XSLT 1.0 does not have an integer data type, only double. You can use number() to convert a string to a number.

How do I grep for all non-ASCII characters?

You can use the command:

grep --color='auto' -P -n "[\x80-\xFF]" file.xml

This will give you the line number, and will highlight non-ascii chars in red.

In some systems, depending on your settings, the above will not work, so you can grep by the inverse

grep --color='auto' -P -n "[^\x00-\x7F]" file.xml

Note also, that the important bit is the -P flag which equates to --perl-regexp: so it will interpret your pattern as a Perl regular expression. It also says that

this is highly experimental and grep -P may warn of unimplemented features.

How to increase Heap size of JVM

Java command line parameters

-Xms: initial heap size
-Xmx: Maximum heap size

if you are using Tomcat. Update CATALINA_OPTS environment variable

export CATALINA_OPTS=-Xms16m -Xmx256m;

Phone number formatting an EditText in Android

I've recently done a similar formatting like 1 (XXX) XXX-XXXX for Android EditText. Please find the code below. Just use the TextWatcher sub-class as the text changed listener : ....

UsPhoneNumberFormatter addLineNumberFormatter = new UsPhoneNumberFormatter(
            new WeakReference<EditText>(mYourEditText));
    mYourEditText.addTextChangedListener(addLineNumberFormatter);

...

private class UsPhoneNumberFormatter implements TextWatcher {
    //This TextWatcher sub-class formats entered numbers as 1 (123) 456-7890
    private boolean mFormatting; // this is a flag which prevents the
                                    // stack(onTextChanged)
    private boolean clearFlag;
    private int mLastStartLocation;
    private String mLastBeforeText;
    private WeakReference<EditText> mWeakEditText;

    public UsPhoneNumberFormatter(WeakReference<EditText> weakEditText) {
        this.mWeakEditText = weakEditText;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
            int after) {
        if (after == 0 && s.toString().equals("1 ")) {
            clearFlag = true;
        }
        mLastStartLocation = start;
        mLastBeforeText = s.toString();
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before,
            int count) {
        // TODO: Do nothing
    }

    @Override
    public void afterTextChanged(Editable s) {
        // Make sure to ignore calls to afterTextChanged caused by the work
        // done below
        if (!mFormatting) {
            mFormatting = true;
            int curPos = mLastStartLocation;
            String beforeValue = mLastBeforeText;
            String currentValue = s.toString();
            String formattedValue = formatUsNumber(s);
            if (currentValue.length() > beforeValue.length()) {
                int setCusorPos = formattedValue.length()
                        - (beforeValue.length() - curPos);
                mWeakEditText.get().setSelection(setCusorPos < 0 ? 0 : setCusorPos);
            } else {
                int setCusorPos = formattedValue.length()
                        - (currentValue.length() - curPos);
                if(setCusorPos > 0 && !Character.isDigit(formattedValue.charAt(setCusorPos -1))){
                    setCusorPos--;
                }
                mWeakEditText.get().setSelection(setCusorPos < 0 ? 0 : setCusorPos);
            }
            mFormatting = false;
        }
    }

    private String formatUsNumber(Editable text) {
        StringBuilder formattedString = new StringBuilder();
        // Remove everything except digits
        int p = 0;
        while (p < text.length()) {
            char ch = text.charAt(p);
            if (!Character.isDigit(ch)) {
                text.delete(p, p + 1);
            } else {
                p++;
            }
        }
        // Now only digits are remaining
        String allDigitString = text.toString();

        int totalDigitCount = allDigitString.length();

        if (totalDigitCount == 0
                || (totalDigitCount > 10 && !allDigitString.startsWith("1"))
                || totalDigitCount > 11) {
            // May be the total length of input length is greater than the
            // expected value so we'll remove all formatting
            text.clear();
            text.append(allDigitString);
            return allDigitString;
        }
        int alreadyPlacedDigitCount = 0;
        // Only '1' is remaining and user pressed backspace and so we clear
        // the edit text.
        if (allDigitString.equals("1") && clearFlag) {
            text.clear();
            clearFlag = false;
            return "";
        }
        if (allDigitString.startsWith("1")) {
            formattedString.append("1 ");
            alreadyPlacedDigitCount++;
        }
        // The first 3 numbers beyond '1' must be enclosed in brackets "()"
        if (totalDigitCount - alreadyPlacedDigitCount > 3) {
            formattedString.append("("
                    + allDigitString.substring(alreadyPlacedDigitCount,
                            alreadyPlacedDigitCount + 3) + ") ");
            alreadyPlacedDigitCount += 3;
        }
        // There must be a '-' inserted after the next 3 numbers
        if (totalDigitCount - alreadyPlacedDigitCount > 3) {
            formattedString.append(allDigitString.substring(
                    alreadyPlacedDigitCount, alreadyPlacedDigitCount + 3)
                    + "-");
            alreadyPlacedDigitCount += 3;
        }
        // All the required formatting is done so we'll just copy the
        // remaining digits.
        if (totalDigitCount > alreadyPlacedDigitCount) {
            formattedString.append(allDigitString
                    .substring(alreadyPlacedDigitCount));
        }

        text.clear();
        text.append(formattedString.toString());
        return formattedString.toString();
    }

}

Calling other function in the same controller?

Yes. Problem is in wrong notation. Use:

$this->sendRequest($uri)

Instead. Or

self::staticMethod()

for static methods. Also read this for getting idea of OOP - http://www.php.net/manual/en/language.oop5.basic.php

Count elements with jQuery

The best way would be to use .each()

var num = 0;

$('.className').each(function(){
    num++;
});

Data binding to SelectedItem in a WPF Treeview

My requirement was for PRISM-MVVM based solution where a TreeView was needed and the bound object is of type Collection<> and hence needs HierarchicalDataTemplate. The default BindableSelectedItemBehavior wont be able to identify the child TreeViewItem. To make it to work in this scenario.

public class BindableSelectedItemBehavior : Behavior<TreeView>
{
    #region SelectedItem Property

    public object SelectedItem
    {
        get { return (object)GetValue(SelectedItemProperty); }
        set { SetValue(SelectedItemProperty, value); }
    }

    public static readonly DependencyProperty SelectedItemProperty =
        DependencyProperty.Register("SelectedItem", typeof(object), typeof(BindableSelectedItemBehavior), new UIPropertyMetadata(null, OnSelectedItemChanged));

    private static void OnSelectedItemChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        var behavior = sender as BindableSelectedItemBehavior;
        if (behavior == null) return;
        var tree = behavior.AssociatedObject;
        if (tree == null) return;
        if (e.NewValue == null)
            foreach (var item in tree.Items.OfType<TreeViewItem>())
                item.SetValue(TreeViewItem.IsSelectedProperty, false);
        var treeViewItem = e.NewValue as TreeViewItem;
        if (treeViewItem != null)
            treeViewItem.SetValue(TreeViewItem.IsSelectedProperty, true);
        else
        {
            var itemsHostProperty = tree.GetType().GetProperty("ItemsHost", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
            if (itemsHostProperty == null) return;
            var itemsHost = itemsHostProperty.GetValue(tree, null) as Panel;
            if (itemsHost == null) return;
            foreach (var item in itemsHost.Children.OfType<TreeViewItem>())
            {
                if (WalkTreeViewItem(item, e.NewValue)) 
                    break;
            }
        }
    }

    public static bool WalkTreeViewItem(TreeViewItem treeViewItem, object selectedValue)
    {
        if (treeViewItem.DataContext == selectedValue)
        {
            treeViewItem.SetValue(TreeViewItem.IsSelectedProperty, true);
            treeViewItem.Focus();
            return true;
        }
        var itemsHostProperty = treeViewItem.GetType().GetProperty("ItemsHost", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
        if (itemsHostProperty == null) return false;
        var itemsHost = itemsHostProperty.GetValue(treeViewItem, null) as Panel;
        if (itemsHost == null) return false;
        foreach (var item in itemsHost.Children.OfType<TreeViewItem>())
        {
            if (WalkTreeViewItem(item, selectedValue))
                break;
        }
        return false;
    }
    #endregion

    protected override void OnAttached()
    {
        base.OnAttached();
        this.AssociatedObject.SelectedItemChanged += OnTreeViewSelectedItemChanged;
    }

    protected override void OnDetaching()
    {
        base.OnDetaching();
        if (this.AssociatedObject != null)
        {
            this.AssociatedObject.SelectedItemChanged -= OnTreeViewSelectedItemChanged;
        }
    }

    private void OnTreeViewSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
    {
        this.SelectedItem = e.NewValue;
    }
}

This enables to iterate through all the elements irrespective of the level.

How do I change TextView Value inside Java Code?

First we need to find a Button:

Button mButton = (Button) findViewById(R.id.my_button);

After that, you must implement View.OnClickListener and there you should find the TextView and execute the method setText:

mButton.setOnClickListener(new View.OnClickListener {
    public void onClick(View v) {
        final TextView mTextView = (TextView) findViewById(R.id.my_text_view);
        mTextView.setText("Some Text");
    }
});

How to check postgres user and password?

You may change the pg_hba.conf and then reload the postgresql. something in the pg_hba.conf may be like below:

# "local" is for Unix domain socket connections only
local   all             all                                     trust
# IPv4 local connections:
host    all             all             127.0.0.1/32            trust

then you change your user to postgresql, you may login successfully.

su postgresql

Copying the cell value preserving the formatting from one cell to another in excel using VBA

I prefer to avoid using select

     With sheets("sheetname").range("I10") 
          .PasteSpecial Paste:=xlPasteValues, _
                  Operation:=xlNone, _
                  SkipBlanks:=False, _
                  Transpose:=False
          .PasteSpecial Paste:=xlPasteFormats, _
                  Operation:=xlNone, _
                  SkipBlanks:=False, _
                  Transpose:=False
          .font.color = sheets("sheetname").range("F10").font.color
      End With
      sheets("sheetname").range("I10:J10").merge

Determine project root from a running node.js application

the easiest way to get the global root (assuming you use NPM to run your node.js app 'npm start', etc)

var appRoot = process.env.PWD;

If you want to cross-verify the above

Say you want to cross-check process.env.PWD with the settings of you node.js application. if you want some runtime tests to check the validity of process.env.PWD, you can cross-check it with this code (that I wrote which seems to work well). You can cross-check the name of the last folder in appRoot with the npm_package_name in your package.json file, for example:

    var path = require('path');

    var globalRoot = __dirname; //(you may have to do some substring processing if the first script you run is not in the project root, since __dirname refers to the directory that the file is in for which __dirname is called in.)

    //compare the last directory in the globalRoot path to the name of the project in your package.json file
    var folders = globalRoot.split(path.sep);
    var packageName = folders[folders.length-1];
    var pwd = process.env.PWD;
    var npmPackageName = process.env.npm_package_name;
    if(packageName !== npmPackageName){
        throw new Error('Failed check for runtime string equality between globalRoot-bottommost directory and npm_package_name.');
    }
    if(globalRoot !== pwd){
        throw new Error('Failed check for runtime string equality between globalRoot and process.env.PWD.');
    }

you can also use this NPM module: require('app-root-path') which works very well for this purpose

How do I list all remote branches in Git 1.7+?

git branch -a | grep remotes/*

onchange event for input type="number"

I had same problem and I solved using this code

HTML

<span id="current"></span><br>
<input type="number" id="n" value="5" step=".5" />

You can add just 3 first lines the others parts is optional.

$('#n').on('change paste', function () {
    $("#current").html($(this).val())   
});
// here when click on spinner to change value, call trigger change
$(".input-group-btn-vertical").click(function () {
   $("#n").trigger("change");
});
// you can use this to block characters non numeric
$("#n").keydown(function (e) {
    // Allow: backspace, delete, tab, escape, enter and .
    if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 || (e.keyCode === 65 && e.ctrlKey === true) || (e.keyCode >= 35 && e.keyCode <= 40)) 
           return;

    if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) 
       e.preventDefault();
});

Example here : http://jsfiddle.net/XezmB/1303/

Is there a way to continue broken scp (secure copy) command process in Linux?

This is all you need.

 rsync -e ssh file host:/directory/.

How to bring back "Browser mode" in IE11?

Microsoft has a tool just for this purpose: Microsoft Expression Web. There's a free version with a bunch of FrontPage/Dreamweaver-like garbage that nobody wants. What's important is that it has a great browser testing feature. I'm running Windows 8.1 Pro (final release, not preview) with Internet Explorer 11. I get these local browsers:

  • Internet Explorer 6
  • Internet Explorer 7
  • Internet Explorer 11 /!\ Unsupported Version (can't use it; big whoop, I have the browser)

Then I get a Remote Browsers (Beta) option. I'm supposed to sign up with a valid e-mail, but there's an error communicating with the server. Oh well.

Firefox used to be supported, but I don't see it now. Might be hiding.

I can compare side-by-side between browser versions. I can also compare with an image, or apparently, a PSD file (no idea how well that works). InDesign would be nice, but that's probably asking for too much.

I have the full version of Expression partially installed as well due to Visual Studio Ultimate being on the same computer, so I'd appreciate someone confirming in a comment that my free installation isn't automatically upgrading.

Update: Looks like the online service was discontinued, but local browsers are still supported. You can also download just SuperPreview, without the editor garbage. If you want the full IDE, the latest version is Microsoft Expression Web 4 (Free Version). Here's the official list of supported browsers. IE6 seems to give an error on Windows 8.1, but IE7 works.

Update 2014-12-09: Microsoft has pretty much given up on this. Don't expect it to work well.