Programs & Examples On #Leiningen

Leiningen is a build automation and dependency management tool for Clojure projects

How to properly create composite primary keys - MYSQL

Aside from personal design preferences, there are cases where one wants to make use of composite primary keys. Tables may have two or more fields that provide a unique combination, and not necessarily by way of foreign keys.

As an example, each US state has a set of unique Congressional districts. While many states may individually have a CD-5, there will never be more than one CD-5 in any of the 50 states, and vice versa. Therefore, creating an autonumber field for Massachusetts CD-5 would be redundant.

If the database drives a dynamic web page, writing code to query on a two-field combination could be much simpler than extracting/resubmitting an autonumbered key.

So while I'm not answering the original question, I certainly appreciate Adam's direct answer.

Bootstrap 3 - set height of modal window according to screen size

I am using jquery for this. I mad a function to set desired height to the modal(You can change that according to your requirement). Then I used Modal Shown event to call this function. Remember not to use $("#modal").show() rather use $("#modal").modal('show') otherwise shown.bs.modal will not be fired.

That all I have for this scenario.

_x000D_
_x000D_
var offset=250; //You can set offset accordingly based on your UI_x000D_
function AdjustPopup() _x000D_
{_x000D_
    $(".modal-body").css("height","auto");_x000D_
    if ($(".modal-body:visible").height() > ($(window).height() - offset)) _x000D_
    {_x000D_
        $(".modal-body:visible").css("height", ($(window).height() - offset));_x000D_
    }_x000D_
}_x000D_
//Execute the function on every trigger on show() event._x000D_
$(document).ready(function(){_x000D_
$('.modal').on('shown.bs.modal', function (e) {_x000D_
        AdjustPopup();_x000D_
    });_x000D_
});_x000D_
//Remember to show modal like this_x000D_
$("#MyModal").modal('show');
_x000D_
_x000D_
_x000D_

passing 2 $index values within nested ng-repeat

What about using this syntax (take a look in this plunker). I just discovered this and it's pretty awesome.

ng-repeat="(key,value) in data"

Example:

<div ng-repeat="(indexX,object) in data">
    <div ng-repeat="(indexY,value) in object">
       {{indexX}} - {{indexY}} - {{value}}
    </div>
</div>

With this syntax you can give your own name to $index and differentiate the two indexes.

How to get thread id from a thread pool?

Using Thread.currentThread():

private class MyTask implements Runnable {
    public void run() {
        long threadId = Thread.currentThread().getId();
        logger.debug("Thread # " + threadId + " is doing this task");
    }
}

I can't install intel HAXM

Option 1: Go to Android SDK Folder --> Extra --> Intel and double click on HAXM installer and install it manually.

Option 2: If you do not have latest version of HAXM then you can open sdk manager in android studio and download it.

Option 3: Download HAXM intaller from Intel site. https://software.intel.com/en-us/android/articles/intel-hardware-accelerated-execution-manager

How do I compare a value to a backslash?

Use following code to perform if-else conditioning in python: Here, I am checking the length of the string. If the length is less than 3 then do nothing, if more then 3 then I check the last 3 characters. If last 3 characters are "ing" then I add "ly" at the end otherwise I add "ing" at the end.

Code-

if (len(s)<=3):
    return s
elif s[-3:]=="ing":
    return s+"ly"
else: return s + "ing"

Easy way to concatenate two byte arrays

Most straightforward:

byte[] c = new byte[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);

mongo - couldn't connect to server 127.0.0.1:27017

I had same problem to connect mongodb after install using brew on macOS.

The problem was also mongod.lock but before i had mongodb 3.6 installed and database directory was /usr/local/var/mongodb and it have old files and mongod.lock

Simple i moved my old database files to different folder and removed everything from /usr/local/var/mongodb

Then restarted :

brew services restart mongodb

And it's working fine now.

Python: access class property from string

Extending Alex's answer slightly:

class User:
    def __init__(self):
        self.data = [1,2,3]
        self.other_data = [4,5,6]
    def doSomething(self, source):
        dataSource = getattr(self,source)
        return dataSource

A = User()
print A.doSomething("data")
print A.doSomething("other_data")

will yield:

[1, 2, 3]
[4, 5, 6]

However, personally I don't think that's great style - getattr will let you access any attribute of the instance, including things like the doSomething method itself, or even the __dict__ of the instance. I would suggest that instead you implement a dictionary of data sources, like so:

class User:
    def __init__(self):

        self.data_sources = {
            "data": [1,2,3],
            "other_data":[4,5,6],
        }

    def doSomething(self, source):
        dataSource = self.data_sources[source]
        return dataSource

A = User()

print A.doSomething("data")
print A.doSomething("other_data")

again yielding:

[1, 2, 3]
[4, 5, 6]

Format timedelta to string

import datetime
hours = datetime.timedelta(hours=16, minutes=30)
print((datetime.datetime(1,1,1) + hours).strftime('%H:%M'))

How to validate Google reCAPTCHA v3 on server side?

In the example above. For me, this if($response.success==false) thing does not work. Here is correct PHP code:

$url = 'https://www.google.com/recaptcha/api/siteverify';
$privatekey = "--your_key--";
$response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
$data = json_decode($response);

if (isset($data->success) AND $data->success==true) {
            // everything is ok!
} else {
            // spam
}

How to add AUTO_INCREMENT to an existing column?

if you have FK constraints and you don't want to remove the constraint from the table. use "index" instead of primary. then you will be able to alter it's type to auto increment

How to set up subdomains on IIS 7

As DotNetMensch said but you DO NOT need to add another site in IIS as this can also cause further problems and make things more complicated because you then have a website within a website so the file paths, masterpage paths and web.config paths may need changing. You just need to edit teh bindings of the existing site and add the new subdomain there.

So:

  1. Add sub-domain to DNS records. My host (RackSpace) uses a web portal to do this so you just log in and go to Network->Domains(DNS)->Actions->Create Zone, and enter your subdomain as mysubdomain.domain.com etc, leave the other settings as default

  2. Go to your domain in IIS, right-click->Edit Bindings->Add, and add your new subdomain leaving everything else the same e.g. mysubdomain.domain.com

You may need to wait 5-10 mins for the DNS records to update but that's all you need.

Find the number of downloads for a particular app in apple appstore

found a paper at: http://papers.ssrn.com/sol3/papers.cfm?abstract_id=1924044 that suggests a formula to calculate the downloads:

d_iPad=13,516*rank^(-0.903)
d_iPhone=52,958*rank^(-0.944)

What is a deadlock?

A classic and very simple program for understanding Deadlock situation :-

public class Lazy {

    private static boolean initialized = false;

    static {
        Thread t = new Thread(new Runnable() {
            public void run() {
                initialized = true;
            }
        });

        t.start();

        try {
            t.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        System.out.println(initialized);
    }
}

When the main thread invokes Lazy.main, it checks whether the class Lazy has been initialized and begins to initialize the class. The main thread now sets initialized to false , creates and starts a background thread whose run method sets initialized to true , and waits for the background thread to complete.

This time, the class is currently being initialized by another thread. Under these circumstances, the current thread, which is the background thread, waits on the Class object until initialization is complete. Unfortunately, the thread that is doing the initialization, the main thread, is waiting for the background thread to complete. Because the two threads are now waiting for each other, the program is DEADLOCKED.

React-Native: Module AppRegistry is not a registered callable module

If you are using windows machine you need to do cd android then ./gradlew clean then run react-native run-android

What are the lesser known but useful data structures?

XOR Linked List uses two XOR'd pointers to lessen the storage requirements for doubly-linked list. Kind of obscure but neat!

How to implement a lock in JavaScript

I've had success mutex-promise.

I agree with other answers that you might not need locking in your case. But it's not true that one never needs locking in Javascript. You need mutual exclusivity when accessing external resources that do not handle concurrency.

Sending mass email using PHP

You can use swiftmailer for it. By using batch process.

<?php
    $message = Swift_Message::newInstance()
      ->setSubject('Let\'s get together today.')
      ->setFrom(array('[email protected]' => 'From Me'))
      ->setBody('Here is the message itself')
      ->addPart('<b>Test message being sent!!</b>', 'text/html');

    $data = mysql_query('SELECT first, last, email FROM users WHERE is_active=1') or die(mysql_error());
    while($row = mysql_fetch_assoc($data))
    {
       $message->addTo($row['email'], $row['first'] . ' ' . $row['last']);
    }

    $message->batchSend();
?>

Typescript Date Type?

Typescript recognizes the Date interface out of the box - just like you would with a number, string, or custom type. So Just use:

myDate : Date;

C# LINQ select from list

Execute the GetEventIdsByEventDate() method and save the results in a variable, and then you can use the .Contains() method

Reading rather large json files in Python

The issue here is that JSON, as a format, is generally parsed in full and then handled in-memory, which for such a large amount of data is clearly problematic.

The solution to this is to work with the data as a stream - reading part of the file, working with it, and then repeating.

The best option appears to be using something like ijson - a module that will work with JSON as a stream, rather than as a block file.

Edit: Also worth a look - kashif's comment about json-streamer and Henrik Heino's comment about bigjson.

Inheritance and init method in Python

In the first situation, Num2 is extending the class Num and since you are not redefining the special method named __init__() in Num2, it gets inherited from Num.

When a class defines an __init__() method, class instantiation automatically invokes __init__() for the newly-created class instance.

In the second situation, since you are redefining __init__() in Num2 you need to explicitly call the one in the super class (Num) if you want to extend its behavior.

class Num2(Num):
    def __init__(self,num):
        Num.__init__(self,num)
        self.n2 = num*2

convert php date to mysql format

Where you have a posted date in format dd/mm/yyyy, use the below:

$date = explode('/', $_POST['posted_date']);
$new_date = $date[2].'-'.$date[1].'-'.$date[0];

If you have it in mm/dd/yyyy, just change the second line:

$new_date = $date[2].'-'.$date[0].'-'.$date[1];

Insert and set value with max()+1 problems

This is select come insert sequel.

I am trying to get serial_no maximum +1 value and its giving correct value.

SELECT MAX(serial_no)+1 into @var FROM sample.kettle;
Insert into kettle(serial_no,name,age,salary) values (@var,'aaa',23,2000);

Android Studio - Device is connected but 'offline'

Step 1: Turn off USB DEBUGGING in Developer Options

Step 2: Remove USB Cable

Step 3: Turn on USB Debugging(This rests USB Configurations)

Step 4: on Command Prompt enter adb kill-server and then adb start-server

Step 5: Connect the USB Cable

Step 6: Check Devices connected in Run in Android Studio(you should be able to see your device listed)

Step 7: If you want to continue running using the cable this would be good enough

(If you want to do Wireless Debugging continue with below step)

Step 8: type adb tcpip 5555. If no error is displayed remove USB Cable

Step 9: Look up IP Address of your phone from About abd then type adb connect xxx.vvv.b.n(your phone's IP)

Step 10: Check in Devices in Android Studio again and you shud see you r device in List of devices. If yes,

insert data from one table to another in mysql

It wont work like this.

When you try to insert the row using a query all values should be there in query.

With the above problem you want to insert magazine_subscription_id, subscription_name, magazine_id, status in select query you have magazine_subscription_id, subscription_name, magazine_id, status 1 it is not possible.

If you want to insert either you need to insert using query of direct values

How to move the cursor word by word in the OS X Terminal

Under iterm2's Preferences > Profile > Keys, you click the + below Key Mappings and record a new shortcut. For Action, select Send Escape Sequence and type b or f for backwards and forwards respectively.

When I tried to record one for (Ctrl+?), I noticed in the Keyboard Shortcut field that the arrow never showed up. Turns out I had to disable the default mac's System Preferences > Keyboard > Shortcuts > Mission Control shorcuts first to get things to work, as they'll override iterm2's default shortcuts. Should be true for the standard terminal app, too.

Keyboard system preferences

Spring 3.0 - Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/security]

I needed to add an additional Maven dependency:

    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-config</artifactId>
        <version>3.0.1.RELEASE</version>
    </dependency>

LIMIT 10..20 in SQL Server

as you found, this is the preferred sql server method:

SELECT * FROM ( 
  SELECT *, ROW_NUMBER() OVER (ORDER BY name) as row FROM sys.databases 
 ) a WHERE a.row > 5 and a.row <= 10

unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING error

In my case, heredoc caused the issue. There is no problem with PHP version 7.3 up. Howerver, it error with PHP 7.0.33 if you use heredoc with space.

My example code

$rexpenditure = <<<Expenditure
                  <tr>
                      <td>$row->payment_referencenumber</td>
                      <td>$row->payment_requestdate</td>
                      <td>$row->payment_description</td>
                      <td>$row->payment_fundingsource</td>
                      <td>$row->payment_agencyulo</td>
                      <td>$row->payment_agencyproject</td>
                      <td>$$row->payment_disbustment</td>
                      <td>$row->payment_payeename</td>
                      <td>$row->payment_processpayment</td>
                  </tr>
Expenditure;

It will error if there is a space on PHP 7.0.33.

Why can a function modify some arguments as perceived by the caller, but not others?

f doesn't actually alter the value of x (which is always the same reference to an instance of a list). Rather, it alters the contents of this list.

In both cases, a copy of a reference is passed to the function. Inside the function,

  • n gets assigned a new value. Only the reference inside the function is modified, not the one outside it.
  • x does not get assigned a new value: neither the reference inside nor outside the function are modified. Instead, x’s value is modified.

Since both the x inside the function and outside it refer to the same value, both see the modification. By contrast, the n inside the function and outside it refer to different values after n was reassigned inside the function.

Jquery to get SelectedText from dropdown

Get text from a dropdown multiple

var texts = [];
$('#list :selected').each(function(){
    texts.push($(this).text());
});

texts now contains a list of selected text

Form Submit Execute JavaScript Best Practice?

Attach an event handler to the submit event of the form. Make sure it cancels the default action.

Quirks Mode has a guide to event handlers, but you would probably be better off using a library to simplify the code and iron out the differences between browsers. All the major ones (such as YUI and jQuery) include event handling features, and there is a large collection of tiny event libraries.

Here is how you would do it in YUI 3:

<script src="http://yui.yahooapis.com/3.4.1/build/yui/yui-min.js"></script>
<script>
    YUI().use('event', function (Y) {
        Y.one('form').on('submit', function (e) {
            // Whatever else you want to do goes here
            e.preventDefault();
        });
    });
</script>

Make sure that the server will pick up the slack if the JavaScript fails for any reason.

Android: how to get the current day of the week (Monday, etc...) in the user's language?

//selected date from calender
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy"); //Date and time
String currentDate = sdf.format(myCalendar.getTime());

//selcted_day name
SimpleDateFormat sdf_ = new SimpleDateFormat("EEEE");
String dayofweek=sdf_.format(myCalendar.getTime());
current_date.setText(currentDate);
lbl_current_date.setText(dayofweek);

Log.e("dayname", dayofweek);

Print raw string from variable? (not getting the answers)

Replace back-slash with forward-slash using one of the below:

  • re.sub(r"\", "/", x)
  • re.sub(r"\", "/", x)

Change color inside strings.xml

<string name="hello_world"><font fgcolor="red">Hello</font>
    </font fgcolor="blue">world!</font></string>

But note that this only works on a relatively short list of built-in colors: aqua, black, blue, fuchsia, green, grey, lime, maroon, navy, olive, purple, red, silver, teal, white, and yellow. See https://stackoverflow.com/a/31655150/338479 for a way to do it with arbitrary colors.

Excel is not updating cells, options > formula > workbook calculation set to automatic

the ctrl alt f9 , is the temporary solution , going to options-formula-auto calculate is the right way, that option turned manual, because some shortcut key on being pressed by mistake turns automatic to manual

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

Getting "method not valid without suitable object" error when trying to make a HTTP request in VBA?

I had to use Debug.print instead of Print, which works in the Immediate window.

Sub SendEmail()
    'Dim objHTTP As New MSXML2.XMLHTTP
    'Set objHTTP = New MSXML2.XMLHTTP60
    'Dim objHTTP As New MSXML2.XMLHTTP60
    Dim objHTTP As New WinHttp.WinHttpRequest
    'Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
    'Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
    URL = "http://localhost:8888/rest/mail/send"
    objHTTP.Open "POST", URL, False
    objHTTP.setRequestHeader "Content-Type", "application/json"
    objHTTP.send ("{""key"":null,""from"":""[email protected]"",""to"":null,""cc"":null,""bcc"":null,""date"":null,""subject"":""My Subject"",""body"":null,""attachments"":null}")
    Debug.Print objHTTP.Status
    Debug.Print objHTTP.ResponseText

End Sub

How to kill a process in MacOS?

in the spotlight, search for Activity Monitor. You can force fully remove any application from here.

enter image description here

document.getElementById(id).focus() is not working for firefox or chrome

Are you trying to reference the element before the DOM has finished loading?

Your code should go in body load (or another function that should execute when the DOM has loaded, such as $(document).ready() in jQuery)

body.onload = function() { 
    // your onchange event handler should be in here too   
    var mnumber = document.getElementById('mobileno').value; 
    if(mnumber.length >=10) {
        alert("Mobile Number Should be in 10 digits only"); 
        document.getElementById('mobileno').value = ""; 
        document.getElementById('mobileno').focus(); 
        return false; 
    }    
}

jQuery form input select by id

You can just target the id directly:

var value = $('#b').val();

If you have more than one element with that id in the same page, it won't work properly anyway. You have to make sure that the id is unique.

If you actually are using the code for different pages, and only want to find the element on those pages where the id:s are nested, you can just use the descendant operator, i.e. space:

var value = $('#a #b').val();

Local storage in Angular 2

To store in LocalStorage :

window.localStorage.setItem(key, data);

To remove an item from LocalStorage :

window.localStorage.removeItem(key);

To get an item from LocalStorage :

window.localStorage.getItem(key);

You can only store a string in LocalStorage; if you have an object, first you have to convert it to string like the following:

window.localStorage.setItem(key, JSON.stringify(obj));

And when you want to get an object from LocalStorage :

const result=JSON.parse(window.localStorage.getItem(key));

All Tips above are the same for SessionStorage.

You can use the following service to work on SessionStorage and LocalStorage. All methods in the service :

getSession(key: string): any
setSession(key: string, value: any): void
removeSession(key: string): void
removeAllSessions(): void
getLocal(key: string): any
setLocal(key: string, value: any): void
removeLocal(key: string): void 
removeAllLocals(): void

Inject this service in your components, services and ...; Do not forget to register the service in your core module.

import { Injectable } from '@angular/core';

@Injectable()
export class BrowserStorageService {

  getSession(key: string): any {
    const data = window.sessionStorage.getItem(key);
    if (data) {
      return JSON.parse(data);
    } else {
      return null;
    }
  }

  setSession(key: string, value: any): void {
    const data = value === undefined ? '' : JSON.stringify(value);
    window.sessionStorage.setItem(key, data);
  }

  removeSession(key: string): void {
    window.sessionStorage.removeItem(key);
  }

  removeAllSessions(): void {
    for (const key in window.sessionStorage) {
      if (window.sessionStorage.hasOwnProperty(key)) {
        this.removeSession(key);
      }
    }
  }

  getLocal(key: string): any {
    const data = window.localStorage.getItem(key);
    if (data) {
      return JSON.parse(data);
    } else {
      return null;
    }
  }

  setLocal(key: string, value: any): void {
    const data = value === undefined ? '' : JSON.stringify(value);
    window.localStorage.setItem(key, data);
  }

  removeLocal(key: string): void {
    window.localStorage.removeItem(key);
  }

  removeAllLocals(): void {
    for (const key in window.localStorage) {
      if (window.localStorage.hasOwnProperty(key)) {
        this.removeLocal(key);
      }
    }
  }
}

Find duplicate records in a table using SQL Server

Try this instead

SELECT MAX(shoppername), COUNT(*) AS cnt
FROM dbo.sales
GROUP BY CHECKSUM(*)
HAVING COUNT(*) > 1

Read about the CHECKSUM function first, as there can be duplicates.

adding directory to sys.path /PYTHONPATH

When running a Python script from Powershell under Windows, this should work:

$pathToSourceRoot = "C:/Users/Steve/YourCode"
$env:PYTHONPATH = "$($pathToSourceRoot);$($pathToSourceRoot)/subdirs_if_required"

# Now run the actual script
python your_script.py

URL encoding in Android

I'm going to add one suggestion here. You can do this which avoids having to get any external libraries.

Give this a try:

String urlStr = "http://abc.dev.domain.com/0007AC/ads/800x480 15sec h.264.mp4";
URL url = new URL(urlStr);
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
url = uri.toURL();

You can see that in this particular URL, I need to have those spaces encoded so that I can use it for a request.

This takes advantage of a couple features available to you in Android classes. First, the URL class can break a url into its proper components so there is no need for you to do any string search/replace work. Secondly, this approach takes advantage of the URI class feature of properly escaping components when you construct a URI via components rather than from a single string.

The beauty of this approach is that you can take any valid url string and have it work without needing any special knowledge of it yourself.

Reverse a comparator in Java 8

You can also use Comparator.comparing(Function, Comparator)
It is convenient to chain comparators when necessary, e.g.:

Comparator<SomeEntity> ENTITY_COMPARATOR = comparing(SomeEntity::getProperty1, reverseOrder())
        .thenComparingInt(SomeEntity::getProperty2)
        .thenComparing(SomeEntity::getProperty3, reverseOrder());

List columns with indexes in PostgreSQL

I don't think this version exists on this thread yet: it provides both the list of column names along with the ddl for the index.

CREATE OR REPLACE VIEW V_TABLE_INDEXES AS

SELECT
     n.nspname  as "schema"
    ,t.relname  as "table"
    ,c.relname  as "index"
    ,i.indisunique AS "is_unique"
    ,array_to_string(array_agg(a.attname), ', ') as "columns"
    ,pg_get_indexdef(i.indexrelid) as "ddl"
FROM pg_catalog.pg_class c
    JOIN pg_catalog.pg_namespace n ON n.oid        = c.relnamespace
    JOIN pg_catalog.pg_index i ON i.indexrelid = c.oid
    JOIN pg_catalog.pg_class t ON i.indrelid   = t.oid
    JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(i.indkey)
WHERE c.relkind = 'i'
      and n.nspname not in ('pg_catalog', 'pg_toast')
      and pg_catalog.pg_table_is_visible(c.oid)
GROUP BY
    n.nspname
    ,t.relname
    ,c.relname
    ,i.indisunique
    ,i.indexrelid
ORDER BY
    n.nspname
    ,t.relname
    ,c.relname;

I found that indexes using functions don't link to column names, so occasionally you find an index listing e.g. one column name when in fact is uses 3.

Example:

CREATE INDEX ui1 ON table1 (coalesce(col1,''),coalesce(col2,''),col3)

The query returns only 'col3' as a column on the index, but the DDL shows the full set of columns used in the index.

Put Excel-VBA code in module or sheet?

Definitely in Modules.

  • Sheets can be deleted, copied and moved with surprising results.
  • You can't call code in sheet "code-behind" from other modules without fully qualifying the reference. This will lead to coupling of the sheet and the code in other modules/sheets.
  • Modules can be exported and imported into other workbooks, and put under version control
  • Code in split logically into modules (data access, utilities, spreadsheet formatting etc.) can be reused as units, and are easier to manage if your macros get large.

Since the tooling is so poor in primitive systems such as Excel VBA, best practices, obsessive code hygiene and religious following of conventions are important, especially if you're trying to do anything remotely complex with it.

This article explains the intended usages of different types of code containers. It doesn't qualify why these distinctions should be made, but I believe most developers trying to develop serious applications on the Excel platform follow them.

There's also a list of VBA coding conventions I've found helpful, although they're not directly related to Excel VBA. Please ignore the crazy naming conventions they have on that site, it's all crazy hungarian.

How do I reference a cell range from one worksheet to another using excel formulas?

If you wish to concatenate multiple cells from different sheets, and you also want to add a delimiter between the content of each cell, the most straightforward way to do it is:

=CONCATENATE(Sheet1!A4, ", ", Sheet2!A5)

This works only for a limited number of referenced cells, but it is fast if you have only of few of these cells that you want to map.

How to change package name in android studio?

Another good method is: First create a new package with the desired name by right clicking on the java folder -> new -> package.

Then, select and drag all your classes to the new package. Android Studio will refactor the package name everywhere.

Finally, delete the old package.

or Look into this post

codes for ADD,EDIT,DELETE,SEARCH in vb2010

A good resource start off point would be MSDN as your looking into a microsoft product

What is a segmentation fault?

To be honest, as other posters have mentioned, Wikipedia has a very good article on this so have a look there. This type of error is very common and often called other things such as Access Violation or General Protection Fault.

They are no different in C, C++ or any other language that allows pointers. These kinds of errors are usually caused by pointers that are

  1. Used before being properly initialised
  2. Used after the memory they point to has been realloced or deleted.
  3. Used in an indexed array where the index is outside of the array bounds. This is generally only when you're doing pointer math on traditional arrays or c-strings, not STL / Boost based collections (in C++.)

How to Convert Boolean to String

You use strval() or (string) to convert to string in PHP. However, that does not convert boolean into the actual spelling of "true" or "false" so you must do that by yourself. Here's an example function:

function strbool($value)
{
    return $value ? 'true' : 'false';
}
echo strbool(false); // "false"
echo strbool(true); // "true"

Create a 3D matrix

If you want to define a 3D matrix containing all zeros, you write

A = zeros(8,4,20);

All ones uses ones, all NaN's uses NaN, all false uses false instead of zeros.

If you have an existing 2D matrix, you can assign an element in the "3rd dimension" and the matrix is augmented to contain the new element. All other new matrix elements that have to be added to do that are set to zero.

For example

B = magic(3); %# creates a 3x3 magic square
B(2,1,2) = 1; %# and you have a 3x3x2 array

Can't open file 'svn/repo/db/txn-current-lock': Permission denied

for example on debian

sudo gpasswd -a svn-admin www-data
sudo chgrp -R www-data svn/
sudo chmod -R g=rwsx svn/

Can typescript export a function?

If you are using this for Angular, then export a function via a named export. Such as:

function someFunc(){}

export { someFunc as someFuncName }

otherwise, Angular will complain that object is not a function.

How to make a background 20% transparent on Android

We can make transparent in dis way also.

White color code - FFFFFF

20% white - #33FFFFFF

20% — 33

70% white - #B3FFFFFF

70% — B3

All teh hex value from 100% to 0%

100% — FF, 99% — FC, 98% — FA, 97% — F7, 96% — F5, 95% — F2, 94% — F0, 93% — ED, 92% — EB, 91% — E8, 90% — E6, 89% — E3, 88% — E0, 87% — DE, 86% — DB, 85% — D9, 84% — D6, 83% — D4, 82% — D1, 81% — CF, 80% — CC, 79% — C9, 78% — C7, 77% — C4, 76% — C2, 75% — BF, 74% — BD, 73% — BA, 72% — B8, 71% — B5, 70% — B3, 69% — B0, 68% — AD, 67% — AB, 66% — A8, 65% — A6, 64% — A3, 63% — A1, 62% — 9E, 61% — 9C, 60% — 99, 59% — 96, 58% — 94, 57% — 91, 56% — 8F, 55% — 8C, 54% — 8A, 53% — 87, 52% — 85, 51% — 82, 50% — 80, 49% — 7D, 48% — 7A, 47% — 78, 46% — 75, 45% — 73, 44% — 70, 43% — 6E, 42% — 6B, 41% — 69, 40% — 66, 39% — 63, 38% — 61, 37% — 5E, 36% — 5C, 35% — 59, 34% — 57, 33% — 54, 32% — 52, 31% — 4F, 30% — 4D, 29% — 4A, 28% — 47, 27% — 45, 26% — 42, 25% — 40, 24% — 3D, 23% — 3B, 22% — 38, 21% — 36, 20% — 33, 19% — 30, 18% — 2E, 17% — 2B, 16% — 29, 15% — 26, 14% — 24, 13% — 21, 12% — 1F, 11% — 1C, 10% — 1A, 9% — 17, 8% — 14, 7% — 12, 6% — 0F, 5% — 0D, 4% — 0A, 3% — 08, 2% — 05, 1% — 03, 0% — 00

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays

I had the same error because I have mapped the HTTP response like this:

this.http.get(url).map(res => res.json);

Note how I accidentally called .json like a variable and not like a method.

Changing it to:

this.http.get(url).map(res => res.json());

did the trick.

Web Application Problems (web.config errors) HTTP 500.19 with IIS7.5 and ASP.NET v2

Another way of getting 500.19 errot for no apparent reason is - missing directories and/or broken permissions on them.

In case of this question, I believe the question asks about full IIS version. I assume this because of this line:

Config File         \\?\E:\wwwroot\web.config

IIS installer usually creates the wwwroot for you and that's the default root folder for all websites and mount point for virtual directories. It always exists, so no problem, you usually don't care much about that.

Since web.config files are hierarchical, you can put there a master web.config file and have some root settings there, and all sites will inherit it. IIS checks if that file exists and tries to load it.

However, first fun part:

This directory will exists if you have IIS properly installed. If it does not exist, you will get 500-class error. However, if you play with file/directory permissions, especially 'advanced' ones, you can actually accidentally deny IIS service account from scanning/reading the contents of this directory. If IIS is unable to check if that wwwroot\web.config exists, or if it exists and IIS is not able to open&read it - bam - 500-class error.

However, for full IIS it is very unlikely. Developers/Admins working with full IIS are usually reluctant regarding playing with wwwroot so it usually stays properly configured.

However, on IIS Express..

Usually, IIS Express "just works". Often, developers using IIS Express often are not aware how much internally it resembles the real IIS.

You can easily stumble upon the fact that IIS Express has its own applicationHost.config file and VS creates and manages it for you (correctly, to some extent) and that sort of an eye-opener telling you that it's not that simple and point-and-click as it seems at first.

Aside from that config file, VisualStudio also creates an empty directory structure under your Documents folder. If I remember correctly, IIS Express considers these folders to be the root directories of your website(s) upon which virtual directories with your code are mounted.

Later, just like IIS, when IIS Express starts up, it expects these folders to exist and checks for root web.config files there. The site web.config files. Almost always, these web.config files are missing - and that's OK because you don't want them - you have your **application web.config", they are placed with rest of the content in a virtual directories.

Now, the second fun part is: IIS Express expects that empty directories. They can be empty, but they need to exist. If they don't exist - you will get a 500-class error telling you that "web.config" file at that path cannot be accessed.

The first time I bumped into this problem was when I was clearing my hard drive. I found that 'documents\websites' folder, full of trash, I recognized several year-old projects I no longer work on, all empty, not a single file, so I deleted it all. A week later - bam - I cannot run/debug any of the sites I was working at the moment. Error was 500.19, cannot read config file.

So, if you use IIS Express and see 500-class error telling about reading configuration, carefully check the error message and read all paths mentioned. If you see anything like:

c:\users\user\documents\visual studio 2013\projects\WebProject1\WebProject1.web\web.config
c:\users\zeshan.munir\documents\visual studio 2015\projects\WebProject1\WebProject1.web\web.config
c:\users\zeshan.munir\documents\visual studio 2017\projects\WebProject1\WebProject1.web\web.config
etc..

Go there exactly where the error indicates, ensure that these folders exist, ensure that IIS worker account can traverse and read them, and if you notice that anything's wrong, maybe it will be that.

BTW. In VisualStudio, on ProjectProperties/Web there's a button "Create Virtual Directory". It essentially does this very thing, so you may try it first, but IIRC it can also somethimes clear/overwrite/swap configuration sections in applicationHost.config file, so be careful with that button if you have any custom setups there.

Add Expires headers

The easiest way to add these headers is a .htaccess file that adds some configuration to your server. If the assets are hosted on a server that you don't control, there's nothing you can do about it.

Note that some hosting providers will not let you use .htaccess files, so check their terms if it doesn't seem to work.

The HTML5Boilerplate project has an excellent .htaccess file that covers the necessary settings. See the relevant part of the file at their Github repository

These are the important bits

# ----------------------------------------------------------------------
# Expires headers (for better cache control)
# ----------------------------------------------------------------------

# These are pretty far-future expires headers.
# They assume you control versioning with filename-based cache busting
# Additionally, consider that outdated proxies may miscache
# www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/

# If you don't use filenames to version, lower the CSS and JS to something like
# "access plus 1 week".

<IfModule mod_expires.c>
  ExpiresActive on

# Your document html
  ExpiresByType text/html "access plus 0 seconds"

# Media: images, video, audio
  ExpiresByType audio/ogg "access plus 1 month"
  ExpiresByType image/gif "access plus 1 month"
  ExpiresByType image/jpeg "access plus 1 month"
  ExpiresByType image/png "access plus 1 month"
  ExpiresByType video/mp4 "access plus 1 month"
  ExpiresByType video/ogg "access plus 1 month"
  ExpiresByType video/webm "access plus 1 month"

# CSS and JavaScript
  ExpiresByType application/javascript "access plus 1 year"
  ExpiresByType text/css "access plus 1 year"
</IfModule>

They have documented what that file does, the most important bit is that you need to rename your CSS and Javascript files whenever they change, because your visitor's browsers will not check them again for a year, once they are cached.

change html input type by JS?

Yes, you can even change it by triggering an event

<input type='text' name='pass'  onclick="(this.type='password')" />


<input type="text" placeholder="date" onfocusin="(this.type='date')" onfocusout="(this.type='text')">

Why Would I Ever Need to Use C# Nested Classes

There is good uses of public nested members too...

Nested classes have access to the private members of the outer class. So a scenario where this is the right way would be when creating a Comparer (ie. implementing the IComparer interface).

In this example, the FirstNameComparer has access to the private _firstName member, which it wouldn't if the class was a separate class...

public class Person
{
    private string _firstName;
    private string _lastName;
    private DateTime _birthday;

    //...
    
    public class FirstNameComparer : IComparer<Person>
    {
        public int Compare(Person x, Person y)
        {
            return x._firstName.CompareTo(y._firstName);
        }
    }
}

How to get the exact local time of client?

You can also make your own nodeJS endpoint, publish it with something like heroku, and access it

require("http").createServer(function (q,r) {
    r.setHeader("accees-control-allow-origin","*")
    r.end(Date.now())
}).listen(process.env.PORT || 80)

Then just access it on JS

fetch ("http://someGerokuApp")
.then(r=>r.text)
. then (r=>console.log(r))

This will still be relative to whatever computer the node app is hosted on, but perhaps you can get the location somehow and provide different endpoints fit the other timezones based on the current one (for example if the server happens to be in California then for a new York timezone just add 1000*60*60*3 milliseconds to Date.now() to add 3 hours)

For simplicity, if it's possible to get the location from the server and send it as a response header, you can just do the calculations for the different time zones in the client side

In fact using heroku they allow you to specify a region that it should be deployed at https://devcenter.heroku.com/articles/regions#specifying-a-region you can use this as reference..

EDIT just realized the timezone is in the date string itself, can just pay the whole thing as a header to be read by the client

require("http").createServer(function (q,r) {
    var d= new Date()
    r.setHeader("accees-control-allow-origin","*")
    r.setHeader("zman", d.toString())
    r.end(d.getTime())
}).listen(process.env.PORT || 80)

Place cursor at the end of text in EditText

enter image description here

Hello Try This

 <EditText
       android:id="@+id/edt_text"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:text="Hello World!"
       android:cursorVisible="true"/>

EditText editText = findViewById(R.id.editText); editText.setSelection(editText.getText().length()); // End pointCursor

Getting all types in a namespace via reflection

You won't be able to get all types in a namespace, because a namespace can bridge multiple assemblies, but you can get all classes in an assembly and check to see if they belong to that namespace.

Assembly.GetTypes() works on the local assembly, or you can load an assembly first then call GetTypes() on it.

Replace an element into a specific position of a vector

vec1[i] = vec2[i]

will set the value of vec1[i] to the value of vec2[i]. Nothing is inserted. Your second approach is almost correct. Instead of +i+1 you need just +i

v1.insert(v1.begin()+i, v2[i])

mysql count group by having

Maybe

SELECT count(*) FROM (
    SELECT COUNT(*) FROM Movies GROUP BY ID HAVING count(Genre) = 4
) AS the_count_total

although that would not be the sum of all the movies, just how many have 4 genre's.

So maybe you want

SELECT sum(
    SELECT COUNT(*) FROM Movies GROUP BY ID having Count(Genre) = 4
) as the_sum_total

Why must wait() always be in synchronized block

@Rollerball is right. The wait() is called, so that the thread can wait for some condition to occur when this wait() call happens, the thread is forced to give up its lock.
To give up something, you need to own it first. Thread needs to own the lock first. Hence the need to call it inside a synchronized method/block.

Yes, I do agree with all the above answers regarding the potential damages/inconsistencies if you did not check the condition within synchronized method/block. However as @shrini1000 has pointed out, just calling wait() within synchronized block will not avert this inconsistency from happening.

Here is a nice read..

What is the difference between <jsp:include page = ... > and <%@ include file = ... >?

Java Revisited

  1. Resource included by include directive is loaded during jsp translation time, while resource included by include action is loaded during request time.
  2. Any change on included resource will not be visible in case of include directive until jsp file compiles again. While in case of include action, any change in included resource will be visible in next request.
  3. Include directive is static import, while include action is dynamic import
  4. Include directive uses file attribute to specify resource to be included while include action use page attribute for same purpose.

Arduino IDE can't find ESP8266WiFi.h file

For those who are having trouble with fatal error: ESP8266WiFi.h: No such file or directory, you can install the package manually.

  1. Download the Arduino ESP8266 core from here https://github.com/esp8266/Arduino
  2. Go into library from the downloaded core and grab ESP8266WiFi.
  3. Drag that into your local Arduino/library folder. This can be found by going into preferences and looking at your Sketchbook location

You may still need to have the http://arduino.esp8266.com/stable/package_esp8266com_index.json package installed beforehand, however.

Edit: That wasn't the full issue, you need to make sure you have the correct ESP8266 Board selected before compiling.

Hope this helps others.

How do you check if a JavaScript Object is a DOM Object?

This could be helpful: isDOM

//-----------------------------------
// Determines if the @obj parameter is a DOM element
function isDOM (obj) {
    // DOM, Level2
    if ("HTMLElement" in window) {
        return (obj && obj instanceof HTMLElement);
    }
    // Older browsers
    return !!(obj && typeof obj === "object" && obj.nodeType === 1 && obj.nodeName);
}

In the code above, we use the double negation operator to get the boolean value of the object passed as argument, this way we ensure that each expression evaluated in the conditional statement be boolean, taking advantage of the Short-Circuit Evaluation, thus the function returns true or false

Python's most efficient way to choose longest string in list?

What should happen if there are more than 1 longest string (think '12', and '01')?

Try that to get the longest element

max_length,longest_element = max([(len(x),x) for x in ('a','b','aa')])

And then regular foreach

for st in mylist:
    if len(st)==max_length:...

Could pandas use column as index?

Yes, with set_index you can make Locality your row index.

data.set_index('Locality', inplace=True)

If inplace=True is not provided, set_index returns the modified dataframe as a result.

Example:

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

> df
     Locality    2005    2006
0  ABBOTSFORD  427000  448000
1  ABERFELDIE  534000  600000

> df.set_index('Locality', inplace=True)
> df
              2005    2006
Locality                  
ABBOTSFORD  427000  448000
ABERFELDIE  534000  600000

> df.loc['ABBOTSFORD']
2005    427000
2006    448000
Name: ABBOTSFORD, dtype: int64

> df.loc['ABBOTSFORD'][2005]
427000

> df.loc['ABBOTSFORD'].values
array([427000, 448000])

> df.loc['ABBOTSFORD'].tolist()
[427000, 448000]

input file appears to be a text format dump. Please use psql

if you use pg_dump with -Fp to backup in plain text format, use following command:

cat db.txt | psql dbname

to copy all data to your database with name dbname

Invalid length for a Base-64 char array

I'm not Reputable enough to upvote or comment yet, but LukeH's answer was spot on for me.

As AES encryption is the standard to use now, it produces a base64 string (at least all the encrypt/decrypt implementations I've seen). This string has a length in multiples of 4 (string.length % 4 = 0)

The strings I was getting contained + and = on the beginning or end, and when you just concatenate that into a URL's querystring, it will look right (for instance, in an email you generate), but when the the link is followed and the .NET page recieves it and puts it into this.Page.Request.QueryString, those special characters will be gone and your string length will not be in a multiple of 4.

As the are special characters at the FRONT of the string (ex: +), as well as = at the end, you can't just add some = to make up the difference as you are altering the cypher text in a way that doesn't match what was actually in the original querystring.

So, wrapping the cypher text with HttpUtility.URLEncode (not HtmlEncode) transforms the non-alphanumeric characters in a way that ensures .NET parses them back into their original state when it is intepreted into the querystring collection.

The good thing is, we only need to do the URLEncode when generating the querystring for the URL. On the incoming side, it's automatically translated back into the original string value.

Here's some example code

string cryptostring = MyAESEncrypt(MySecretString);
string URL = WebFunctions.ToAbsoluteUrl("~/ResetPassword.aspx?RPC=" + HttpUtility.UrlEncode(cryptostring));

How to change folder with git bash?

To move from c drive to other drive(D or E)use this command----->

cd "your path" Now hit enter. Check your path using $pwd. Your path has been change from one directory to other.

Ex---> cd "D:\WEB_DEV\HTML_CSS_projects\TouristVisitors_LandingPage". note - this is my path, your path should be different.

How to properly stop the Thread in Java?

Using Thread.interrupt() is a perfectly acceptable way of doing this. In fact, it's probably preferrable to a flag as suggested above. The reason being that if you're in an interruptable blocking call (like Thread.sleep or using java.nio Channel operations), you'll actually be able to break out of those right away.

If you use a flag, you have to wait for the blocking operation to finish and then you can check your flag. In some cases you have to do this anyway, such as using standard InputStream/OutputStream which are not interruptable.

In that case, when a thread is interrupted, it will not interrupt the IO, however, you can easily do this routinely in your code (and you should do this at strategic points where you can safely stop and cleanup)

if (Thread.currentThread().isInterrupted()) {
  // cleanup and stop execution
  // for example a break in a loop
}

Like I said, the main advantage to Thread.interrupt() is that you can immediately break out of interruptable calls, which you can't do with the flag approach.

Convert JS date time to MySQL datetime

JS time value for MySQL

var datetime = new Date().toLocaleString();

OR

const DATE_FORMATER = require( 'dateformat' );
var datetime = DATE_FORMATER( new Date(), "yyyy-mm-dd HH:MM:ss" );

OR

const MOMENT= require( 'moment' );
let datetime = MOMENT().format( 'YYYY-MM-DD  HH:mm:ss.000' );

you can send this in params its will work.

Use dynamic variable names in JavaScript

It is always better to use create a namespace and declare a variable in it instead of adding it to the global object. We can also create a function to get and set the value

See the below code snippet:

//creating a namespace in which all the variables will be defined.
var myObjects={};

//function that will set the name property in the myObjects namespace
function setName(val){
  myObjects.Name=val;
}

//function that will return the name property in the myObjects namespace
function getName(){
  return myObjects.Name;
}

//now we can use it like:
  setName("kevin");
  var x = getName();
  var y = x;
  console.log(y)  //"kevin"
  var z = "y";
  console.log(z); //"y"
  console.log(eval(z)); //"kevin"

In this similar way, we can declare and use multiple variables. Although this will increase the line of code but the code will be more robust and less error-prone.

Firing events on CSS class changes in jQuery

Whenever you change a class in your script, you could use a trigger to raise your own event.

$(this).addClass('someClass');
$(mySelector).trigger('cssClassChanged')
....
$(otherSelector).bind('cssClassChanged', data, function(){ do stuff });

but otherwise, no, there's no baked-in way to fire an event when a class changes. change() only fires after focus leaves an input whose input has been altered.

_x000D_
_x000D_
$(function() {_x000D_
  var button = $('.clickme')_x000D_
      , box = $('.box')_x000D_
  ;_x000D_
  _x000D_
  button.on('click', function() { _x000D_
    box.removeClass('box');_x000D_
    $(document).trigger('buttonClick');_x000D_
  });_x000D_
            _x000D_
  $(document).on('buttonClick', function() {_x000D_
    box.text('Clicked!');_x000D_
  });_x000D_
});
_x000D_
.box { background-color: red; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="box">Hi</div>_x000D_
<button class="clickme">Click me</button>
_x000D_
_x000D_
_x000D_

More info on jQuery Triggers

Drawing Circle with OpenGL

I have done it using the following code,

glBegin(GL.GL_LINE_LOOP);
     for(int i =0; i <= 300; i++){
         double angle = 2 * Math.PI * i / 300;
         double x = Math.cos(angle);
         double y = Math.sin(angle);
         gl.glVertex2d(x,y);
     }
glEnd();

Extension gd is missing from your system - laravel composer Update

I have installed php7, I did the following to solve exactly the same error

sudo apt-get install php7.0-gd
sudo apt-get install php7.0-intl
sudo apt-get install php7.0-xsl

"Non-static method cannot be referenced from a static context" error

You need to correctly separate static data from instance data. In your code, onLoan and setLoanItem() are instance members. If you want to reference/call them you must do so via an instance. So you either want

public void loanItem() {
    this.media.setLoanItem("Yes");
}

or

public void loanItem(Media object) {
    object.setLoanItem("Yes");
}

depending on how you want to pass that instance around.

How to add link to flash banner

If you have a flash FLA file that shows the FLV movie you can add a button inside the FLA file. This button can be given an action to load the URL.

on (release) {
  getURL("http://someurl/");
}

To make the button transparent you can place a square inside it that is moved to the hit-area frame of the button.

I think it would go too far to explain into depth with pictures how to go about in stackoverflow.

Html table with button on each row

Put a single listener on the table. When it gets a click from an input with a button that has a name of "edit" and value "edit", change its value to "modify". Get rid of the input's id (they aren't used for anything here), or make them all unique.

<script type="text/javascript">

function handleClick(evt) {
  var node = evt.target || evt.srcElement;
  if (node.name == 'edit') {
    node.value = "Modify";
  }
}

</script>

<table id="table1" border="1" onclick="handleClick(event);">
    <thead>
      <tr>
          <th>Select
    </thead>
    <tbody>
       <tr> 
           <td>
               <form name="f1" action="#" >
                <input id="edit1" type="submit" name="edit" value="Edit">
               </form>
       <tr> 
           <td>
               <form name="f2" action="#" >
                <input id="edit2" type="submit" name="edit" value="Edit">
               </form>
       <tr> 
           <td>
               <form name="f3" action="#" >
                <input id="edit3" type="submit" name="edit" value="Edit">
               </form>

   </tbody>
</table>

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

Edit Jan 6, 2017

I needed to keep double quotes in my configuration file so double escaping double quotes with sed helps:

render_template() {
  eval "echo \"$(sed 's/\"/\\\\"/g' $1)\""
}

I can't think of keeping trailing new lines, but empty lines in between are kept.


Although it is an old topic, IMO I found out more elegant solution here: http://pempek.net/articles/2013/07/08/bash-sh-as-template-engine/

#!/bin/sh

# render a template configuration file
# expand variables + preserve formatting
render_template() {
  eval "echo \"$(cat $1)\""
}

user="Gregory"
render_template /path/to/template.txt > path/to/configuration_file

All credits to Grégory Pakosz.

What does [object Object] mean?

[object Object] is the default toString representation of an object in javascript.

If you want to know the properties of your object, just foreach over it like this:

for(var property in obj) {
    alert(property + "=" + obj[property]);
}

In your particular case, you are getting a jQuery object. Try doing this instead:

$('#senddvd').click(function ()
{
   alert('hello');
   var a=whichIsVisible();
   alert(whichIsVisible().attr("id"));
});

This should alert the id of the visible element.

Gradle - Move a folder from ABC to XYZ

Your task declaration is incorrectly combining the Copy task type and project.copy method, resulting in a task that has nothing to copy and thus never runs. Besides, Copy isn't the right choice for renaming a directory. There is no Gradle API for renaming, but a bit of Groovy code (leveraging Java's File API) will do. Assuming Project1 is the project directory:

task renABCToXYZ {     doLast {         file("ABC").renameTo(file("XYZ"))     } } 

Looking at the bigger picture, it's probably better to add the renaming logic (i.e. the doLast task action) to the task that produces ABC.

How to assign a heredoc value to a variable in Bash?

There is still no solution that preserves newlines.

This is not true - you're probably just being misled by the behaviour of echo:

echo $VAR # strips newlines

echo "$VAR" # preserves newlines

Force LF eol in git repo and working copy

To force LF line endings for all text files, you can create .gitattributes file in top-level of your repository with the following lines (change as desired):

# Ensure all C and PHP files use LF.
*.c         eol=lf
*.php       eol=lf

which ensures that all files that Git considers to be text files have normalized (LF) line endings in the repository (normally core.eol configuration controls which one do you have by default).

Based on the new attribute settings, any text files containing CRLFs should be normalized by Git. If this won't happen automatically, you can refresh a repository manually after changing line endings, so you can re-scan and commit the working directory by the following steps (given clean working directory):

$ echo "* text=auto" >> .gitattributes
$ rm .git/index     # Remove the index to force Git to
$ git reset         # re-scan the working directory
$ git status        # Show files that will be normalized
$ git add -u
$ git add .gitattributes
$ git commit -m "Introduce end-of-line normalization"

or as per GitHub docs:

git add . -u
git commit -m "Saving files before refreshing line endings"
git rm --cached -r . # Remove every file from Git's index.
git reset --hard # Rewrite the Git index to pick up all the new line endings.
git add . # Add all your changed files back, and prepare them for a commit.
git commit -m "Normalize all the line endings" # Commit the changes to your repository.

See also: @Charles Bailey post.

In addition, if you would like to exclude any files to not being treated as a text, unset their text attribute, e.g.

manual.pdf      -text

Or mark it explicitly as binary:

# Denote all files that are truly binary and should not be modified.
*.png binary
*.jpg binary

To see some more advanced git normalization file, check .gitattributes at Drupal core:

# Drupal git normalization
# @see https://www.kernel.org/pub/software/scm/git/docs/gitattributes.html
# @see https://www.drupal.org/node/1542048

# Normally these settings would be done with macro attributes for improved
# readability and easier maintenance. However macros can only be defined at the
# repository root directory. Drupal avoids making any assumptions about where it
# is installed.

# Define text file attributes.
# - Treat them as text.
# - Ensure no CRLF line-endings, neither on checkout nor on checkin.
# - Detect whitespace errors.
#   - Exposed by default in `git diff --color` on the CLI.
#   - Validate with `git diff --check`.
#   - Deny applying with `git apply --whitespace=error-all`.
#   - Fix automatically with `git apply --whitespace=fix`.

*.config  text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.css     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.dist    text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.engine  text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.html    text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=html
*.inc     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.install text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.js      text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.json    text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.lock    text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.map     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.md      text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.module  text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.php     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.po      text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.profile text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.script  text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.sh      text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.sql     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.svg     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.theme   text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.twig    text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.txt     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.xml     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.yml     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2

# Define binary file attributes.
# - Do not treat them as text.
# - Include binary diff in patches instead of "binary files differ."
*.eot     -text diff
*.exe     -text diff
*.gif     -text diff
*.gz      -text diff
*.ico     -text diff
*.jpeg    -text diff
*.jpg     -text diff
*.otf     -text diff
*.phar    -text diff
*.png     -text diff
*.svgz    -text diff
*.ttf     -text diff
*.woff    -text diff
*.woff2   -text diff

See also:

How to declare a global variable in php?

$GLOBALS[] is the right solution, but since we're talking about alternatives, a function can also do this job easily:

function capital() {
    return my_var() . ' is the capital of Italy';
}

function my_var() {
    return 'Rome';
}

Change PictureBox's image to image from my resources?

If you loaded the resource using the visual studio UI, then you should be able to do this:

picturebox.Image = project.Properties.Resources.imgfromresource

Login to Microsoft SQL Server Error: 18456

first see the details of the error if "state" is "1" Ensure the database is set for both SQL and Windows authentication under SQL server / Properties / Security.

for other state see the above answers ....

Last Run Date on a Stored Procedure in SQL Server

Oh, be careful now! All that glitters is NOT gold! All of the “stats” dm views and functions have a problem for this type of thing. They only work against what is in cache and the lifetime of what is in cache can be measure in minutes. If you were to use such a thing to determine which SPs are candidates for being dropped, you could be in for a world of hurt when you delete SPs that were used just minutes ago.

The following excerpts are from Books Online for the given dm views…

sys.dm_exec_procedure_stats Returns aggregate performance statistics for cached stored procedures. The view contains one row per stored procedure, and the lifetime of the row is as long as the stored procedure remains cached. When a stored procedure is removed from the cache, the corresponding row is eliminated from this view.

sys.dm_exec_query_stats The view contains one row per query statement within the cached plan, and the lifetime of the rows are tied to the plan itself. When a plan is removed from the cache, the corresponding rows are eliminated from this view.

Determining Referer in PHP

Using $_SERVER['HTTP_REFERER']

The address of the page (if any) which referred the user agent to the current page. This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.

if (!empty($_SERVER['HTTP_REFERER'])) {
    header("Location: " . $_SERVER['HTTP_REFERER']);
} else {
    header("Location: index.php");
}
exit;

Convert a 1D array to a 2D array in numpy

convert a 1-dimensional array into a 2-dimensional array by adding new axis.

a=np.array([10,20,30,40,50,60])

b=a[:,np.newaxis]--it will convert it to two dimension.

Capture close event on Bootstrap Modal

Though is answered in another stack overflow question Bind a function to Twitter Bootstrap Modal Close but for visual feel here is more detailed answer.

Source: http://getbootstrap.com/javascript/#modals-events

Python script to copy text to clipboard

I try this clipboard 0.0.4 and it works well.

https://pypi.python.org/pypi/clipboard/0.0.4

import clipboard
clipboard.copy("abc")  # now the clipboard content will be string "abc"
text = clipboard.paste()  # text will have the content of clipboard

Is it possible to use global variables in Rust?

You can use static variables fairly easily as long as they are thread-local.

The downside is that the object will not be visible to other threads your program might spawn. The upside is that unlike truly global state, it is entirely safe and is not a pain to use - true global state is a massive pain in any language. Here's an example:

extern mod sqlite;

use std::cell::RefCell;

thread_local!(static ODB: RefCell<sqlite::database::Database> = RefCell::new(sqlite::open("test.db"));

fn main() {
    ODB.with(|odb_cell| {
        let odb = odb_cell.borrow_mut();
        // code that uses odb goes here
    });
}

Here we create a thread-local static variable and then use it in a function. Note that it is static and immutable; this means that the address at which it resides is immutable, but thanks to RefCell the value itself will be mutable.

Unlike regular static, in thread-local!(static ...) you can create pretty much arbitrary objects, including those that require heap allocations for initialization such as Vec, HashMap and others.

If you cannot initialize the value right away, e.g. it depends on user input, you may also have to throw Option in there, in which case accessing it gets a bit unwieldy:

extern mod sqlite;

use std::cell::RefCell;

thread_local!(static ODB: RefCell<Option<sqlite::database::Database>> = RefCell::New(None));

fn main() {
    ODB.with(|odb_cell| {
        // assumes the value has already been initialized, panics otherwise
        let odb = odb_cell.borrow_mut().as_mut().unwrap();
        // code that uses odb goes here
    });
}

Show a popup/message box from a Windows batch file

You can invoke dll function from user32.dll i think Something like

Rundll32.exe user32.dll, MessageBox (0, "text", "titleText", {extra flags for like topmost messagebox e.t.c})

Typing it from my Phone, don't judge me... otherwise i would link the extra flags.

$http get parameters does not work

The 2nd parameter in the get call is a config object. You want something like this:

$http
    .get('accept.php', {
        params: {
            source: link,
            category_id: category
        }
     })
     .success(function (data,status) {
          $scope.info_show = data
     });

See the Arguments section of http://docs.angularjs.org/api/ng.$http for more detail

Windows shell command to get the full path to the current directory?

@echo off
for /f "usebackq tokens=*" %%x in (`chdir`) do set var=%%x
echo The currenct directory is: %var%

But, of course, gmaran23's answer is the much easier one.

Getting session value in javascript

protected void Page_Load(object sender, EventArgs e)
    {
        Session["MyTest"] = "abcd";

        String csname = "OnSubmitScript";
        Type cstype = this.GetType();

        // Get a ClientScriptManager reference from the Page class.
        ClientScriptManager cs = Page.ClientScript;

        // Check to see if the OnSubmit statement is already registered.
        if (!cs.IsOnSubmitStatementRegistered(cstype, csname))
        {
            string cstext = " document.getElementById(\"TextBox1\").value = getMyvalSession()  ; ";
            cs.RegisterOnSubmitStatement(cstype, csname, cstext);
        }

        if (TextBox1.Text.Equals("")) { }
        else {
              Session["MyTest"] = TextBox1.Text;
        }

    }


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">

    <script language=javascript type="text/javascript">
        function getMyvalSession() {

             var txt = "efgh";
             var ff = '<%=Session["MyTest"] %>' + txt;
             return ff ;
        }
    </script>

</head>
<body>

    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"  AutoPostBack=true ></asp:TextBox>
     <input type="submit"  value="Submit" />
    </div>
    </form>
</body>
</html>

How do I find the length (or dimensions, size) of a numpy matrix in python?

shape is a property of both numpy ndarray's and matrices.

A.shape

will return a tuple (m, n), where m is the number of rows, and n is the number of columns.

In fact, the numpy matrix object is built on top of the ndarray object, one of numpy's two fundamental objects (along with a universal function object), so it inherits from ndarray

Core dump file is not generated

Remember if you are starting the server from a service, it will start a different bash session so the ulimit won't be effective there. Try to put this in your script itself:

ulimit -c unlimited

HashSet vs LinkedHashSet

I suggest you to use LinkedHashSet most of the time, because it has better performance overall):

  1. Predictable iteration order LinkedHashSet (Oracle)
  2. LinkedHashSet is more expensive for insertions than HashSet;
  3. In general slightly better performance than HashMap, because the most of the time we use Set structures for iterating.

Performance tests:

------------- TreeSet -------------
 size       add  contains   iterate
   10       746       173        89
  100       501       264        68
 1000       714       410        69
10000      1975       552        69
------------- HashSet -------------
 size       add  contains   iterate
   10       308        91        94
  100       178        75        73
 1000       216       110        72
10000       711       215       100
---------- LinkedHashSet ----------
 size       add  contains   iterate
   10       350        65        83
  100       270        74        55
 1000       303       111        54
10000      1615       256        58

You can see source test page here: The Final Performance Testing Example

How to sort List of objects by some property

We can use the Comparator.comparing() method to sort a list based on an object's property.

class SortTest{
    public static void main(String[] args) {
        ArrayList<ActiveAlarm> activeAlarms = new ArrayList<>(){{
            add(new ActiveAlarm("Alarm 1", 5, 10));
            add(new ActiveAlarm("Alarm 2", 2, 12));
            add(new ActiveAlarm("Alarm 3", 0, 8));
        }};

        /* I sort the arraylist here using the getter methods */
        activeAlarms.sort(Comparator.comparing(ActiveAlarm::getTimeStarted)
                .thenComparing(ActiveAlarm::getTimeEnded));

        System.out.println(activeAlarms);
    }
}

Note that before doing it, you'll have to define at least the getter methods of the properties you want to base your sort on.

public class ActiveAlarm {
    public long timeStarted;
    public long timeEnded;
    private String name = "";
    private String description = "";
    private String event;
    private boolean live = false;

    public ActiveAlarm(String name, long timeStarted, long timeEnded) {
        this.name = name;
        this.timeStarted = timeStarted;
        this.timeEnded = timeEnded;
    }

    public long getTimeStarted() {
        return timeStarted;
    }

    public long getTimeEnded() {
        return timeEnded;
    }

    @Override
    public String toString() {
        return name;
    }
}

Output:

[Alarm 3, Alarm 2, Alarm 1]

Changing user agent on urllib2.urlopen

there are two properties of urllib.URLopener() namely:
addheaders = [('User-Agent', 'Python-urllib/1.17'), ('Accept', '*/*')] and
version = 'Python-urllib/1.17'.
To fool the website you need to changes both of these values to an accepted User-Agent. for e.g.
Chrome browser : 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.149 Safari/537.36'
Google bot : 'Googlebot/2.1'
like this

import urllib
page_extractor=urllib.URLopener()  
page_extractor.addheaders = [('User-Agent', 'Googlebot/2.1'), ('Accept', '*/*')]  
page_extractor.version = 'Googlebot/2.1'
page_extractor.retrieve(<url>, <file_path>)

changing just one property does not work because the website marks it as a suspicious request.

Copy or rsync command

if you are using cp doesn't save existing files when copying folders of the same name. Lets say you have this folders:

/myFolder
  someTextFile.txt

/someOtherFolder
  /myFolder
    wellHelloThere.txt

Then you copy one over the other:

cp /someOtherFolder/myFolder /myFolder

result:

/myFolder
  wellHelloThere.txt

This is at least what happens on macOS and I wanted to preserve the diff files so I used rsync.

get the titles of all open windows

you should use the EnumWindow API.

there are plenty of examples on how to use it from C#, I found something here:

Get Application's Window Handles

Issue with EnumWindows

Running shell command and capturing the output

In all officially maintained versions of Python, the simplest approach is to use the subprocess.check_output function:

>>> subprocess.check_output(['ls', '-l'])
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'

check_output runs a single program that takes only arguments as input.1 It returns the result exactly as printed to stdout. If you need to write input to stdin, skip ahead to the run or Popen sections. If you want to execute complex shell commands, see the note on shell=True at the end of this answer.

The check_output function works in all officially maintained versions of Python. But for more recent versions, a more flexible approach is available.

Modern versions of Python (3.5 or higher): run

If you're using Python 3.5+, and do not need backwards compatibility, the new run function is recommended by the official documentation for most tasks. It provides a very general, high-level API for the subprocess module. To capture the output of a program, pass the subprocess.PIPE flag to the stdout keyword argument. Then access the stdout attribute of the returned CompletedProcess object:

>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'

The return value is a bytes object, so if you want a proper string, you'll need to decode it. Assuming the called process returns a UTF-8-encoded string:

>>> result.stdout.decode('utf-8')
'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'

This can all be compressed to a one-liner if desired:

>>> subprocess.run(['ls', '-l'], stdout=subprocess.PIPE).stdout.decode('utf-8')
'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'

If you want to pass input to the process's stdin, you can pass a bytes object to the input keyword argument:

>>> cmd = ['awk', 'length($0) > 5']
>>> ip = 'foo\nfoofoo\n'.encode('utf-8')
>>> result = subprocess.run(cmd, stdout=subprocess.PIPE, input=ip)
>>> result.stdout.decode('utf-8')
'foofoo\n'

You can capture errors by passing stderr=subprocess.PIPE (capture to result.stderr) or stderr=subprocess.STDOUT (capture to result.stdout along with regular output). If you want run to throw an exception when the process returns a nonzero exit code, you can pass check=True. (Or you can check the returncode attribute of result above.) When security is not a concern, you can also run more complex shell commands by passing shell=True as described at the end of this answer.

Later versions of Python streamline the above further. In Python 3.7+, the above one-liner can be spelled like this:

>>> subprocess.run(['ls', '-l'], capture_output=True, text=True).stdout
'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'

Using run this way adds just a bit of complexity, compared to the old way of doing things. But now you can do almost anything you need to do with the run function alone.

Older versions of Python (3-3.4): more about check_output

If you are using an older version of Python, or need modest backwards compatibility, you can use the check_output function as briefly described above. It has been available since Python 2.7.

subprocess.check_output(*popenargs, **kwargs)  

It takes takes the same arguments as Popen (see below), and returns a string containing the program's output. The beginning of this answer has a more detailed usage example. In Python 3.5+, check_output is equivalent to executing run with check=True and stdout=PIPE, and returning just the stdout attribute.

You can pass stderr=subprocess.STDOUT to ensure that error messages are included in the returned output. When security is not a concern, you can also run more complex shell commands by passing shell=True as described at the end of this answer.

If you need to pipe from stderr or pass input to the process, check_output won't be up to the task. See the Popen examples below in that case.

Complex applications and legacy versions of Python (2.6 and below): Popen

If you need deep backwards compatibility, or if you need more sophisticated functionality than check_output or run provide, you'll have to work directly with Popen objects, which encapsulate the low-level API for subprocesses.

The Popen constructor accepts either a single command without arguments, or a list containing a command as its first item, followed by any number of arguments, each as a separate item in the list. shlex.split can help parse strings into appropriately formatted lists. Popen objects also accept a host of different arguments for process IO management and low-level configuration.

To send input and capture output, communicate is almost always the preferred method. As in:

output = subprocess.Popen(["mycmd", "myarg"], 
                          stdout=subprocess.PIPE).communicate()[0]

Or

>>> import subprocess
>>> p = subprocess.Popen(['ls', '-a'], stdout=subprocess.PIPE, 
...                                    stderr=subprocess.PIPE)
>>> out, err = p.communicate()
>>> print out
.
..
foo

If you set stdin=PIPE, communicate also allows you to pass data to the process via stdin:

>>> cmd = ['awk', 'length($0) > 5']
>>> p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
...                           stderr=subprocess.PIPE,
...                           stdin=subprocess.PIPE)
>>> out, err = p.communicate('foo\nfoofoo\n')
>>> print out
foofoo

Note Aaron Hall's answer, which indicates that on some systems, you may need to set stdout, stderr, and stdin all to PIPE (or DEVNULL) to get communicate to work at all.

In some rare cases, you may need complex, real-time output capturing. Vartec's answer suggests a way forward, but methods other than communicate are prone to deadlocks if not used carefully.

As with all the above functions, when security is not a concern, you can run more complex shell commands by passing shell=True.

Notes

1. Running shell commands: the shell=True argument

Normally, each call to run, check_output, or the Popen constructor executes a single program. That means no fancy bash-style pipes. If you want to run complex shell commands, you can pass shell=True, which all three functions support. For example:

>>> subprocess.check_output('cat books/* | wc', shell=True, text=True)
' 1299377 17005208 101299376\n'

However, doing this raises security concerns. If you're doing anything more than light scripting, you might be better off calling each process separately, and passing the output from each as an input to the next, via

run(cmd, [stdout=etc...], input=other_output)

Or

Popen(cmd, [stdout=etc...]).communicate(other_output)

The temptation to directly connect pipes is strong; resist it. Otherwise, you'll likely see deadlocks or have to do hacky things like this.

Using Colormaps to set color of line in matplotlib

I thought it would be beneficial to include what I consider to be a more simple method using numpy's linspace coupled with matplotlib's cm-type object. It's possible that the above solution is for an older version. I am using the python 3.4.3, matplotlib 1.4.3, and numpy 1.9.3., and my solution is as follows.

import matplotlib.pyplot as plt

from matplotlib import cm
from numpy import linspace

start = 0.0
stop = 1.0
number_of_lines= 1000
cm_subsection = linspace(start, stop, number_of_lines) 

colors = [ cm.jet(x) for x in cm_subsection ]

for i, color in enumerate(colors):
    plt.axhline(i, color=color)

plt.ylabel('Line Number')
plt.show()

This results in 1000 uniquely-colored lines that span the entire cm.jet colormap as pictured below. If you run this script you'll find that you can zoom in on the individual lines.

cm.jet between 0.0 and 1.0 with 1000 graduations

Now say I want my 1000 line colors to just span the greenish portion between lines 400 to 600. I simply change my start and stop values to 0.4 and 0.6 and this results in using only 20% of the cm.jet color map between 0.4 and 0.6.

enter image description here

So in a one line summary you can create a list of rgba colors from a matplotlib.cm colormap accordingly:

colors = [ cm.jet(x) for x in linspace(start, stop, number_of_lines) ]

In this case I use the commonly invoked map named jet but you can find the complete list of colormaps available in your matplotlib version by invoking:

>>> from matplotlib import cm
>>> dir(cm)

dyld: Library not loaded: @rpath/libswiftCore.dylib

The most easy and easy to ignored way : clean and rebuild.

This solved the issue after tried the answers above and did not worked.

Eclipse count lines of code

I created a Eclipse plugin, which can count the lines of source code. It support Kotlin, Java, Java Script, JSP, XML, C/C++, C#, and many other file types.

Please take a look at it. Any feedback would be appreciated!

the git-hub repository is here

Basic Python client socket example

Here is the simplest python socket example.

Server side:

import socket

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind(('localhost', 8089))
serversocket.listen(5) # become a server socket, maximum 5 connections

while True:
    connection, address = serversocket.accept()
    buf = connection.recv(64)
    if len(buf) > 0:
        print buf
        break

Client Side:

import socket

clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket.connect(('localhost', 8089))
clientsocket.send('hello')
  • First run the SocketServer.py, and make sure the server is ready to listen/receive sth
  • Then the client send info to the server;
  • After the server received sth, it terminates

Maximum size of an Array in Javascript

Like @maerics said, your target machine and browser will determine performance.

But for some real world numbers, on my 2017 enterprise Chromebook, running the operation:

console.time();
Array(x).fill(0).filter(x => x < 6).length
console.timeEnd();
  • x=5e4 takes 16ms, good enough for 60fps
  • x=4e6 takes 250ms, which is noticeable but not a big deal
  • x=3e7 takes 1300ms, which is pretty bad
  • x=4e7 takes 11000ms and allocates an extra 2.5GB of memory

So around 30 million elements is a hard upper limit, because the javascript VM falls off a cliff at 40 million elements and will probably crash the process.


EDIT: In the code above, I'm actually filling the array with elements and looping over them, simulating the minimum of what an app might want to do with an array. If you just run Array(2**32-1) you're creating a sparse array that's closer to an empty JavaScript object with a length, like {length: 4294967295}. If you actually tried to use all those 4 billion elements, you'll definitely your user's javascript process.

Including all the jars in a directory within the Java classpath

I have multiple jars in a folder. The below command worked for me in JDK1.8 to include all jars present in the folder. Please note that to include in quotes if you have a space in the classpath

Windows

Compiling: javac -classpath "C:\My Jars\sdk\lib\*" c:\programs\MyProgram.java

Running: java -classpath "C:\My Jars\sdk\lib\*;c:\programs" MyProgram

Linux

Compiling: javac -classpath "/home/guestuser/My Jars/sdk/lib/*" MyProgram.java

Running: java -classpath "/home/guestuser/My Jars/sdk/lib/*:/home/guestuser/programs" MyProgram

Using Laravel Homestead: 'no input file specified'

I had such problem. I reviewed Homestead.yaml file and all files and all of the settings were correct. My problem removed after the following steps.

1-If you are in vagrant@homestead:~$ command line, type exit command.

2- Now you must be inside Homestead folder. run this command

vagrant reload --provision

3- run vagrant ssh

Now if you type the related address in your browser it should show the Laravel page.

How to give the background-image path in CSS?

you can also add inline css for adding image as a background as per below example

<div class="item active" style="background-image: url(../../foo.png);">

How to replace captured groups only?

A simplier option is to just capture the digits and replace them.

_x000D_
_x000D_
const name = 'preceding_text_0_following_text';_x000D_
const matcher = /(\d+)/;_x000D_
_x000D_
// Replace with whatever you would like_x000D_
const newName = name.replace(matcher, 'NEW_STUFF');_x000D_
console.log("Full replace", newName);_x000D_
_x000D_
// Perform work on the match and replace using a function_x000D_
// In this case increment it using an arrow function_x000D_
const incrementedName = name.replace(matcher, (match) => ++match);_x000D_
console.log("Increment", incrementedName);
_x000D_
_x000D_
_x000D_

Resources

How to activate an Anaconda environment

I was having the same, a fix seems to have been made in the source.

align 3 images in same row with equal spaces?

The modern approach: flexbox

Simply add the following CSS to the container element (here, the div):

div {
  display: flex;
  justify-content: space-between;
}

_x000D_
_x000D_
div {_x000D_
  display: flex;_x000D_
  justify-content: space-between;_x000D_
}
_x000D_
<div>_x000D_
 <img src="http://placehold.it/100x100" alt=""  /> _x000D_
 <img src="http://placehold.it/100x100" alt=""  />_x000D_
 <img src="http://placehold.it/100x100" alt="" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

The old way (for ancient browsers - prior to flexbox)

Use text-align: justify; on the container element.

Then stretch the content to take up 100% width

MARKUP

<div>
 <img src="http://placehold.it/100x100" alt=""  /> 
 <img src="http://placehold.it/100x100" alt=""  />
 <img src="http://placehold.it/100x100" alt="" />
</div>

CSS

div {
    text-align: justify;
}

div img {
    display: inline-block;
    width: 100px;
    height: 100px;
}

div:after {
    content: '';
    display: inline-block;
    width: 100%;
}

_x000D_
_x000D_
div {_x000D_
    text-align: justify;_x000D_
}_x000D_
_x000D_
div img {_x000D_
    display: inline-block;_x000D_
    width: 100px;_x000D_
    height: 100px;_x000D_
}_x000D_
_x000D_
div:after {_x000D_
    content: '';_x000D_
    display: inline-block;_x000D_
    width: 100%;_x000D_
}
_x000D_
<div>_x000D_
 <img src="http://placehold.it/100x100" alt=""  /> _x000D_
 <img src="http://placehold.it/100x100" alt=""  />_x000D_
 <img src="http://placehold.it/100x100" alt="" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to show soft-keyboard when edittext is focused

I had a similar problem using view animations. So I've put an animation listener to make sure I'd wait for the animation to end before trying to request a keyboard access on the shown edittext.

    bottomUp.setAnimationListener(new Animation.AnimationListener() {
        @Override
        public void onAnimationStart(Animation animation) {
        }

        @Override
        public void onAnimationEnd(Animation animation) {
            if (textToFocus != null) {
                // Position cursor at the end of the text
                textToFocus.setSelection(textToFocus.getText().length());
                // Show keyboard
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.showSoftInput(textToFocus, InputMethodManager.SHOW_IMPLICIT);
            }
        }

        @Override
        public void onAnimationRepeat(Animation animation) {
        }
    });

Trying to git pull with error: cannot open .git/FETCH_HEAD: Permission denied

In my case, I only had read access to the .git/FETCH_HEAD file. I had to do "sudo chmod g+w .git/FETCH_HEAD" in order to be able to do a pull request.

Ruby 'require' error: cannot load such file

I used jruby-1.7.4 to compile my ruby code.

require 'roman-numerals.rb' 

is the code which threw the below error.

LoadError: no such file to load -- roman-numerals
  require at org/jruby/RubyKernel.java:1054
  require at /Users/amanoharan/.rvm/rubies/jruby-1.7.4/lib/ruby/shared/rubygems/custom_require.rb:36
   (root) at /Users/amanoharan/Documents/Aptana Studio 3 Workspace/RubyApplication/RubyApplication1/Ruby2.rb:2

I removed rb from require and gave

require 'roman-numerals' 

It worked fine.

background-size in shorthand background property (CSS3)

You will have to use vendor prefixes to support different browsers and therefore can't use it in shorthand.

body { 
        background: url(images/bg.jpg) no-repeat center center fixed; 
        -webkit-background-size: cover;
        -moz-background-size: cover;
        -o-background-size: cover;
        background-size: cover;
}

EPPlus - Read Excel Table

This is my working version. Note that the resolvers code is not shown but are a spin on my implementation which allows columns to be resolved even though they are named slightly differently in each worksheet.

public static IEnumerable<T> ToArray<T>(this ExcelWorksheet worksheet, List<PropertyNameResolver> resolvers) where T : new()
{

  // List of all the column names
  var header = worksheet.Cells.GroupBy(cell => cell.Start.Row).First();

  // Get the properties from the type your are populating
  var properties = typeof(T).GetProperties().ToList();


  var start = worksheet.Dimension.Start;
  var end = worksheet.Dimension.End;

  // Resulting list
  var list = new List<T>();

  // Iterate the rows starting at row 2 (ie start.Row + 1)
  for (int row = start.Row + 1; row <= end.Row; row++)
  {
    var instance = new T();
    for (int col = start.Column; col <= end.Column; col++)
    {
      object value = worksheet.Cells[row, col].Text;

      // Get the column name zero based (ie col -1)
      var column = (string)header.Skip(col - 1).First().Value;

      // Gets the corresponding property to set
      var property = properties.Property(resolvers, column);

      try
      {
        var propertyName = property.PropertyType.IsGenericType
          ? property.PropertyType.GetGenericArguments().First().FullName
          : property.PropertyType.FullName;


        // Implement setter code as needed. 
        switch (propertyName)
        {
          case "System.String":
            property.SetValue(instance, Convert.ToString(value));
            break;
          case "System.Int32":
            property.SetValue(instance, Convert.ToInt32(value));
            break;
          case "System.DateTime":
            if (DateTime.TryParse((string) value, out var date))
            {
              property.SetValue(instance, date);
            }
            property.SetValue(instance, FromExcelSerialDate(Convert.ToInt32(value)));
            break;
          case "System.Boolean":
            property.SetValue(instance, (int)value == 1);
            break;
        }
      }
      catch (Exception e)
      {
        // instance property is empty because there was a problem.
      }

    } 
    list.Add(instance);
  }
  return list;
}

// Utility function taken from the above post's inline function.
public static DateTime FromExcelSerialDate(int excelDate)
{
  if (excelDate < 1)
    throw new ArgumentException("Excel dates cannot be smaller than 0.");

  var dateOfReference = new DateTime(1900, 1, 1);

  if (excelDate > 60d)
    excelDate = excelDate - 2;
  else
    excelDate = excelDate - 1;
  return dateOfReference.AddDays(excelDate);
}

How do I do a not equal in Django queryset filtering?

You can use Q objects for this. They can be negated with the ~ operator and combined much like normal Python expressions:

from myapp.models import Entry
from django.db.models import Q

Entry.objects.filter(~Q(id=3))

will return all entries except the one(s) with 3 as their ID:

[<Entry: Entry object>, <Entry: Entry object>, <Entry: Entry object>, ...]

How can I zoom an HTML element in Firefox and Opera?

Try this code, this’ll work:

-moz-transform: scale(2);

You can refer to this.

How to fully clean bin and obj folders within Visual Studio?

I store my finished VS projects by saving only source code.

I delete BIN, DEBUG, RELEASE, OBJ, ARM and .vs folders from all projects.

This reduces the size of the project considerably. The project

must be rebuilt when pulled out of storage.

Android studio - Failed to find target android-18

What worked for me in Android Studio (0.8.1):

  1. Right click on project name and open Module Settings
  2. Verify SDK Locations SDK
  3. Verify Gradle and Plugin Versions (Review the error message hints for the proper version to use) Gradke
  4. On the app Module set the Compile SDK Version to android-L (latest)
  5. Set the Build Tools version to largest available value (in my case 20.0.0) Build

These changes via the UI make the equivalent changes represented in other answers but is a better way to proceed because on close, all appropriate files (current and future) will be updated automatically (which is helpful when confronted by the many places where issues can occur).

NB: It is very important to review the Event Log and note that Android Studio provides helpful messages on alternative ways to resolve such issues.

T-sql - determine if value is integer

See whether the below query will help

SELECT *
FROM MY_TABLE
WHERE CHARINDEX('.',MY_FIELD) = 0 AND CHARINDEX(',',MY_FIELD) = 0       
AND ISNUMERIC(MY_FIELD) = 1 AND CONVERT(FLOAT,MY_FIELD) / 2147483647 <= 1

I'm getting the "missing a using directive or assembly reference" and no clue what's going wrong

This problem would be caused by your application missing a reference to an external dll that you are trying to use code from. Usually Visual Studio should give you an idea about which objects that it doesn't know what to do with so that should be a step in the right direction.

You need to look in the solution explorer and right click on project references and then go to add -> and look up the one you need. It's most likely the System.Configuration assembly as most people have pointed out here while should be under the Framework option in the references window. That should resolve your issue.

How to clear the cache in NetBeans

Close NetBeans before deleting the cache.

NetBeans 7.2+, Windows 7

Cache is located in C:\Users\<username>\AppData\Local\NetBeans\Cache\.

Clear the cache using the %USERPROFILE% Windows variable:

del /s /q %USERPROFILE%\AppData\Local\NetBeans\Cache\

If it is set, you can also use the environment variable %LOCALAPPDATA%:

del /s /q %LOCALAPPDATA%\NetBeans\Cache\

NetBeans 7.2+, Linux

Cache is at: ~/.cache/netbeans/${netbeans_version}/index/

Mac OS X

Cache is at: ~/Library/Caches/NetBeans/${netbeans_version}/

See also http://wiki.netbeans.org/FaqWhatIsUserdir.

Help Menu

On Windows, selecting the Help » About menu will display a dialog that contains the following text:

Product Version: NetBeans IDE 8.0.2 (Build 201411181905)
Java: 1.7.0_80; Java HotSpot(TM) 64-Bit Server VM 24.80-b11
Runtime: Java(TM) SE Runtime Environment 1.7.0_80-b15
System: Windows 7 version 6.1 running on amd64; Cp1252; en_CA (nb)
User directory: C:\Users\Username\AppData\Roaming\NetBeans\8.0.2
Cache directory: C:\Users\Username\AppData\Local\NetBeans\Cache\8.0.2

Regardless of operating system, the About dialog will contain the correct path to the cache directory.

Why would anybody use C over C++?

Most of the significant features of c++ somehow involve classes or templates. These are wonderful features except for the way the compiler transforms these into object code. Most compilers use name mangling, and the ones that don't do something at least as messy.

If your system lives on its own, as is the case with many applications, then C++ is a fine choice.

If your system needs to interact with software not neccesarily written in C++ (most frequently in assembler, or Fortran Libraries) then you are in a tight spot. To interact with those kinds of cases, you'll need to disable name mangling for those symbols. this is usually done by declaring those objects extern "C", but then they can't be templates, overloaded functions, or classes. If those are likely to be your applications API, then you'll have to wrap them with helper functions, and keep those functions in sync with the actual implementations.

And in reality, the C++ language provides a standard syntax for features that can be easily implemented in pure C.

In short, the overhead of interoperable C++ is too high for most folks to justify.

How to open Console window in Eclipse?

The "trim stack" is a vertical icon bar that should appear, if it isn't there already, on one side of the main window. Back when this answer was originally written, it was down the left hand side (of which I had a screen shot that unfortunately was uploaded to some image paste bin place and not Stack Overflow, then linked, and has since been lost). Not being much of an eclipse user currently I don't know if this is still the case.

It contains icons for each sub-window that is minimized, so if none of them are minimized, there is no trim stack. Try minimizing the Package Explorer/Navigator window and you should see it appear. You can then click the "Restore" icon (the overlapping squares at the top) in the trim stack to get the window back.

BUT -- and it's not consistent -- sometimes with Eclipse Juno when the window with the Console, etc, is minimized and there is no trim stack, the trim stack doesn't appear and using "Show View" does nothing. The way around that I've found is to minimize some other window, then the trim stack appears and the Console icon (blue & white monitor square) appears. Click that and the Console, etc. appears in a pop-up. Click the Restore icon in that pop-up and it will become part of the main window again.

How to replace space with comma using sed?

If you are talking about sed, this works:

sed -e "s/ /,/g" < a.txt

In vim, use same regex to replace:

s/ /,/g

What is the difference between HAVING and WHERE in SQL?

HAVING is used when you are using an aggregate such as GROUP BY.

SELECT edc_country, COUNT(*)
FROM Ed_Centers
GROUP BY edc_country
HAVING COUNT(*) > 1
ORDER BY edc_country;

Recursive search and replace in text files on Mac and Linux

find . -type f | xargs sed -i '' 's/string1/string2/g'

Refer here for more info.

Download a file from NodeJS Server using Express

For static files like pdfs, Word docs, etc. just use Express's static function in your config:

// Express config
var app = express().configure(function () {
    this.use('/public', express.static('public')); // <-- This right here
});

And then just put all your files inside that 'public' folder, for example:

/public/docs/my_word_doc.docx

And then a regular old link will allow the user to download it:

<a href="public/docs/my_word_doc.docx">My Word Doc</a>

keytool error bash: keytool: command not found

Use

./keytool -genkey -alias mypassword -keyalg RSA

Deleting multiple elements from a list

As a function:

def multi_delete(list_, *args):
    indexes = sorted(list(args), reverse=True)
    for index in indexes:
        del list_[index]
    return list_

Runs in n log(n) time, which should make it the fastest correct solution yet.

Synchronous XMLHttpRequest warning and <script>

Browsers now warn for the use of synchronous XHR. MDN says this was implemented recently:

Starting with Gecko 30.0 (Firefox 30.0 / Thunderbird 30.0 / SeaMonkey 2.27)

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests#Synchronous_request

Here's how the change got implemented in Firefox and Chromium:

As for Chrome people report this started happening somewhere around version 39. I'm not sure how to link a revision/changeset to a particular version of Chrome.

Yes, it happens when jQuery appends markup to the page including script tags that load external js files. You can reproduce it with something like this:

$('body').append('<script src="foo.js"></script>');

I guess jQuery will fix this in some future version. Until then we can either ignore it or use A. Wolff's suggestion above.

Secure Web Services: REST over HTTPS vs SOAP + WS-Security. Which is better?

As you say, REST is good enough for banks so should be good enough for you.

There are two main aspects to security: 1) encryption and 2) identity.

Transmitting in SSL/HTTPS provides encryption over the wire. But you'll also need to make sure that both servers can confirm that they know who they are speaking to. This can be via SSL client certificates, shares secrets, etc.

I'm sure one could make the case that SOAP is "more secure" but probably not in any significant way. The nude motorcyclist analogy is cute but if accurate would imply that the whole internet is insecure.

When 1 px border is added to div, Div size increases, Don't want to do that

This is also helpful in this scenario. it allows you to set borders without changing div width

textarea { 
  -webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
  -moz-box-sizing: border-box;    /* Firefox, other Gecko */
  box-sizing: border-box;         /* Opera/IE 8+ */
}

Taken from http://css-tricks.com/box-sizing/

How do I use extern to share variables between source files?

With xc8 you have to be careful about declaring a variable as the same type in each file as you could , erroneously, declare something an int in one file and a char say in another. This could lead to corruption of variables.

This problem was elegantly solved in a microchip forum some 15 years ago /* See "http:www.htsoft.com" / / "forum/all/showflat.php/Cat/0/Number/18766/an/0/page/0#18766"

But this link seems to no longer work...

So I;ll quickly try to explain it; make a file called global.h.

In it declare the following

#ifdef MAIN_C
#define GLOBAL
 /* #warning COMPILING MAIN.C */
#else
#define GLOBAL extern
#endif
GLOBAL unsigned char testing_mode; // example var used in several C files

Now in the file main.c

#define MAIN_C 1
#include "global.h"
#undef MAIN_C

This means in main.c the variable will be declared as an unsigned char.

Now in other files simply including global.h will have it declared as an extern for that file.

extern unsigned char testing_mode;

But it will be correctly declared as an unsigned char.

The old forum post probably explained this a bit more clearly. But this is a real potential gotcha when using a compiler that allows you to declare a variable in one file and then declare it extern as a different type in another. The problems associated with that are if you say declared testing_mode as an int in another file it would think it was a 16 bit var and overwrite some other part of ram, potentially corrupting another variable. Difficult to debug!

Why does the Visual Studio editor show dots in blank spaces?

In visual studio 2015, goto->view->formatting marks, unselect show

How to get value from form field in django framework?

To retrieve data from form which send post request you can do it like this

def login_view(request):
    if(request.POST):
        login_data = request.POST.dict()
        username = login_data.get("username")
        password = login_data.get("password")
        user_type = login_data.get("user_type")
        print(user_type, username, password)
        return HttpResponse("This is a post request")
    else:
        return render(request, "base.html")

Could not find tools.jar. Please check that C:\Program Files\Java\jre1.8.0_151 contains a valid JDK installation

Solution 1:

  1. Go to your android folder > Gradle.properties > add your jdk path.

  2. Clean and rebuild then it is done. // For Example Purpose Only

    org.gradle.java.home=/Library/Java/JavaVirtualMachines/jdk1.8.0_251.jdk/Contents/Home

Solution 2 At last, here I found the solution.

  1. Add jdk path

    to gradle.properties file and did a rebuild.
    
  2. This will also solve your error.

Here is all Solution could not find tools.jar

Python re.sub replace with matched content

Use \1 instead of $1.

\number Matches the contents of the group of the same number.

http://docs.python.org/library/re.html#regular-expression-syntax

How to rebase local branch onto remote master

git fetch origin master:master pulls the latest version of master without needing to check it out.

So all you need is:

git fetch origin master:master && git rebase master

How to return only the Date from a SQL Server DateTime datatype

If using SQL 2008 and above:

select cast(getdate() as date)

Change MySQL default character set to UTF-8 in my.cnf?

If you are confused by your setting for client and conn is reseted after restart mysql service. Try these steps (which worked for me):

  1. vi /etc/my.cnf
  2. add the contents blow and :wq [client] character-sets-dir=/usr/local/mysql/share/mysql/charsets
  3. restart mysql and login mysql , use database, input command status;, you'll find the character-set for 'client' and 'conn' is set to 'utf8'.

Check the reference for more info.

SDK Manager.exe doesn't work

I had this same problem and after trying a variety of things like changing the path variables I went to java.com on a whim and downloaded java, installed, and lo and behold the sdk manager worked after that.

Re-run Spring Boot Configuration Annotation Processor to update generated metadata

For me, other answers didn't work. I had to go to open Files and do Invalidate caches and restart on Intellij. After that, everything worked fine again.

How To Check If A Key in **kwargs Exists?

One way is to add it by yourself! How? By merging kwargs with a bunch of defaults. This won't be appropriate on all occasions, for example, if the keys are not known to you in advance. However, if they are, here is a simple example:

import sys

def myfunc(**kwargs):
    args = {'country':'England','town':'London',
            'currency':'Pound', 'language':'English'}

    diff = set(kwargs.keys()) - set(args.keys())
    if diff:
        print("Invalid args:",tuple(diff),file=sys.stderr)
        return

    args.update(kwargs)            
    print(args)

The defaults are set in the dictionary args, which includes all the keys we are expecting. We first check to see if there are any unexpected keys in kwargs. Then we update args with kwargs which will overwrite any new values that the user has set. We don't need to test if a key exists, we now use args as our argument dictionary and have no further need of kwargs.

How to import existing *.sql files in PostgreSQL 8.4?

Well, the shortest way I know of, is following:

psql -U {user_name} -d {database_name} -f {file_path} -h {host_name}

database_name: Which database should you insert your file data in.

file_path: Absolute path to the file through which you want to perform the importing.

host_name: The name of the host. For development purposes, it is mostly localhost.

Upon entering this command in console, you will be prompted to enter your password.

Xamarin 2.0 vs Appcelerator Titanium vs PhoneGap

There's also AppGyver Steroids that unites PhoneGap and Native UI nicely.

With Steroids you can add things like native tabs, native navigation bar, native animations and transitions, native modal windows, native drawer/panel (facebooks side menu) etc. to your PhoneGap app.

Here's a demo: http://youtu.be/oXWwDMdoTCk?t=20m17s

UICollectionView cell selection and cell reuse

Framework will handle switching the views for you once you setup your cell's backgroundView and selectedBackgroundView, see example from Managing the Visual State for Selections and Highlights:

UIView* backgroundView = [[UIView alloc] initWithFrame:self.bounds];
backgroundView.backgroundColor = [UIColor redColor];
self.backgroundView = backgroundView;

UIView* selectedBGView = [[UIView alloc] initWithFrame:self.bounds];
selectedBGView.backgroundColor = [UIColor whiteColor];
self.selectedBackgroundView = selectedBGView;

you only need in your class that implements UICollectionViewDelegate enable cells to be highlighted and selected like this:

- (BOOL)collectionView:(UICollectionView *)collectionView
        shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (BOOL)collectionView:(UICollectionView *)collectionView
        shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath;
{
    return YES;
}

This works me.

How do you reverse a string in place in JavaScript?

A small function that handles both combining diacritics and 2-byte characters:

_x000D_
_x000D_
(function(){_x000D_
  var isCombiningDiacritic = function( code )_x000D_
  {_x000D_
    return (0x0300 <= code && code <= 0x036F)  // Comb. Diacritical Marks_x000D_
        || (0x1AB0 <= code && code <= 0x1AFF)  // Comb. Diacritical Marks Extended_x000D_
        || (0x1DC0 <= code && code <= 0x1DFF)  // Comb. Diacritical Marks Supplement_x000D_
        || (0x20D0 <= code && code <= 0x20FF)  // Comb. Diacritical Marks for Symbols_x000D_
        || (0xFE20 <= code && code <= 0xFE2F); // Comb. Half Marks_x000D_
_x000D_
  };_x000D_
_x000D_
  String.prototype.reverse = function()_x000D_
  {_x000D_
    var output = "",_x000D_
        i      = this.length - 1,_x000D_
        width;_x000D_
_x000D_
    for ( ; i >= 0; --i )_x000D_
    {_x000D_
      width = 1;_x000D_
      while( i > 0 && isCombiningDiacritic( this.charCodeAt(i) ) )_x000D_
      {_x000D_
        --i;_x000D_
        width++;_x000D_
      }_x000D_
_x000D_
      if (_x000D_
           i > 0_x000D_
        && "\uDC00" <= this[i]   && this[i]   <= "\uDFFF"_x000D_
        && "\uD800" <= this[i-1] && this[i-1] <= "\uDBFF"_x000D_
      )_x000D_
      {_x000D_
        --i;_x000D_
        width++;_x000D_
      }_x000D_
_x000D_
      output += this.substr( i, width );_x000D_
    }_x000D_
_x000D_
    return output;_x000D_
  }_x000D_
})();_x000D_
_x000D_
// Tests_x000D_
[_x000D_
  'abcdefg',_x000D_
  'ab\u0303c',_x000D_
  'a\uD83C\uDFA5b',_x000D_
  'a\uD83C\uDFA5b\uD83C\uDFA6c',_x000D_
  'a\uD83C\uDFA5b\u0306c\uD83C\uDFA6d',_x000D_
  'TO???????? TH?E??? ?P???O??N?Y?' // copied from http://stackoverflow.com/a/1732454/1509264_x000D_
].forEach(_x000D_
  function(str){ console.log( str + " -> " + str.reverse() ); }_x000D_
);_x000D_
  
_x000D_
_x000D_
_x000D_


Update

A more complete list of combining diacritics is:

      var isCombiningDiacritic = function( code )
      {
        return (0x0300 <= code && code <= 0x036F)
            || (0x0483 <= code && code <= 0x0489)
            || (0x0591 <= code && code <= 0x05BD)
            || (code == 0x05BF)
            || (0x05C1 <= code && code <= 0x05C2)
            || (0x05C4 <= code && code <= 0x05C5)
            || (code == 0x05C7)
            || (0x0610 <= code && code <= 0x061A)
            || (0x064B <= code && code <= 0x065F)
            || (code == 0x0670)
            || (0x06D6 <= code && code <= 0x06DC)
            || (0x06DF <= code && code <= 0x06E4)
            || (0x06E7 <= code && code <= 0x06E8)
            || (0x06EA <= code && code <= 0x06ED)
            || (code == 0x0711)
            || (0x0730 <= code && code <= 0x074A)
            || (0x07A6 <= code && code <= 0x07B0)
            || (0x07EB <= code && code <= 0x07F3)
            || (code == 0x07FD)
            || (0x0816 <= code && code <= 0x0819)
            || (0x081B <= code && code <= 0x0823)
            || (0x0825 <= code && code <= 0x0827)
            || (0x0829 <= code && code <= 0x082D)
            || (0x0859 <= code && code <= 0x085B)
            || (0x08D3 <= code && code <= 0x08E1)
            || (0x08E3 <= code && code <= 0x0902)
            || (code == 0x093A)
            || (code == 0x093C)
            || (0x0941 <= code && code <= 0x0948)
            || (code == 0x094D)
            || (0x0951 <= code && code <= 0x0957)
            || (0x0962 <= code && code <= 0x0963)
            || (code == 0x0981)
            || (code == 0x09BC)
            || (0x09C1 <= code && code <= 0x09C4)
            || (code == 0x09CD)
            || (0x09E2 <= code && code <= 0x09E3)
            || (0x09FE <= code && code <= 0x0A02)
            || (code == 0x0A3C)
            || (0x0A41 <= code && code <= 0x0A51)
            || (0x0A70 <= code && code <= 0x0A71)
            || (code == 0x0A75)
            || (0x0A81 <= code && code <= 0x0A82)
            || (code == 0x0ABC)
            || (0x0AC1 <= code && code <= 0x0AC8)
            || (code == 0x0ACD)
            || (0x0AE2 <= code && code <= 0x0AE3)
            || (0x0AFA <= code && code <= 0x0B01)
            || (code == 0x0B3C)
            || (code == 0x0B3F)
            || (0x0B41 <= code && code <= 0x0B44)
            || (0x0B4D <= code && code <= 0x0B56)
            || (0x0B62 <= code && code <= 0x0B63)
            || (code == 0x0B82)
            || (code == 0x0BC0)
            || (code == 0x0BCD)
            || (code == 0x0C00)
            || (code == 0x0C04)
            || (0x0C3E <= code && code <= 0x0C40)
            || (0x0C46 <= code && code <= 0x0C56)
            || (0x0C62 <= code && code <= 0x0C63)
            || (code == 0x0C81)
            || (code == 0x0CBC)
            || (0x0CCC <= code && code <= 0x0CCD)
            || (0x0CE2 <= code && code <= 0x0CE3)
            || (0x0D00 <= code && code <= 0x0D01)
            || (0x0D3B <= code && code <= 0x0D3C)
            || (0x0D41 <= code && code <= 0x0D44)
            || (code == 0x0D4D)
            || (0x0D62 <= code && code <= 0x0D63)
            || (code == 0x0DCA)
            || (0x0DD2 <= code && code <= 0x0DD6)
            || (code == 0x0E31)
            || (0x0E34 <= code && code <= 0x0E3A)
            || (0x0E47 <= code && code <= 0x0E4E)
            || (code == 0x0EB1)
            || (0x0EB4 <= code && code <= 0x0EBC)
            || (0x0EC8 <= code && code <= 0x0ECD)
            || (0x0F18 <= code && code <= 0x0F19)
            || (code == 0x0F35)
            || (code == 0x0F37)
            || (code == 0x0F39)
            || (0x0F71 <= code && code <= 0x0F7E)
            || (0x0F80 <= code && code <= 0x0F84)
            || (0x0F86 <= code && code <= 0x0F87)
            || (0x0F8D <= code && code <= 0x0FBC)
            || (code == 0x0FC6)
            || (0x102D <= code && code <= 0x1030)
            || (0x1032 <= code && code <= 0x1037)
            || (0x1039 <= code && code <= 0x103A)
            || (0x103D <= code && code <= 0x103E)
            || (0x1058 <= code && code <= 0x1059)
            || (0x105E <= code && code <= 0x1060)
            || (0x1071 <= code && code <= 0x1074)
            || (code == 0x1082)
            || (0x1085 <= code && code <= 0x1086)
            || (code == 0x108D)
            || (code == 0x109D)
            || (0x135D <= code && code <= 0x135F)
            || (0x1712 <= code && code <= 0x1714)
            || (0x1732 <= code && code <= 0x1734)
            || (0x1752 <= code && code <= 0x1753)
            || (0x1772 <= code && code <= 0x1773)
            || (0x17B4 <= code && code <= 0x17B5)
            || (0x17B7 <= code && code <= 0x17BD)
            || (code == 0x17C6)
            || (0x17C9 <= code && code <= 0x17D3)
            || (code == 0x17DD)
            || (0x180B <= code && code <= 0x180D)
            || (0x1885 <= code && code <= 0x1886)
            || (code == 0x18A9)
            || (0x1920 <= code && code <= 0x1922)
            || (0x1927 <= code && code <= 0x1928)
            || (code == 0x1932)
            || (0x1939 <= code && code <= 0x193B)
            || (0x1A17 <= code && code <= 0x1A18)
            || (code == 0x1A1B)
            || (code == 0x1A56)
            || (0x1A58 <= code && code <= 0x1A60)
            || (code == 0x1A62)
            || (0x1A65 <= code && code <= 0x1A6C)
            || (0x1A73 <= code && code <= 0x1A7F)
            || (0x1AB0 <= code && code <= 0x1B03)
            || (code == 0x1B34)
            || (0x1B36 <= code && code <= 0x1B3A)
            || (code == 0x1B3C)
            || (code == 0x1B42)
            || (0x1B6B <= code && code <= 0x1B73)
            || (0x1B80 <= code && code <= 0x1B81)
            || (0x1BA2 <= code && code <= 0x1BA5)
            || (0x1BA8 <= code && code <= 0x1BA9)
            || (0x1BAB <= code && code <= 0x1BAD)
            || (code == 0x1BE6)
            || (0x1BE8 <= code && code <= 0x1BE9)
            || (code == 0x1BED)
            || (0x1BEF <= code && code <= 0x1BF1)
            || (0x1C2C <= code && code <= 0x1C33)
            || (0x1C36 <= code && code <= 0x1C37)
            || (0x1CD0 <= code && code <= 0x1CD2)
            || (0x1CD4 <= code && code <= 0x1CE0)
            || (0x1CE2 <= code && code <= 0x1CE8)
            || (code == 0x1CED)
            || (code == 0x1CF4)
            || (0x1CF8 <= code && code <= 0x1CF9)
            || (0x1DC0 <= code && code <= 0x1DFF)
            || (0x20D0 <= code && code <= 0x20F0)
            || (0x2CEF <= code && code <= 0x2CF1)
            || (code == 0x2D7F)
            || (0x2DE0 <= code && code <= 0x2DFF)
            || (0x302A <= code && code <= 0x302D)
            || (0x3099 <= code && code <= 0x309A)
            || (0xA66F <= code && code <= 0xA672)
            || (0xA674 <= code && code <= 0xA67D)
            || (0xA69E <= code && code <= 0xA69F)
            || (0xA6F0 <= code && code <= 0xA6F1)
            || (code == 0xA802)
            || (code == 0xA806)
            || (code == 0xA80B)
            || (0xA825 <= code && code <= 0xA826)
            || (0xA8C4 <= code && code <= 0xA8C5)
            || (0xA8E0 <= code && code <= 0xA8F1)
            || (code == 0xA8FF)
            || (0xA926 <= code && code <= 0xA92D)
            || (0xA947 <= code && code <= 0xA951)
            || (0xA980 <= code && code <= 0xA982)
            || (code == 0xA9B3)
            || (0xA9B6 <= code && code <= 0xA9B9)
            || (0xA9BC <= code && code <= 0xA9BD)
            || (code == 0xA9E5)
            || (0xAA29 <= code && code <= 0xAA2E)
            || (0xAA31 <= code && code <= 0xAA32)
            || (0xAA35 <= code && code <= 0xAA36)
            || (code == 0xAA43)
            || (code == 0xAA4C)
            || (code == 0xAA7C)
            || (code == 0xAAB0)
            || (0xAAB2 <= code && code <= 0xAAB4)
            || (0xAAB7 <= code && code <= 0xAAB8)
            || (0xAABE <= code && code <= 0xAABF)
            || (code == 0xAAC1)
            || (0xAAEC <= code && code <= 0xAAED)
            || (code == 0xAAF6)
            || (code == 0xABE5)
            || (code == 0xABE8)
            || (code == 0xABED)
            || (code == 0xFB1E)
            || (0xFE00 <= code && code <= 0xFE0F)
            || (0xFE20 <= code && code <= 0xFE2F)
            || (code == 0x101FD)
            || (code == 0x102E0)
            || (0x10376 <= code && code <= 0x1037A)
            || (0x10A01 <= code && code <= 0x10A0F)
            || (0x10A38 <= code && code <= 0x10A3F)
            || (0x10AE5 <= code && code <= 0x10AE6)
            || (0x10D24 <= code && code <= 0x10D27)
            || (0x10F46 <= code && code <= 0x10F50)
            || (code == 0x11001)
            || (0x11038 <= code && code <= 0x11046)
            || (0x1107F <= code && code <= 0x11081)
            || (0x110B3 <= code && code <= 0x110B6)
            || (0x110B9 <= code && code <= 0x110BA)
            || (0x11100 <= code && code <= 0x11102)
            || (0x11127 <= code && code <= 0x1112B)
            || (0x1112D <= code && code <= 0x11134)
            || (code == 0x11173)
            || (0x11180 <= code && code <= 0x11181)
            || (0x111B6 <= code && code <= 0x111BE)
            || (0x111C9 <= code && code <= 0x111CC)
            || (0x1122F <= code && code <= 0x11231)
            || (code == 0x11234)
            || (0x11236 <= code && code <= 0x11237)
            || (code == 0x1123E)
            || (code == 0x112DF)
            || (0x112E3 <= code && code <= 0x112EA)
            || (0x11300 <= code && code <= 0x11301)
            || (0x1133B <= code && code <= 0x1133C)
            || (code == 0x11340)
            || (0x11366 <= code && code <= 0x11374)
            || (0x11438 <= code && code <= 0x1143F)
            || (0x11442 <= code && code <= 0x11444)
            || (code == 0x11446)
            || (code == 0x1145E)
            || (0x114B3 <= code && code <= 0x114B8)
            || (code == 0x114BA)
            || (0x114BF <= code && code <= 0x114C0)
            || (0x114C2 <= code && code <= 0x114C3)
            || (0x115B2 <= code && code <= 0x115B5)
            || (0x115BC <= code && code <= 0x115BD)
            || (0x115BF <= code && code <= 0x115C0)
            || (0x115DC <= code && code <= 0x115DD)
            || (0x11633 <= code && code <= 0x1163A)
            || (code == 0x1163D)
            || (0x1163F <= code && code <= 0x11640)
            || (code == 0x116AB)
            || (code == 0x116AD)
            || (0x116B0 <= code && code <= 0x116B5)
            || (code == 0x116B7)
            || (0x1171D <= code && code <= 0x1171F)
            || (0x11722 <= code && code <= 0x11725)
            || (0x11727 <= code && code <= 0x1172B)
            || (0x1182F <= code && code <= 0x11837)
            || (0x11839 <= code && code <= 0x1183A)
            || (0x119D4 <= code && code <= 0x119DB)
            || (code == 0x119E0)
            || (0x11A01 <= code && code <= 0x11A06)
            || (0x11A09 <= code && code <= 0x11A0A)
            || (0x11A33 <= code && code <= 0x11A38)
            || (0x11A3B <= code && code <= 0x11A3E)
            || (code == 0x11A47)
            || (0x11A51 <= code && code <= 0x11A56)
            || (0x11A59 <= code && code <= 0x11A5B)
            || (0x11A8A <= code && code <= 0x11A96)
            || (0x11A98 <= code && code <= 0x11A99)
            || (0x11C30 <= code && code <= 0x11C3D)
            || (0x11C92 <= code && code <= 0x11CA7)
            || (0x11CAA <= code && code <= 0x11CB0)
            || (0x11CB2 <= code && code <= 0x11CB3)
            || (0x11CB5 <= code && code <= 0x11CB6)
            || (0x11D31 <= code && code <= 0x11D45)
            || (code == 0x11D47)
            || (0x11D90 <= code && code <= 0x11D91)
            || (code == 0x11D95)
            || (code == 0x11D97)
            || (0x11EF3 <= code && code <= 0x11EF4)
            || (0x16AF0 <= code && code <= 0x16AF4)
            || (0x16B30 <= code && code <= 0x16B36)
            || (code == 0x16F4F)
            || (0x16F8F <= code && code <= 0x16F92)
            || (0x1BC9D <= code && code <= 0x1BC9E)
            || (0x1D167 <= code && code <= 0x1D169)
            || (0x1D17B <= code && code <= 0x1D182)
            || (0x1D185 <= code && code <= 0x1D18B)
            || (0x1D1AA <= code && code <= 0x1D1AD)
            || (0x1D242 <= code && code <= 0x1D244)
            || (0x1DA00 <= code && code <= 0x1DA36)
            || (0x1DA3B <= code && code <= 0x1DA6C)
            || (code == 0x1DA75)
            || (code == 0x1DA84)
            || (0x1DA9B <= code && code <= 0x1E02A)
            || (0x1E130 <= code && code <= 0x1E136)
            || (0x1E2EC <= code && code <= 0x1E2EF)
            || (0x1E8D0 <= code && code <= 0x1E8D6)
            || (0x1E944 <= code && code <= 0x1E94A)
            || (0xE0100 <= code && code <= 0xE01EF);
      };

What is the best way to get the first letter from a string in Java, returned as a string of length 1?

import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;

import java.util.concurrent.TimeUnit;

@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1)
@Fork(value = 1)
@Measurement(iterations = 5, time = 1)
public class StringFirstCharBenchmark {

    private String source;

    @Setup
    public void init() {
        source = "MALE";
    }

    @Benchmark
    public String substring() {
        return source.substring(0, 1);
    }

    @Benchmark
    public String indexOf() {
        return String.valueOf(source.indexOf(0));
    }
}

Results:

+----------------------------------------------------------------------+
| Benchmark                           Mode  Cnt   Score   Error  Units |
+----------------------------------------------------------------------+
| StringFirstCharBenchmark.indexOf    avgt    5  23.777 ? 5.788  ns/op |
| StringFirstCharBenchmark.substring  avgt    5  11.305 ? 1.411  ns/op |
+----------------------------------------------------------------------+

How to compare two NSDates: Which is more recent?

In Swift, you can overload existing operators:

func > (lhs: NSDate, rhs: NSDate) -> Bool {
    return lhs.timeIntervalSinceReferenceDate > rhs.timeIntervalSinceReferenceDate
}

func < (lhs: NSDate, rhs: NSDate) -> Bool {
    return lhs.timeIntervalSinceReferenceDate < rhs.timeIntervalSinceReferenceDate
}

Then, you can compare NSDates directly with <, >, and == (already supported).

Call a function after previous function is complete

This answer uses promises, a JavaScript feature of the ECMAScript 6 standard. If your target platform does not support promises, polyfill it with PromiseJs.

Promises are a new (and a lot better) way to handle asynchronous operations in JavaScript:

$('a.button').click(function(){
    if (condition == 'true'){
        function1(someVariable).then(function() {
            //this function is executed after function1
            function2(someOtherVariable);
        });
    }
    else {
        doThis(someVariable);
    }
});


function function1(param, callback) {
    return new Promise(function (fulfill, reject){
        //do stuff
        fulfill(result); //if the action succeeded
        reject(error); //if the action did not succeed
    });
} 

This may seem like a significant overhead for this simple example, but for more complex code it is far better than using callbacks. You can easily chain multiple asynchronous calls using multiple then statements:

function1(someVariable).then(function() {
    function2(someOtherVariable);
}).then(function() {
    function3();
});

You can also wrap jQuery deferrds easily (which are returned from $.ajax calls):

Promise.resolve($.ajax(...params...)).then(function(result) {
    //whatever you want to do after the request
});

As @charlietfl noted, the jqXHR object returned by $.ajax() implements the Promise interface. So it is not actually necessary to wrap it in a Promise, it can be used directly:

$.ajax(...params...).then(function(result) {
    //whatever you want to do after the request
});

Force browser to clear cache

In addition to setting Cache-control: no-cache, you should also set the Expires header to -1 if you would like the local copy to be refreshed each time (some versions of IE seem to require this).

See HTTP Cache - check with the server, always sending If-Modified-Since

In Python, how do I convert all of the items in a list to floats?

This is how I would do it.

my_list = ['0.49', '0.54', '0.54', '0.54', '0.54', '0.54', '0.55', '0.54', 
    '0.54', '0.54', '0.55', '0.55', '0.55', '0.54', '0.55', '0.55', '0.54', 
    '0.55', '0.55', '0.54']
print type(my_list[0]) # prints <type 'str'>
my_list = [float(i) for i in my_list]
print type(my_list[0]) # prints <type 'float'>

"This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded"

The error was due to the way that I configured the Application Pool in IIS.

My web service uses an Application Tool configured for v2.0.50727. This resulted in the error message.

When I changed it to v4.0.30319, I did not get the error.

Display Records From MySQL Database using JTable in Java

this is the easy way to do that you just need to download the jar file "rs2xml.jar" add it to your project and do that : 1- creat a connection 2- statment and resultset 3- creat a jtable 4- give the result set to DbUtils.resultSetToTableModel(rs) as define in this methode you well get your jtable so easy.

public void afficherAll(String tableName){
        String sql="select * from "+tableName;
        try {
            stmt=con.createStatement();
            rs=stmt.executeQuery(sql);
            tbContTable.setModel(DbUtils.resultSetToTableModel(rs));
        } catch (SQLException e) {
            // TODO Auto-generated catch block
             JOptionPane.showMessageDialog(null, e);
        }       
    }

Spring Boot Adding Http Request Interceptors

To add interceptor to a spring boot application, do the following

  1. Create an interceptor class

    public class MyCustomInterceptor implements HandlerInterceptor{
    
        //unimplemented methods comes here. Define the following method so that it     
        //will handle the request before it is passed to the controller.
    
        @Override
        public boolean preHandle(HttpServletRequest request,HttpServletResponse  response){
        //your custom logic here.
            return true;
        }
    }
    
  2. Define a configuration class

    @Configuration
    public class MyConfig extends WebMvcConfigurerAdapter{
        @Override
        public void addInterceptors(InterceptorRegistry registry){
            registry.addInterceptor(new MyCustomInterceptor()).addPathPatterns("/**");
        }
    }
    
  3. Thats it. Now all your requests will pass through the logic defined under preHandle() method of MyCustomInterceptor.

Implementing a slider (SeekBar) in Android

For future readers!

Starting from material components android 1.2.0-alpha01, you have slider component

ex:

<com.google.android.material.slider.Slider
        android:id="@+id/slider"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:valueFrom="20f"
        android:valueTo="70f"
        android:stepSize="10" />

Set adb vendor keys

If you have an AVD, this might help.

Open the AVD Manager from Android Studio. Choose the dropdown in the right most of your device row. Then do Wipe Data. Restart your virtual device, and ADB will work.

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

In my case, for an Azure hosted Angular 2/4 site, my API call to mySite/api/... was redirecting due to mySite routing issues. So, it was returning the HTML from the redirected page instead of the api JSON. I added an exclusion in a web.config file for the api path.

I was not getting this error when developing locally because the Site and API were on different ports. There is probably a better way to do this ... but it worked.

<?xml version="1.0" encoding="UTF-8"?>

<configuration>
    <system.webServer>
        <rewrite>
        <rules>
        <clear />

        <!-- ignore static files -->
        <rule name="AngularJS Conditions" stopProcessing="true">
        <match url="(app/.*|css/.*|fonts/.*|assets/.*|images/.*|js/.*|api/.*)" />
        <conditions logicalGrouping="MatchAll" trackAllCaptures="false" />
        <action type="None" />
        </rule>

        <!--remaining all other url's point to index.html file -->
        <rule name="AngularJS Wildcard" enabled="true">
        <match url="(.*)" />
        <conditions logicalGrouping="MatchAll" trackAllCaptures="false" />
        <action type="Rewrite" url="index.html" />
        </rule>

        </rules>
        </rewrite>
    </system.webServer>
</configuration>

CSS - Expand float child DIV height to parent's height

If you are aware of bootstrap you can do it easily by using 'flex' property.All you need to do is pass below css properties to parent div

.homepageSection {
  overflow: hidden;
  height: auto;
  display: flex;
  flex-flow: row;
}

where .homepageSection is my parent div. Now add child div in your html as

<div class="abc col-md-6">
<div class="abc col-md-6">

where abc is my child div.You can check equality of height in both child div irrespective of border just by giving border to child div

Changing the child element's CSS when the parent is hovered

Why not just use CSS?

.parent:hover .child, .parent.hover .child { display: block; }

and then add JS for IE6 (inside a conditional comment for instance) which doesn't support :hover properly:

jQuery('.parent').hover(function () {
    jQuery(this).addClass('hover');
}, function () {
    jQuery(this).removeClass('hover');
});

Here's a quick example: Fiddle

Drop all tables whose names begin with a certain string

Xenph Yan's answer was far cleaner than mine but here is mine all the same.

DECLARE @startStr AS Varchar (20)
SET @startStr = 'tableName'

DECLARE @startStrLen AS int
SELECT @startStrLen = LEN(@startStr)

SELECT 'DROP TABLE ' + name FROM sysobjects
WHERE type = 'U' AND LEFT(name, @startStrLen) = @startStr

Just change tableName to the characters that you want to search with.

Fastest way to count number of occurrences in a Python list

a = ['1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '7', '7', '7', '10', '10']
print a.count("1")

It's probably optimized heavily at the C level.

Edit: I randomly generated a large list.

In [8]: len(a)
Out[8]: 6339347

In [9]: %timeit a.count("1")
10 loops, best of 3: 86.4 ms per loop

Edit edit: This could be done with collections.Counter

a = Counter(your_list)
print a['1']

Using the same list in my last timing example

In [17]: %timeit Counter(a)['1']
1 loops, best of 3: 1.52 s per loop

My timing is simplistic and conditional on many different factors, but it gives you a good clue as to performance.

Here is some profiling

In [24]: profile.run("a.count('1')")
         3 function calls in 0.091 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.091    0.091 <string>:1(<module>)
        1    0.091    0.091    0.091    0.091 {method 'count' of 'list' objects}

        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Prof
iler' objects}



In [25]: profile.run("b = Counter(a); b['1']")
         6339356 function calls in 2.143 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    2.143    2.143 <string>:1(<module>)
        2    0.000    0.000    0.000    0.000 _weakrefset.py:68(__contains__)
        1    0.000    0.000    0.000    0.000 abc.py:128(__instancecheck__)
        1    0.000    0.000    2.143    2.143 collections.py:407(__init__)
        1    1.788    1.788    2.143    2.143 collections.py:470(update)
        1    0.000    0.000    0.000    0.000 {getattr}
        1    0.000    0.000    0.000    0.000 {isinstance}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Prof
iler' objects}
  6339347    0.356    0.000    0.356    0.000 {method 'get' of 'dict' objects}

Highcharts - redraw() vs. new Highcharts.chart

you have to call set and add functions on chart object before calling redraw.

chart.xAxis[0].setCategories([2,4,5,6,7], false);

chart.addSeries({
    name: "acx",
    data: [4,5,6,7,8]
}, false);

chart.redraw();

How to get the scroll bar with CSS overflow on iOS

make sure your body and divs have not a

  position:fixed

else it would not work

Make a link use POST instead of GET

This is an old question, but none of the answers satisfy the request in-full. So I'm adding another answer.

The requested code, as I understand, should make only one change to the way normal hyperlinks work: the POST method should be used instead of GET. The immediate implications would be:

  1. When the link is clicked we should reload the tab to the url of the href
  2. As the method is POST, we should have no query string in the URL of the target page we load
  3. That page should receive the data in parameters (names and value) by POST

I am using jquery here, but this could be done with native apis (harder and longer of course).

<html>
<head>
    <script src="path/to/jquery.min.js" type="text/javascript"></script>
    <script>
        $(document).ready(function() {

            $("a.post").click(function(e) {
                e.stopPropagation();
                e.preventDefault();
                var href = this.href;
                var parts = href.split('?');
                var url = parts[0];
                var params = parts[1].split('&');
                var pp, inputs = '';
                for(var i = 0, n = params.length; i < n; i++) {
                    pp = params[i].split('=');
                    inputs += '<input type="hidden" name="' + pp[0] + '" value="' + pp[1] + '" />';
                }
                $("body").append('<form action="'+url+'" method="post" id="poster">'+inputs+'</form>');
                $("#poster").submit();
            });
        });
    </script>
</head>
<body>
    <a class="post" href="reflector.php?color=blue&weight=340&model=x-12&price=14.800">Post it!</a><br/>
    <a href="reflector.php?color=blue&weight=340&model=x-12&price=14.800">Normal link</a>
</body>
</html>

And to see the result, save the following as reflector.php in the same directory you have the above saved.

<h2>Get</h2>
<pre>
<?php print_r($_GET); ?>
</pre>

<h2>Post</h2>
<pre>
<?php print_r($_POST); ?>
</pre>

'NOT NULL constraint failed' after adding to models.py

if the zipcode field is not a required field then add null=True and blank=True, then run makemigrations and migrate command to successfully reflect the changes in the database.

Should a RESTful 'PUT' operation return something

The HTTP/1.1 spec (section 9.6) discusses the appropriate response/error codes. However it doesn't address the response content.

What would you expect ? A simple HTTP response code (200 etc.) seems straightforward and unambiguous to me.

c++ Read from .csv file

That because your csv file is in invalid format, maybe the line break in your text file is not the \n or \r

and, using c/c++ to parse text is not a good idea. try awk:

 $awk -F"," '{print "ID="$1"\tName="$2"\tAge="$3"\tGender="$4}' 1.csv
 ID=0   Name=Filipe Age=19  Gender=M
 ID=1   Name=Maria  Age=20  Gender=F
 ID=2   Name=Walter Age=60  Gender=M

MVC - Set selected value of SelectList

In case someone is looking I reposted my answer from: SelectListItem selected = true not working in view

After searching myself for answer to this problem - I had some hints along the way but this is the resulting solution for me. It is an extension Method. I am using MVC 5 C# 4.52 is the target. The code below sets the Selection to the First Item in the List because that is what I needed, you might desire simply to pass a string and skip enumerating - but I also wanted to make sure I had something returned to my SelectList from the DB)

Extension Method:

public static class SelectListextensions {

public static System.Web.Mvc.SelectList SetSelectedValue

(this System.Web.Mvc.SelectList list, string value) { if (value != null) { var selected = list.Where(x => x.Text == value).FirstOrDefault(); selected.Selected = true;
} return list; }
}

And for those who like the complete low down (like me) here is the usage. The object Category has a field defined as Name - this is the field that will show up as Text in the drop down. You can see that test for the Text property in the code above.

Example Code:

SelectList categorylist = new SelectList(dbContext.Categories, "Id", "Name");

SetSelectedItemValue(categorylist);

select list function:

private SelectList SetSelectedItemValue(SelectList source) { Category category = new Category();

SelectListItem firstItem = new SelectListItem();

int selectListCount = -1;

if (source != null && source.Items != null)
{
    System.Collections.IEnumerator cenum = source.Items.GetEnumerator();

    while (cenum.MoveNext())
    {
        if (selectListCount == -1)
        {
            selectListCount = 0;
        }

        selectListCount += 1;

        category = (Category)cenum.Current;

        source.SetSelectedValue(category.Name);

        break;
    }
    if (selectListCount > 0)
    {
        foreach (SelectListItem item in source.Items)
        {
            if (item.Value == cenum.Current.ToString())
            {
                item.Selected = true;

                break;
            }
        }
    }
}
return source;

}

You can make this a Generic All Inclusive function / Extension - but it is working as is for me

How to create a DataFrame from a text file in Spark

You will not able to convert it into data frame until you use implicit conversion.

val sqlContext = new SqlContext(new SparkContext())

import sqlContext.implicits._

After this only you can convert this to data frame

case class Test(id:String,filed2:String)

val myFile = sc.textFile("file.txt")

val df= myFile.map( x => x.split(";") ).map( x=> Test(x(0),x(1)) ).toDF()

Determining the current foreground application from a background task or service

Do something like this:

int showLimit = 20;

/* Get all Tasks available (with limit set). */
ActivityManager mgr = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> allTasks = mgr.getRunningTasks(showLimit);
/* Loop through all tasks returned. */
for (ActivityManager.RunningTaskInfo aTask : allTasks) 
{                  
    Log.i("MyApp", "Task: " + aTask.baseActivity.getClassName()); 
    if (aTask.baseActivity.getClassName().equals("com.android.email.activity.MessageList")) 
        running=true;
}

Is there a "theirs" version of "git merge -s ours"?

Older versions of git allowed you to use the "theirs" merge strategy:

git pull --strategy=theirs remote_branch

But this has since been removed, as explained in this message by Junio Hamano (the Git maintainer). As noted in the link, instead you would do this:

git fetch origin
git reset --hard origin

Beware, though, that this is different than an actual merge. Your solution is probably the option you're really looking for.

window.location.href doesn't redirect

window.location.replace is the best way to emulate a redirect:

function ShowComments(){
    var movieShareId = document.getElementById('movieId');
    window.location.replace("/comments.aspx?id=" + (movieShareId.textContent || movieShareId.innerText) + "/");
}

More information about why window.location.replace is the best javascript redirect can be found right here.

When should null values of Boolean be used?

The best way would be to avoid booleans completely, since every boolean implies that you have a conditional statement anywhere else in your code (see http://www.antiifcampaign.com/ and this question: Can you write any algorithm without an if statement?).

However, pragmatically you have to use booleans from time to time, but, as you have already found out by yourself, dealing with Booleans is more error prone and more cumbersome. So I would suggest using booleans wherever possible. Exceptions from this might be a legacy database with nullable boolean-columns, although I would try to hide that in my mapping as well.

PHP - Session destroy after closing browser

This might help you,

session_set_cookie_params(0);
session_start();

Your session cookie will be destroyed... so your session will be good until the browser is open. please view http://www.php.net//manual/en/function.session-set-cookie-params.php this may help you.

Where are $_SESSION variables stored?

One addition: It should be noted that, in case "/tmp" is the directory where the session data is stored (which seems to be the default value), the sessions will not persist after reboot of that web server, as "/tmp" is often purged during reboot. The concept of a client-wise persistence stands and falls with the persistence of the storage on the server - which might fail if the "/tmp" directory is used for session data.

Batch command to move files to a new directory

Something like this might help:

SET Today=%Date:~10,4%%Date:~4,2%%Date:~7,2%
mkdir C:\Test\Backup-%Today%
move C:\Test\Log\*.* C:\Test\Backup-%Today%\
SET Today=

The important part is the first line. It takes the output of the internal DATE value and parses it into an environmental variable named Today, in the format CCYYMMDD, as in '20110407`.

The %Date:~10,4% says to extract a *substring of the Date environmental variable 'Thu 04/07/2011' (built in - type echo %Date% at a command prompt) starting at position 10 for 4 characters (2011). It then concatenates another substring of Date: starting at position 4 for 2 chars (04), and then concats two additional characters starting at position 7 (07).

*The substring value starting points are 0-based.

You may need to adjust these values depending on the date format in your locale, but this should give you a starting point.

Bootstrap 4, how to make a col have a height of 100%?

Use the Bootstrap 4 h-100 class for height:100%;

<div class="container-fluid h-100">
  <div class="row justify-content-center h-100">
    <div class="col-4 hidden-md-down" id="yellow">
      XXXX
    </div>
    <div class="col-10 col-sm-10 col-md-10 col-lg-8 col-xl-8">
      Form Goes Here
    </div>
  </div>
</div>

https://www.codeply.com/go/zxd6oN1yWp

You'll also need ensure any parent(s) are also 100% height (or have a defined height)...

html,body {
  height: 100%;
}

Note: 100% height is not the same as "remaining" height.


Related: Bootstrap 4: How to make the row stretch remaining height?

Does a foreign key automatically create an index?

No, there is no implicit index on foreign key fields, otherwise why would Microsoft say "Creating an index on a foreign key is often useful". Your colleague may be confusing the foreign key field in the referring table with the primary key in the referred-to table - primary keys do create an implicit index.

The program can’t start because MSVCR71.dll is missing from your computer. Try reinstalling the program to fix this program

MY SOLUTION!!!!!!! I fixed this problem when I was trying to install business objects. When the installer failed to register .dll's I inputted the MSVCR71.dll into both system32 and sysWOW64 then clicked retry. Installation finished. I did try adding this in before and after install but, install still failed.