Programs & Examples On #Allegro

Allegro is a game programming library for C/C++ developers distributed freely, supporting the following platforms: Unix (Linux, FreeBSD, etc.), Windows, OS X, iOS, and Android.

fatal error LNK1169: one or more multiply defined symbols found in game programming

just add /FORCE as linker flag and you're all set.

for instance, if you're working on CMakeLists.txt. Then add following line:

SET(CMAKE_EXE_LINKER_FLAGS  "/FORCE")

Rotating a point about another point (2D)

First subtract the pivot point (cx,cy), then rotate it, then add the point again.

Untested:

POINT rotate_point(float cx,float cy,float angle,POINT p)
{
  float s = sin(angle);
  float c = cos(angle);

  // translate point back to origin:
  p.x -= cx;
  p.y -= cy;

  // rotate point
  float xnew = p.x * c - p.y * s;
  float ynew = p.x * s + p.y * c;

  // translate point back:
  p.x = xnew + cx;
  p.y = ynew + cy;
  return p;
}

A full list of all the new/popular databases and their uses?

Martin Fowler did an interesting blog post last year about non-relational databases starting to gain traction. He mentions:

  • Drizzle (a "bare bones" relational database)
  • CouchDB (a document-oriented database)
  • GemStone (an object-oriented database)

There is also Google's BigTable which is described as "a sparse, distributed multi-dimensional sorted map".

I have been working with GemStone for a number of years now and the productivity gains is amazing - having the database store your objects directly removes the need to constantly marshall back and forth between tables and objects.

Converting from IEnumerable to List

You can do this very simply using LINQ.

Make sure this using is at the top of your C# file:

using System.Linq;

Then use the ToList extension method.

Example:

IEnumerable<int> enumerable = Enumerable.Range(1, 300);
List<int> asList = enumerable.ToList();

C# looping through an array

Just increment i by 3 in each step:

  Debug.Assert((theData.Length % 3) == 0);  // 'theData' will always be divisible by 3

  for (int i = 0; i < theData.Length; i += 3)
  {
       //grab 3 items at a time and do db insert, 
       // continue until all items are gone..
       string item1 = theData[i+0];
       string item2 = theData[i+1];
       string item3 = theData[i+2];
       // use the items
  }

To answer some comments, it is a given that theData.Length is a multiple of 3 so there is no need to check for theData.Length-2 as an upperbound. That would only mask errors in the preconditions.

PHP not displaying errors even though display_errors = On

When you update the configuration in the php.ini file, you might have to restart apache. Try running apachectl restart or apache2ctl restart, or something like that.

Also, in you ini file, make sure you have display_errors = on, but only in a development environment, never in a production machine.

Also, the strictest error reporting is exactly what you have cited, E_ALL | E_STRICT. You can find more information on error levels at the php docs.

run program in Python shell

Use execfile for Python 2:

>>> execfile('C:\\test.py')

Use exec for Python 3

>>> exec(open("C:\\test.py").read())

Update multiple rows with different values in a single SQL query

Try with "update tablet set (row='value' where id=0001'), (row='value2' where id=0002'), ...

How can I set the focus (and display the keyboard) on my EditText programmatically

I recommend using a LifecycleObserver which is part of the Handling Lifecycles with Lifecycle-Aware Components of Android Jetpack.

I want to open and close the Keyboard when the Fragment/Activity appears. Firstly, define two extension functions for the EditText. You can put them anywhere in your project:

fun EditText.showKeyboard() {
    requestFocus()
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
}

fun EditText.hideKeyboard() {
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(this.windowToken, 0)
}

Then define a LifecycleObserver which opens and closes the keyboard when the Activity/Fragment reaches onResume() or onPause:

class EditTextKeyboardLifecycleObserver(private val editText: WeakReference<EditText>) :
    LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun openKeyboard() {
        editText.get()?.postDelayed({ editText.get()?.showKeyboard() }, 100)
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    fun closeKeyboard() {
        editText.get()?.hideKeyboard()
    }
}

Then add the following line to any of your Fragments/Activities, you can reuse the LifecycleObserver any times. E.g. for a Fragment:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

    // inflate the Fragment layout

    lifecycle.addObserver(EditTextKeyboardLifecycleObserver(WeakReference(myEditText)))

    // do other stuff and return the view

}

Skip Git commit hooks

From man githooks:

pre-commit
This hook is invoked by git commit, and can be bypassed with --no-verify option. It takes no parameter, and is invoked before obtaining the proposed commit log message and making a commit. Exiting with non-zero status from this script causes the git commit to abort.

How can I insert binary file data into a binary SQL field using a simple insert statement?

I believe this would be somewhere close.

INSERT INTO Files
(FileId, FileData)
SELECT 1, * FROM OPENROWSET(BULK N'C:\Image.jpg', SINGLE_BLOB) rs

Something to note, the above runs in SQL Server 2005 and SQL Server 2008 with the data type as varbinary(max). It was not tested with image as data type.

How to see the changes between two commits without commits in-between?

My alias settings in ~/.bashrc file for git diff:

alias gdca='git diff --cached' # diff between your staged file and the last commit
alias gdcc='git diff HEAD{,^}' # diff between your latest two commits

How to detect if user select cancel InputBox VBA Excel

Following example uses InputBox method to validate user entry to unhide sheets: Important thing here is to use wrap InputBox variable inside StrPtr so it could be compared to '0' when user chose to click 'x' icon on the InputBox.

Sub unhidesheet()

Dim ws As Worksheet
Dim pw As String

pw = InputBox("Enter Password to Unhide Sheets:", "Unhide Data Sheets")
If StrPtr(pw) = 0 Then

   Exit Sub
ElseIf pw = NullString Then
   Exit Sub
ElseIf pw = 123456 Then
    For Each ws In ThisWorkbook.Worksheets
        ws.Visible = xlSheetVisible
    Next
End If
End Sub

Why is pydot unable to find GraphViz's executables in Windows 8?

In "pydot.py" (located in ...\Anaconda3\Lib\site-packages), replace:

def get_executable_extension():
    # type: () -> str
    if is_windows():
        return '.bat' if is_anacoda() else '.exe'
    else:
        return ''

with:

def get_executable_extension():
    # type: () -> str
    if is_windows():
        return '.exe'
    else:
        return ''

There does not seem to be any eason to add ".bat" when the system is "Windows/Anaconda" vs "Windows" and there may be no ".bat" associated with the ".exe". This seems better than adding a ".bat" for every executable pydot calls...

Difference between string and text in rails?

If you are using oracle... STRING will be created as VARCHAR(255) column and TEXT, as a CLOB.

NATIVE_DATABASE_TYPES = {
    primary_key: "NUMBER(38) NOT NULL PRIMARY KEY",
    string: { name: "VARCHAR2", limit: 255 },
    text: { name: "CLOB" },
    ntext: { name: "NCLOB" },
    integer: { name: "NUMBER", limit: 38 },
    float: { name: "BINARY_FLOAT" },
    decimal: { name: "DECIMAL" },
    datetime: { name: "TIMESTAMP" },
    timestamp: { name: "TIMESTAMP" },
    timestamptz: { name: "TIMESTAMP WITH TIME ZONE" },
    timestampltz: { name: "TIMESTAMP WITH LOCAL TIME ZONE" },
    time: { name: "TIMESTAMP" },
    date: { name: "DATE" },
    binary: { name: "BLOB" },
    boolean: { name: "NUMBER", limit: 1 },
    raw: { name: "RAW", limit: 2000 },
    bigint: { name: "NUMBER", limit: 19 }
}

https://github.com/rsim/oracle-enhanced/blob/master/lib/active_record/connection_adapters/oracle_enhanced_adapter.rb

Getting list of pixel values from PIL

Not PIL, but scipy.misc.imread might still be interesting:

import scipy.misc
im = scipy.misc.imread('um_000000.png', flatten=False, mode='RGB')
print(im.shape)

gives

(480, 640, 3)

so it is (height, width, channels). So you can iterate over it by

for y in range(im.shape[0]):
    for x in range(im.shape[1]):
        color = tuple(im[y][x])
        r, g, b = color

Can I update a component's props in React.js?

Much has changed with hooks, e.g. componentWillReceiveProps turned into useEffect+useRef (as shown in this other SO answer), but Props are still Read-Only, so only the caller method should update it.

nginx error:"location" directive is not allowed here in /etc/nginx/nginx.conf:76

Since your server already includes the sites-enabled folder ( notice the include /etc/nginx/sites-enabled/* line ), then you better use that.

  1. Create a file inside /etc/nginx/sites-available and call it whatever you want, I'll call it django since it's a djanog server

    sudo touch /etc/nginx/sites-available/django
    
  2. Then create a symlink that points to it

    sudo ln -s /etc/nginx/sites-available/django /etc/nginx/sites-enabled
    
  3. Then edit that file with whatever file editor you use, vim or nano or whatever and create the server inside it

    server {
        # hostname or ip or multiple separated by spaces
        server_name localhost example.com 192.168.1.1; #change to your setting
        location / {
            root /home/techcee/scrapbook/local/lib/python2.7/site-packages/django/__init__.pyc/;
        }
    }
    
  4. Restart or reload nginx settings

    sudo service nginx reload
    

Note I believe that your configuration like this probably won't work yet because you need to pass it to a fastcgi server or something, but at least this is how you could create a valid server

Python os.path.join() on a list

I stumbled over the situation where the list might be empty. In that case:

os.path.join('', *the_list_with_path_components)

Note the first argument, which will not alter the result.

Pushing from local repository to GitHub hosted remote

You push your local repository to the remote repository using the git push command after first establishing a relationship between the two with the git remote add [alias] [url] command. If you visit your Github repository, it will show you the URL to use for pushing. You'll first enter something like:

git remote add origin [email protected]:username/reponame.git

Unless you started by running git clone against the remote repository, in which case this step has been done for you already.

And after that, you'll type:

git push origin master

After your first push, you can simply type:

git push

when you want to update the remote repository in the future.

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 13: ordinal not in range(128)

This works fine for me.

f = open(file_path, 'r+', encoding="utf-8")

You can add a third parameter encoding to ensure the encoding type is 'utf-8'

Note: this method works fine in Python3, I did not try it in Python2.7.

Fetching data from MySQL database to html dropdown list

To do this you want to loop through each row of your query results and use this info for each of your drop down's options. You should be able to adjust the code below fairly easily to meet your needs.

// Assume $db is a PDO object
$query = $db->query("YOUR QUERY HERE"); // Run your query

echo '<select name="DROP DOWN NAME">'; // Open your drop down box

// Loop through the query results, outputing the options one by one
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
   echo '<option value="'.$row['something'].'">'.$row['something'].'</option>';
}

echo '</select>';// Close your drop down box

Connect to mysql in a docker container from the host

I recommend checking out docker-compose. Here's how that would work:

Create a file named, docker-compose.yml that looks like this:

version: '2'

services:

  mysql:
    image: mariadb:10.1.19
    ports:
      - 8083:3306
    volumes:
      - ./mysql:/var/lib/mysql
    environment:
      MYSQL_ROOT_PASSWORD: wp

Next, run:

$ docker-compose up

Notes:

Now, you can access the mysql console thusly:

$ mysql -P 8083 --protocol=tcp -u root -p

Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 5.5.5-10.1.19-MariaDB-1~jessie mariadb.org binary distribution

Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

Notes:

  • You can pass the -d flag to run the mysql/mariadb container in detached/background mode.

  • The password is "wp" which is defined in the docker-compose.yml file.

  • Same advice as maniekq but full example with docker-compose.

Getting HTTP code in PHP using curl

curl_exec is necessary. Try CURLOPT_NOBODY to not download the body. That might be faster.

How to remove carriage return and newline from a variable in shell script

Pipe to sed -e 's/[\r\n]//g' to remove both Carriage Returns (\r) and Line Feeds (\n) from each text line.

AngularJS ng-click stopPropagation

An addition to Stewie's answer. In case when your callback decides whether the propagation should be stopped or not, I found it useful to pass the $event object to the callback:

<div ng-click="parentHandler($event)">
  <div ng-click="childHandler($event)">
  </div>
</div>

And then in the callback itself, you can decide whether the propagation of the event should be stopped:

$scope.childHandler = function ($event) {
  if (wanna_stop_it()) {
    $event.stopPropagation();
  }
  ...
};

How to pass arguments to entrypoint in docker-compose.yml

You can use docker-compose run instead of docker-compose up and tack the arguments on the end. For example:

docker-compose run dperson/samba arg1 arg2 arg3

If you need to connect to other docker containers, use can use --service-ports option:

docker-compose run --service-ports dperson/samba arg1 arg2 arg3

Running Node.js in apache?

Hosting a nodejs site through apache can be organized with apache proxy module.

It's better to start nodejs server on localhost with default port 1337

Enable proxy with a command:

sudo a2enmod proxy proxy_http

Do not enable proxying with ProxyRequests until you have secured your server. Open proxy servers are dangerous both to your network and to the Internet at large. Setting ProxyRequests to Off does not disable use of the ProxyPass directive.

Configure /etc/apche2/sites-availables with

<VirtualHost *:80>
    ServerAdmin [email protected]
    ServerName site.com
    ServerAlias www.site.com 

    ProxyRequests off

    <Proxy *>
        Order deny,allow
        Allow from all
    </Proxy>

    <Location />
        ProxyPass http://localhost:1337/
        ProxyPassReverse http://localhost:1337/
    </Location>
</VirtualHost>

and restart apache2 service.

What is Java Servlet?

What is a Servlet?

  • A servlet is simply a class which responds to a particular type of network request - most commonly an HTTP request.
  • Basically servlets are usually used to implement web applications - but there are also various frameworks which operate on top of servlets (e.g. Struts) to give a higher-level abstraction than the "here's an HTTP request, write to this HTTP response" level which servlets provide.
  • Servlets run in a servlet container which handles the networking side (e.g. parsing an HTTP request, connection handling etc). One of the best-known open source servlet containers is Tomcat.

  • In a request/response paradigm, a web server can serve only static pages to the client

  • To serve dynamic pages, a we require Servlets.
  • Servlet is nothing but a Java program
  • This Java program doesn’t have a main method. It only has some callback methods.
  • How does the web server communicate to the servlet? Via container or Servlet engine.
  • Servlet lives and dies within a web container.
  • Web container is responsible for invoking methods in a servlets. It knows what callback methods the Servlet has.

Flow of Request

  • Client sends HTTP request to Web server
  • Web server forwards that HTTP request to web container.
  • Since Servlet can not understand HTTP, its a Java program, it only understands objects, so web container converts that request into valid request object
  • Web container spins a thread for each request
  • All the business logic goes inside doGet() or doPost() callback methods inside the servlets
  • Servlet builds a Java response object and sends it to the container. It converts that to HTTP response again to send it to the client

How does the Container know which Servlet client has requested for?

  • There’s a file called web.xml
  • This is the master file for a web container
  • You have information about servlet in this file-

    • servlets
      • Servlet-name
      • Servlet-class
    • servlet-mappings- the path like /Login or /Notifications is mapped here in
      • Servlet-name
      • url-pattern
    • and so on
  • Every servlet in the web app should have an entry into this file

  • So this lookup happens like- url-pattern -> servlet-name -> servlet-class

How to "install" Servlets? * Well, the servlet objects are inherited from the library- javax.servlet.* . Tomcat and Spring can be used to utilize these objects to fit the use case.

Ref- Watch this on 1.5x- https://www.youtube.com/watch?v=tkFRGdUgCsE . This has an awesome explanation.

Adding image inside table cell in HTML

Sould look like:

<td colspan ='4'><img src="\Pics\H.gif" alt="" border='3' height='100' width='100' /></td>

.

<td> need to be closed with </td> <img /> is (in most case) an empty tag. The closing tag is replacede by /> instead... like for br's

<br/>

Your html structure is plain worng (sorry), but this will probably turn into a really bad cross-brwoser compatibility. Also, Encapsulate the value of your attributes with quotes and avoid using upercase in tags.

In LaTeX, how can one add a header/footer in the document class Letter?

With regard to Brent.Longborough's answer (appering only on page 2 onward), perhaps you need to set the \thispagestyle{} after \begin{document}. I wonder if the letter class is setting the first page style to empty.

How to set the matplotlib figure default size in ipython notebook?

I believe the following work in version 0.11 and above. To check the version:

$ ipython --version

It may be worth adding this information to your question.

Solution:

You need to find the file ipython_notebook_config.py. Depending on your installation process this should be in somewhere like

.config/ipython/profile_default/ipython_notebook_config.py

where .config is in your home directory.

Once you have located this file find the following lines

# Subset of matplotlib rcParams that should be different for the inline backend.
# c.InlineBackend.rc = {'font.size': 10, 'figure.figsize': (6.0, 4.0), 'figure.facecolor': 'white', 'savefig.dpi': 72, 'figure.subplot.bottom': 0.125, 'figure.edgecolor': 'white'}

Uncomment this line c.InlineBack... and define your default figsize in the second dictionary entry.

Note that this could be done in a python script (and hence interactively in IPython) using

pylab.rcParams['figure.figsize'] = (10.0, 8.0)

How to alter a column and change the default value?

In case the above does not work for you (i.e.: you are working with new SQL or Azure) try the following:

1) drop existing column constraint (if any):

ALTER TABLE [table_name] DROP CONSTRAINT DF_my_constraint

2) create a new one:

ALTER TABLE [table_name] ADD CONSTRAINT DF_my_constraint  DEFAULT getdate() FOR column_name;

MAC addresses in JavaScript

No you cannot get the MAC address in JavaScript, mainly because the MAC address uniquely identifies the running computer so it would be a security vulnerability.

Now if all you need is a unique identifier, I suggest you create one yourself using some cryptographic algorithm and store it in a cookie.

If you really need to know the MAC address of the computer AND you are developing for internal applications, then I suggest you use an external component to do that: ActiveX for IE, XPCOM for Firefox (installed as an extension).

How to check if a String is numeric in Java

Java 8 lambda expressions.

String someString = "123123";
boolean isNumeric = someString.chars().allMatch( Character::isDigit );

Run/install/debug Android applications over Wi-Fi?

I wrote a shell script which can let you debug an Android device via Wi-Fi.

Here is the code:

#!/usr/bin/env bash
#Notice: if unable to connect to [ip]:5555,
#try adb kill-server then try again.

adb shell ip route > addrs.txt
#Case 1:Nexus 7
#192.168.88.0/23 dev wlan0  proto kernel  scope link  src 192.168.89.48

#Case 2: Smartsian T1,Huawei C8813
#default via 192.168.88.1 dev eth0  metric 30
#8.8.8.8 via 192.168.88.1 dev eth0  metric 30
#114.114.114.114 via 192.168.88.1 dev eth0  metric 30
#192.168.88.0/23 dev eth0  proto kernel  scope link  src 192.168.89.152  metric 30
#192.168.88.1 dev eth0  scope link  metric 30

ip_addrs=$(awk {'if( NF >=9){print $9;}'} addrs.txt)

echo "the device ip address is $ip_addrs"

echo "connecting..."

rm addrs.txt

adb tcpip 5555

adb connect "$ip_addrs"

Git submodule update

To update each submodule, you could invoke the following command (at the root of the repository):

git submodule -q foreach git pull -q origin master

You can remove the -q option to follow the whole process.

Web-scraping JavaScript page with Python

You'll want to use urllib, requests, beautifulSoup and selenium web driver in your script for different parts of the page, (to name a few).
Sometimes you'll get what you need with just one of these modules.
Sometimes you'll need two, three, or all of these modules.
Sometimes you'll need to switch off the js on your browser.
Sometimes you'll need header info in your script.
No websites can be scraped the same way and no website can be scraped in the same way forever without having to modify your crawler, usually after a few months. But they can all be scraped! Where there's a will there's a way for sure.
If you need scraped data continuously into the future just scrape everything you need and store it in .dat files with pickle.
Just keep searching how to try what with these modules and copying and pasting your errors into the Google.

How do I send a file in Android from a mobile device to server using http?

This can be done with a HTTP Post request to the server:

HttpClient http = AndroidHttpClient.newInstance("MyApp");
HttpPost method = new HttpPost("http://url-to-server");

method.setEntity(new FileEntity(new File("path-to-file"), "application/octet-stream"));

HttpResponse response = http.execute(method);

What does this expression language ${pageContext.request.contextPath} exactly do in JSP EL?

use request.getContextPath() instead of ${pageContext.request.contextPath} in JSP expression language.

<%
String contextPath = request.getContextPath();
%>
out.println(contextPath);

output: willPrintMyProjectcontextPath

show all tables in DB2 using the LIST command

To get a list of tables for the current database in DB2 -->

Connect to the database:

db2 connect to DATABASENAME user USER using PASSWORD

Run this query:

db2 LIST TABLES

This is the equivalent of SHOW TABLES in MySQL.

You may need to execute 'set schema myschema' to the correct schema before you run the list tables command. By default upon login your schema is the same as your username - which often won't contain any tables. You can use 'values current schema' to check what schema you're currently set to.

What exactly is an instance in Java?

The main differnece is when you say ClassName obj = null; you are just creating an object for that class. It's not an instance of that class.

This statement will just allot memory for the static meber variables, not for the normal member variables.

But when you say ClassName obj = new ClassName(); you are creating an instance of the class. This staement will allot memory all member variables.

How to delete multiple rows in SQL where id = (x to y)

If you need to delete based on a list, you can use IN:

DELETE FROM your_table
WHERE id IN (value1, value2, ...);

If you need to delete based on the result of a query, you can also use IN:

DELETE FROM your_table
WHERE id IN (select aColumn from ...);

(Notice that the subquery must return only one column)

If you need to delete based on a range of values, either you use BETWEEN or you use inequalities:

DELETE FROM your_table
WHERE id BETWEEN bottom_value AND top_value;

or

DELETE FROM your_table
WHERE id >= a_value AND id <= another_value;

How can I get the error message for the mail() function?

$e=error_get_last();
if($e['message']!==''){
    // An error function
}

error_get_last(); - return the last error that occurred

how to insert a new line character in a string to PrintStream then use a scanner to re-read the file

The linefeed character \n is not the line separator in certain operating systems (such as windows, where it's "\r\n") - my suggestion is that you use \r\n instead, then it'll both see the line-break with only \n and \r\n, I've never had any problems using it.

Also, you should look into using a StringBuilder instead of concatenating the String in the while-loop at BookCatalog.toString(), it is a lot more effective. For instance:

public String toString() {
        BookNode current = front;
        StringBuilder sb = new StringBuilder();
        while (current!=null){
            sb.append(current.getData().toString()+"\r\n ");
            current = current.getNext();
        }
        return sb.toString();
}

Commenting out a set of lines in a shell script

What if you just wrap your code into function?

So this:

cd ~/documents
mkdir test
echo "useless script" > about.txt

Becomes this:

CommentedOutBlock() {
  cd ~/documents
  mkdir test
  echo "useless script" > about.txt
}

ExecutorService that interrupts tasks after a timeout

It seems problem is not in JDK bug 6602600 ( it was solved at 2010-05-22), but in incorrect call of sleep(10) in circle. Addition note, that the main Thread must give directly CHANCE to other threads to realize thier tasks by invoke SLEEP(0) in EVERY branch of outer circle. It is better, I think, to use Thread.yield() instead of Thread.sleep(0)

The result corrected part of previous problem code is such like this:

.......................
........................
Thread.yield();         

if (i % 1000== 0) {
System.out.println(i + "/" + counter.get()+ "/"+service.toString());
}

//                
//                while (i > counter.get()) {
//                    Thread.sleep(10);
//                } 

It works correctly with amount of outer counter up to 150 000 000 tested circles.

Filter an array using a formula (without VBA)

This will do it if you only want the first "B" value, you can sub a cell address for "B" if you want to make it more generic.

=INDEX(A2:A6,SUMPRODUCT(MATCH(TRUE,(B2:B6)="B",0)),1)

To use this based on two columns, just concatenate inside the match:

=INDEX(A2:A6,SUMPRODUCT(MATCH(TRUE,(A2:A6&B2:B6)=("3"&"B"),0)),1)

Force DOM redraw/refresh on Chrome/Mac

Sample Html:

<section id="parent">
  <article class="child"></article>
  <article class="child"></article>
</section>

Js:

  jQuery.fn.redraw = function() {
        return this.hide(0,function() {$(this).show(100);});
        // hide immediately and show with 100ms duration

    };

call function:

$('article.child').redraw(); //<==bad idea

$('#parent').redraw();

git add only modified changes and ignore untracked files

To stage modified and deleted files

git add -u

Programmatically saving image to Django ImageField

Working! You can save image by using FileSystemStorage. check the example below

def upload_pic(request):
if request.method == 'POST' and request.FILES['photo']:
    photo = request.FILES['photo']
    name = request.FILES['photo'].name
    fs = FileSystemStorage()
##### you can update file saving location too by adding line below #####
    fs.base_location = fs.base_location+'/company_coverphotos'
##################
    filename = fs.save(name, photo)
    uploaded_file_url = fs.url(filename)+'/company_coverphotos'
    Profile.objects.filter(user=request.user).update(photo=photo)

execute function after complete page load

Put your script after the completion of body tag...it works...

What's the -practical- difference between a Bare and non-Bare repository?

This is not a new answer, but it helped me to understand the different aspects of the answers above (and it is too much for a comment).

Using Git Bash just try:

me@pc MINGW64 /c/Test
$ ls -al
total 16
drwxr-xr-x 1 myid 1049089 0 Apr  1 11:35 ./
drwxr-xr-x 1 myid 1049089 0 Apr  1 11:11 ../

me@pc MINGW64 /c/Test
$ git init
Initialized empty Git repository in C:/Test/.git/

me@pc MINGW64 /c/Test (master)
$ ls -al
total 20
drwxr-xr-x 1 myid 1049089 0 Apr  1 11:35 ./
drwxr-xr-x 1 myid 1049089 0 Apr  1 11:11 ../
drwxr-xr-x 1 myid 1049089 0 Apr  1 11:35 .git/

me@pc MINGW64 /c/Test (master)
$ cd .git

me@pc MINGW64 /c/Test/.git (GIT_DIR!)
$ ls -al
total 15
drwxr-xr-x 1 myid 1049089   0 Apr  1 11:35 ./
drwxr-xr-x 1 myid 1049089   0 Apr  1 11:35 ../
-rw-r--r-- 1 myid 1049089 130 Apr  1 11:35 config
-rw-r--r-- 1 myid 1049089  73 Apr  1 11:35 description
-rw-r--r-- 1 myid 1049089  23 Apr  1 11:35 HEAD
drwxr-xr-x 1 myid 1049089   0 Apr  1 11:35 hooks/
drwxr-xr-x 1 myid 1049089   0 Apr  1 11:35 info/
drwxr-xr-x 1 myid 1049089   0 Apr  1 11:35 objects/
drwxr-xr-x 1 myid 1049089   0 Apr  1 11:35 refs/

Same with git --bare:

me@pc MINGW64 /c/Test
$ ls -al
total 16
drwxr-xr-x 1 myid 1049089 0 Apr  1 11:36 ./
drwxr-xr-x 1 myid 1049089 0 Apr  1 11:11 ../

me@pc MINGW64 /c/Test
$ git init --bare
Initialized empty Git repository in C:/Test/

me@pc MINGW64 /c/Test (BARE:master)
$ ls -al
total 23
drwxr-xr-x 1 myid 1049089   0 Apr  1 11:36 ./
drwxr-xr-x 1 myid 1049089   0 Apr  1 11:11 ../
-rw-r--r-- 1 myid 1049089 104 Apr  1 11:36 config
-rw-r--r-- 1 myid 1049089  73 Apr  1 11:36 description
-rw-r--r-- 1 myid 1049089  23 Apr  1 11:36 HEAD
drwxr-xr-x 1 myid 1049089   0 Apr  1 11:36 hooks/
drwxr-xr-x 1 myid 1049089   0 Apr  1 11:36 info/
drwxr-xr-x 1 myid 1049089   0 Apr  1 11:36 objects/

Split column at delimiter in data frame

The newly popular tidyr package does this with separate. It uses regular expressions so you'll have to escape the |

df <- data.frame(ID=11:13, FOO=c('a|b', 'b|c', 'x|y'))
separate(data = df, col = FOO, into = c("left", "right"), sep = "\\|")

  ID left right
1 11    a     b
2 12    b     c
3 13    x     y

though in this case the defaults are smart enough to work (it looks for non-alphanumeric characters to split on).

separate(data = df, col = FOO, into = c("left", "right"))

ALTER DATABASE failed because a lock could not be placed on database

In rare cases (e.g., after a heavy transaction is commited) a running CHECKPOINT system process holding a FILE lock on the database file prevents transition to MULTI_USER mode.

Converting array to list in Java

If this helps: I've had the same problem and simply wrote a generic function that takes an array and returns an ArrayList of the same type with the same contents:

public static <T> ArrayList<T> ArrayToArrayList(T[] array) {
    ArrayList<T> list = new ArrayList<T>();
    for(T elmt : array) list.add(elmt);
    return list;
}

HTML/Javascript change div content

change onClick to onClick="changeDivContent(this)" and try

function changeDivContent(btn) {
  content.innerHTML = btn.value
}

_x000D_
_x000D_
function changeDivContent(btn) {_x000D_
  content.innerHTML = btn.value_x000D_
}
_x000D_
<input type="radio" name="radiobutton" value="A" onClick="changeDivContent(this)">_x000D_
<input type="radio" name="radiobutton" value="B" onClick="changeDivContent(this)">_x000D_
_x000D_
<div id="content"></div>
_x000D_
_x000D_
_x000D_

Appending a line break to an output file in a shell script

Try

echo -en "`date` User `whoami` started the script.\n" >> output.log

Try issuing this multiple times. I hope you are looking for the same output.

C++ Erase vector element by value rather than by position?

How about std::remove() instead:

#include <algorithm>
...
vec.erase(std::remove(vec.begin(), vec.end(), 8), vec.end());

This combination is also known as the erase-remove idiom.

Printing column separated by comma using Awk command line

A simple, although -less solution in :

while IFS=, read -r a a a b; do echo "$a"; done <inputfile

It works faster for small files (<100 lines) then as it uses less resources (avoids calling the expensive fork and execve system calls).

EDIT from Ed Morton (sorry for hi-jacking the answer, I don't know if there's a better way to address this):

To put to rest the myth that shell will run faster than awk for small files:

$ wc -l file
99 file

$ time while IFS=, read -r a a a b; do echo "$a"; done <file >/dev/null

real    0m0.016s
user    0m0.000s
sys     0m0.015s

$ time awk -F, '{print $3}' file >/dev/null

real    0m0.016s
user    0m0.000s
sys     0m0.015s

I expect if you get a REALY small enough file then you will see the shell script run in a fraction of a blink of an eye faster than the awk script but who cares?

And if you don't believe that it's harder to write robust shell scripts than awk scripts, look at this bug in the shell script you posted:

$ cat file
a,b,-e,d
$ cut -d, -f3 file
-e
$ awk -F, '{print $3}' file
-e
$ while IFS=, read -r a a a b; do echo "$a"; done <file

$

How to upgrade scikit-learn package in anaconda

Following Worked for me for scikit-learn on Anaconda-Jupyter Notebook.

Upgrading my scikit-learn from 0.19.1 to 0.19.2 in anaconda installed on Ubuntu on Google VM instance:

Run the following commands in the terminal:

First, check existing available packages with versions by using:

conda list    

It will show different packages and their installed versions in the output. Here check for scikit-learn. e.g. for me, the output was:

scikit-learn              0.19.1           py36hedc7406_0  

Now I want to Upgrade to 0.19.2 July 2018 release i.e. latest available version.

conda config --append channels conda-forge
conda install scikit-learn=0.19.2

As you are trying to upgrade to 0.17 version try the following command:

conda install scikit-learn=0.17

Now check the required version of the scikit-learn is installed correctly or not by using:

conda list 

For me the Output was:

scikit-learn              0.19.2          py36_blas_openblasha84fab4_201  [blas_openblas]  conda-forge

Note: Don't use pip command if you are using Anaconda or Miniconda

I tried following commands:

!conda update conda 
!pip install -U scikit-learn

It will install the required packages also will show in the conda list but if you try to import that package it will not work.

On the website http://scikit-learn.org/stable/install.html it is mentioned as: Warning To upgrade or uninstall scikit-learn installed with Anaconda or conda you should not use the pip.

Creating a dictionary from a CSV file

One-liner solution

import pandas as pd

dict = {row[0] : row[1] for _, row in pd.read_csv("file.csv").iterrows()}

How to make a new List in Java

Using Google Collections, you could use the following methods in the Lists class

import com.google.common.collect.Lists;

// ...

List<String> strings = Lists.newArrayList();

List<Integer> integers = Lists.newLinkedList();

There are overloads for varargs initialization and initialising from an Iterable<T>.

The advantage of these methods is that you don't need to specify the generic parameter explicitly as you would with the constructor - the compiler will infer it from the type of the variable.

git discard all changes and pull from upstream

You can do it in a single command:

git fetch --all && git reset --hard origin/master

Or in a pair of commands:

git fetch --all
git reset --hard origin/master

Note than you will lose ALL your local changes

AJAX jQuery refresh div every 5 seconds

you can use this one.

<div id="test"></div>

you java script code should be like that.

setInterval(function(){
      $('#test').load('test.php');
 },5000);

Why is Dictionary preferred over Hashtable in C#?

Another important difference is that Hashtable is thread safe. Hashtable has built-in multiple reader/single writer (MR/SW) thread safety which means Hashtable allows ONE writer together with multiple readers without locking.

In the case of Dictionary there is no thread safety; if you need thread safety you must implement your own synchronization.

To elaborate further:

Hashtable provides some thread-safety through the Synchronized property, which returns a thread-safe wrapper around the collection. The wrapper works by locking the entire collection on every add or remove operation. Therefore, each thread that is attempting to access the collection must wait for its turn to take the one lock. This is not scalable and can cause significant performance degradation for large collections. Also, the design is not completely protected from race conditions.

The .NET Framework 2.0 collection classes like List<T>, Dictionary<TKey, TValue>, etc. do not provide any thread synchronization; user code must provide all synchronization when items are added or removed on multiple threads concurrently

If you need type safety as well thread safety, use concurrent collections classes in the .NET Framework. Further reading here.

An additional difference is that when we add the multiple entries in Dictionary, the order in which the entries are added is maintained. When we retrieve the items from Dictionary we will get the records in the same order we have inserted them. Whereas Hashtable doesn't preserve the insertion order.

Option to ignore case with .contains method?

private boolean containsIgnoreCase(List<String> list, String soughtFor) {
    for (String current : list) {
        if (current.equalsIgnoreCase(soughtFor)) {
            return true;
        }
    }
    return false;
}

How to list all tags along with the full message in git?

It's far from pretty, but you could create a script or an alias that does something like this:

for c in $(git for-each-ref refs/tags/ --format='%(refname)'); do echo $c; git show --quiet "$c"; echo; done

How to exclude rows that don't join with another table?

If you want to select the columns from First Table "which are also present in Second table, then in this case you can also use EXCEPT. In this case, column names can be different as well but data type should be same.

Example:

select ID, FName
from FirstTable
EXCEPT
select ID, SName
from SecondTable

Why does Git tell me "No such remote 'origin'" when I try to push to origin?

I'm guessing you didn't run this command after the commit failed so just actually run this to create the remote :

 git remote add origin https://github.com/VijayNew/NewExample.git

And the commit failed because you need to git add some files you want to track.

Resource interpreted as Document but transferred with MIME type application/json warning in Chrome Developer Tools

This type of warnings are usually flagged because of the request HTTP headers. Specifically the Accept request header. The MDN documentation for HTTP headers states

The Accept request HTTP header advertises which content types, expressed as MIME types, the client is able to understand. Using content negotiation, the server then selects one of the proposals, uses it and informs the client of its choice with the Content-Type response header. Browsers set adequate values for this header depending of the context where the request is done....

application/json is probably not on the list of MIME types in the Accept header sent by the browser hence the warning.

Solution

Custom HTTP headers can only be sent programmatically via XMLHttpRequest or any of the js library wrappers implementing it.

How to see PL/SQL Stored Function body in Oracle

SELECT text 
FROM all_source
where name = 'FGETALGOGROUPKEY'
order by line

alternatively:

select dbms_metadata.get_ddl('FUNCTION', 'FGETALGOGROUPKEY')
from dual;

JS strings "+" vs concat method

You can try with this code (Same case)

chaine1 + chaine2; 

I suggest you also (I prefer this) the string.concat method

How do you clear your Visual Studio cache on Windows Vista?

The accepted answer gave two locations:

here

C:\Documents and Settings\Administrator\Local Settings\Temp\VWDWebCache

and possibly here

C:\Documents and Settings\Administrator\Local Settings\Application Data\Microsoft\WebsiteCache

Did you try those?

Edited to add

On my Windows Vista machine, it's located in

%Temp%\VWDWebCache

and in

%LocalAppData%\Microsoft\WebsiteCache

From your additional information (regarding team edition) this comes from Clear Client TFS Cache:

Clear Client TFS Cache

Visual Studio and Team Explorer provide a caching mechanism which can get out of sync. If I have multiple instances of a single TFS which can be connected to from a single Visual Studio client, that client can become confused.

To solve it..

For Windows Vista delete contents of this folder

%LocalAppData%\Microsoft\Team Foundation\1.0\Cache

Take screenshots in the iOS simulator

Press ?S or go to File > Save screenshot from your simulator menu and you will get the screenshot saved on your desktop.

Show and hide divs at a specific time interval using jQuery

Loop through divs every 10 seconds.

$(function () {

    var counter = 0,
        divs = $('#div1, #div2, #div3');

    function showDiv () {
        divs.hide() // hide all divs
            .filter(function (index) { return index == counter % 3; }) // figure out correct div to show
            .show('fast'); // and show it

        counter++;
    }; // function to loop through divs and show correct div

    showDiv(); // show first div    

    setInterval(function () {
        showDiv(); // show next div
    }, 10 * 1000); // do this every 10 seconds    

});

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

You can do it with:

UPDATE mytable SET Total = Pieces * Price;

Display names of all constraints for a table in Oracle SQL

Use either of the two commands below. Everything must be in uppercase. The table name must be wrapped in quotation marks:

--SEE THE CONSTRAINTS ON A TABLE
SELECT COLUMN_NAME, CONSTRAINT_NAME FROM USER_CONS_COLUMNS WHERE TABLE_NAME = 'TBL_CUSTOMER';

--OR FOR LESS DETAIL
SELECT CONSTRAINT_NAME FROM USER_CONSTRAINTS WHERE TABLE_NAME = 'TBL_CUSTOMER';

System.Threading.Timer in C# it seems to be not working. It runs very fast every 3 second

I would just do:

private static Timer timer;
 private static void Main()
 {
   timer = new Timer(_ => OnCallBack(), null, 1000 * 10,Timeout.Infinite); //in 10 seconds
   Console.ReadLine();
 }

  private static void OnCallBack()
  {
    timer.Dispose();
    Thread.Sleep(3000); //doing some long operation
    timer = new Timer(_ => OnCallBack(), null, 1000 * 10,Timeout.Infinite); //in 10 seconds
  }

And ignore the period parameter, since you're attempting to control the periodicy yourself.


Your original code is running as fast as possible, since you keep specifying 0 for the dueTime parameter. From Timer.Change:

If dueTime is zero (0), the callback method is invoked immediately.

Using Spring RestTemplate in generic method with generic parameter

I have another way to do this... suppose you swap out your message converter to String for your RestTemplate, then you can receive raw JSON. Using the raw JSON, you can then map it into your Generic Collection using a Jackson Object Mapper. Here's how:

Swap out the message converter:

    List<HttpMessageConverter<?>> oldConverters = new ArrayList<HttpMessageConverter<?>>();
    oldConverters.addAll(template.getMessageConverters());

    List<HttpMessageConverter<?>> stringConverter = new ArrayList<HttpMessageConverter<?>>();
    stringConverter.add(new StringHttpMessageConverter());

    template.setMessageConverters(stringConverter);

Then get your JSON response like this:

    ResponseEntity<String> response = template.exchange(uri, HttpMethod.GET, null, String.class);

Process the response like this:

     String body = null;
     List<T> result = new ArrayList<T>();
     ObjectMapper mapper = new ObjectMapper();

     if (response.hasBody()) {
        body = items.getBody();
        try {
            result = mapper.readValue(body, mapper.getTypeFactory().constructCollectionType(List.class, clazz));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            template.setMessageConverters(oldConverters);
        }
        ...

Bootstrap get div to align in the center

In bootstrap you can use .text-centerto align center. also add .row and .col-md-* to your code.

align= is deprecated,

Added .col-xs-* for demo

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<div class="footer">
  <div class="container">
    <div class="row">
      <div class="col-xs-4">
        <p>Hello there</p>
      </div>
      <div class="col-xs-4 text-center">
        <a href="#" class="btn btn-warning" onclick="changeLook()">Re</a>
        <a href="#" class="btn btn-warning" onclick="changeBack()">Rs</a>
      </div>
      <div class="col-xs-4 text-right">
        <a href="#"><i class="fa fa-facebook-square fa-2x"></i></a>
        <a href="#"><i class="fa fa-twitter fa-2x"></i></a>
        <a href="#"><i class="fa fa-google-plus fa-2x"></i></a>
      </div>
    </div>
  </div>
</div>
_x000D_
_x000D_
_x000D_

UPDATE(OCT 2017)

For those who are reading this and want to use the new version of bootstrap (beta version), you can do the above in a simpler way, using Boostrap Flexbox utilities classes

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<div class="container footer">
  <div class="d-flex justify-content-between">
    <div class="p-1">
      <p>Hello there</p>
    </div>
    <div class="p-1">
      <a href="#" class="btn btn-warning" onclick="changeLook()">Re</a>
      <a href="#" class="btn btn-warning" onclick="changeBack()">Rs</a>
    </div>
    <div class="p-1">
      <a href="#"><i class="fa fa-facebook-square fa-2x"></i></a>
      <a href="#"><i class="fa fa-twitter fa-2x"></i></a>
      <a href="#"><i class="fa fa-google-plus fa-2x"></i></a>
    </div>
  </div>
</div>
_x000D_
_x000D_
_x000D_

Pure JavaScript: a function like jQuery's isNumeric()

There is Javascript function isNaN which will do that.

isNaN(90)
=>false

so you can check numeric by

!isNaN(90)
=>true

segmentation fault : 11

Your array is occupying roughly 8 GB of memory (1,000 x 1,000,000 x sizeof(double) bytes). That might be a factor in your problem. It is a global variable rather than a stack variable, so you may be OK, but you're pushing limits here.

Writing that much data to a file is going to take a while.

You don't check that the file was opened successfully, which could be a source of trouble, too (if it did fail, a segmentation fault is very likely).

You really should introduce some named constants for 1,000 and 1,000,000; what do they represent?

You should also write a function to do the calculation; you could use an inline function in C99 or later (or C++). The repetition in the code is excruciating to behold.

You should also use C99 notation for main(), with the explicit return type (and preferably void for the argument list when you are not using argc or argv):

int main(void)

Out of idle curiosity, I took a copy of your code, changed all occurrences of 1000 to ROWS, all occurrences of 1000000 to COLS, and then created enum { ROWS = 1000, COLS = 10000 }; (thereby reducing the problem size by a factor of 100). I made a few minor changes so it would compile cleanly under my preferred set of compilation options (nothing serious: static in front of the functions, and the main array; file becomes a local to main; error check the fopen(), etc.).

I then created a second copy and created an inline function to do the repeated calculation, (and a second one to do subscript calculations). This means that the monstrous expression is only written out once — which is highly desirable as it ensure consistency.

#include <stdio.h>

#define   lambda   2.0
#define   g        1.0
#define   F0       1.0
#define   h        0.1
#define   e        0.00001

enum { ROWS = 1000, COLS = 10000 };

static double F[ROWS][COLS];

static void Inicio(double D[ROWS][COLS])
{
    for (int i = 399; i < 600; i++) // Magic numbers!!
        D[i][0] = F0;
}

enum { R = ROWS - 1 };

static inline int ko(int k, int n)
{
    int rv = k + n;
    if (rv >= R)
        rv -= R;
    else if (rv < 0)
        rv += R;
    return(rv);
}

static inline void calculate_value(int i, int k, double A[ROWS][COLS])
{
    int ks2 = ko(k, -2);
    int ks1 = ko(k, -1);
    int kp1 = ko(k, +1);
    int kp2 = ko(k, +2);

    A[k][i] = A[k][i-1]
            + e/(h*h*h*h) * g*g * (A[kp2][i-1] - 4.0*A[kp1][i-1] + 6.0*A[k][i-1] - 4.0*A[ks1][i-1] + A[ks2][i-1])
            + 2.0*g*e/(h*h) * (A[kp1][i-1] - 2*A[k][i-1] + A[ks1][i-1])
            + e * A[k][i-1] * (lambda - A[k][i-1] * A[k][i-1]);
}

static void Iteration(double A[ROWS][COLS])
{
    for (int i = 1; i < COLS; i++)
    {
        for (int k = 0; k < R; k++)
            calculate_value(i, k, A);
        A[999][i] = A[0][i];
    }
}

int main(void)
{
    FILE *file = fopen("P2.txt","wt");
    if (file == 0)
        return(1);
    Inicio(F);
    Iteration(F);
    for (int i = 0; i < COLS; i++)
    {
        for (int j = 0; j < ROWS; j++)
        {
            fprintf(file,"%lf \t %.4f \t %lf\n", 1.0*j/10.0, 1.0*i, F[j][i]);
        }
    }
    fclose(file);
    return(0);
}

This program writes to P2.txt instead of P1.txt. I ran both programs and compared the output files; the output was identical. When I ran the programs on a mostly idle machine (MacBook Pro, 2.3 GHz Intel Core i7, 16 GiB 1333 MHz RAM, Mac OS X 10.7.5, GCC 4.7.1), I got reasonably but not wholly consistent timing:

Original   Modified
6.334s      6.367s
6.241s      6.231s
6.315s     10.778s
6.378s      6.320s
6.388s      6.293s
6.285s      6.268s
6.387s     10.954s
6.377s      6.227s
8.888s      6.347s
6.304s      6.286s
6.258s     10.302s
6.975s      6.260s
6.663s      6.847s
6.359s      6.313s
6.344s      6.335s
7.762s      6.533s
6.310s      9.418s
8.972s      6.370s
6.383s      6.357s

However, almost all that time is spent on disk I/O. I reduced the disk I/O to just the very last row of data, so the outer I/O for loop became:

for (int i = COLS - 1; i < COLS; i++)

the timings were vastly reduced and very much more consistent:

Original    Modified
0.168s      0.165s
0.145s      0.165s
0.165s      0.166s
0.164s      0.163s
0.151s      0.151s
0.148s      0.153s
0.152s      0.171s
0.165s      0.165s
0.173s      0.176s
0.171s      0.165s
0.151s      0.169s

The simplification in the code from having the ghastly expression written out just once is very beneficial, it seems to me. I'd certainly far rather have to maintain that program than the original.

How to use the pass statement?

If you want to import a module, if it exists, and ignore importing it, if that module does not exists, you can use the below code:

try:
    import a_module
except ImportError:
    pass
#rest of your code

If you avoid writing the pass statement and continue writing the rest of your code, a IndentationError would be raised, since the lines after opening the except block are not indented

CSS selector for "foo that contains bar"?

Only thing that comes even close is the :contains pseudo class in CSS3, but that only selects textual content, not tags or elements, so you're out of luck.

A simpler way to select a parent with specific children in jQuery can be written as (with :has()):

$('#parent:has(#child)');

Get Maven artifact version at runtime

Here's a method for getting the version from the pom.properties, falling back to getting it from the manifest

public synchronized String getVersion() {
    String version = null;

    // try to load from maven properties first
    try {
        Properties p = new Properties();
        InputStream is = getClass().getResourceAsStream("/META-INF/maven/com.my.group/my-artefact/pom.properties");
        if (is != null) {
            p.load(is);
            version = p.getProperty("version", "");
        }
    } catch (Exception e) {
        // ignore
    }

    // fallback to using Java API
    if (version == null) {
        Package aPackage = getClass().getPackage();
        if (aPackage != null) {
            version = aPackage.getImplementationVersion();
            if (version == null) {
                version = aPackage.getSpecificationVersion();
            }
        }
    }

    if (version == null) {
        // we could not compute the version so use a blank
        version = "";
    }

    return version;
} 

Find current directory and file's directory

If you're using Python 3.4, there is the brand new higher-level pathlib module which allows you to conveniently call pathlib.Path.cwd() to get a Path object representing your current working directory, along with many other new features.

More info on this new API can be found here.

Sleeping in a batch file

The best solution that should work on all Windows versions after Windows 2000 would be:

timeout numbersofseconds /nobreak > nul

List tables in a PostgreSQL schema

You can select the tables from information_schema

SELECT * FROM information_schema.tables 
WHERE table_schema = 'public'

What does "Could not find or load main class" mean?

I had same problem and finally found my mistake :) I used this command for compiling and it worked correctly:

javac -cp "/home/omidmohebbi/AAAATest/jars/core-1.7.jar:/home/omidmohebbi/AAAATest/jars/javase-1.7.jar:/home/omidmohebbi/AAAATest/jars/qrgen-1.2.jar" qrcode.java

But this command did not work for me (I could not find or load the main class, qrcode):

java -cp "/home/omidmohebbi/AAAATest/jars/core-1.7.jar:/home/omidmohebbi/AAAATest/jars/javase-1.7.jar:/home/omidmohebbi/AAAATest/jars/qrgen-1.2.jar" qrcode

Finally I just added the ':' character at end of the classpath and the problem was solved:

java -cp "/home/omidmohebbi/AAAATest/jars/core-1.7.jar:/home/omidmohebbi/AAAATest/jars/javase-1.7.jar:/home/omidmohebbi/AAAATest/jars/qrgen-1.2.jar:" qrcode

How to calculate age in T-SQL with years, months, and days

declare @StartDate datetime = '2016-01-31'
declare @EndDate datetime = '2016-02-01'
SELECT @StartDate AS [StartDate]
      ,@EndDate AS [EndDate]
      ,DATEDIFF(Year,@StartDate,@EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate), @StartDate) > @EndDate THEN 1 ELSE 0 END AS [Years]
      ,DATEDIFF(Month,(DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate), @StartDate) > @EndDate THEN 1 ELSE 0 END,@StartDate)),@EndDate) - CASE WHEN DATEADD(Month, DATEDIFF(Month,DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate), @StartDate) > @EndDate THEN 1 ELSE 0 END,@StartDate),@EndDate) , @StartDate) > @EndDate THEN 1 ELSE 0 END AS [Months]
      ,DATEDIFF(Day, DATEADD(Month,DATEDIFF(Month, (DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate), @StartDate) > @EndDate THEN 1 ELSE 0 END,@StartDate)),@EndDate) - CASE WHEN DATEADD(Month, DATEDIFF(Month,DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate), @StartDate) > @EndDate THEN 1 ELSE 0 END,@StartDate),@EndDate) , @StartDate) > @EndDate THEN 1 ELSE 0 END  ,DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate), @StartDate) > @EndDate THEN 1 ELSE 0 END,@StartDate)) ,@EndDate) - CASE WHEN DATEADD(Day,DATEDIFF(Day, DATEADD(Month,DATEDIFF(Month, (DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate), @StartDate) > @EndDate THEN 1 ELSE 0 END,@StartDate)),@EndDate) - CASE WHEN DATEADD(Month, DATEDIFF(Month,DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate), @StartDate) > @EndDate THEN 1 ELSE 0 END,@StartDate),@EndDate) , @StartDate) > @EndDate THEN 1 ELSE 0 END  ,DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate), @StartDate) > @EndDate THEN 1 ELSE 0 END,@StartDate)) ,@EndDate),DATEADD(Month,DATEDIFF(Month, (DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate), @StartDate) > @EndDate THEN 1 ELSE 0 END,@StartDate)),@EndDate) - CASE WHEN DATEADD(Month, DATEDIFF(Month,DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate), @StartDate) > @EndDate THEN 1 ELSE 0 END,@StartDate),@EndDate) , @StartDate) > @EndDate THEN 1 ELSE 0 END  ,DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate), @StartDate) > @EndDate THEN 1 ELSE 0 END,@StartDate))) > @EndDate THEN 1 ELSE 0 END AS [Days]

Calculating Page Table Size

Suppose logical address space is **32 bit so total possible logical entries will be 2^32 and other hand suppose each page size is 4 byte then size of one page is *2^2*2^10=2^12...* now we know that no. of pages in page table is pages=total possible logical address entries/page size so pages=2^32/2^12 =2^20 Now suppose that each entry in page table takes 4 bytes then total size of page table in *physical memory will be=2^2*2^20=2^22=4mb***

How to check Elasticsearch cluster health?

To check on elasticsearch cluster health you need to use

curl localhost:9200/_cat/health

More on the cat APIs here.

I usually use elasticsearch-head plugin to visualize that.

You can find it's github project here.

It's easy to install sudo $ES_HOME/bin/plugin -i mobz/elasticsearch-head and then you can open localhost:9200/_plugin/head/ in your web brower.

You should have something that looks like this :

enter image description here

on change event for file input element

Use the files filelist of the element instead of val()

$("input[type=file]").on('change',function(){
    alert(this.files[0].name);
});

How to pass multiple arguments in processStartInfo?

It is purely a string:

startInfo.Arguments = "-sk server -sky exchange -pe -n CN=localhost -ir LocalMachine -is Root -ic MyCA.cer -sr LocalMachine -ss My MyAdHocTestCert.cer"

Of course, when arguments contain whitespaces you'll have to escape them using \" \", like:

"... -ss \"My MyAdHocTestCert.cer\""

See MSDN for this.

Convert HTML Character Back to Text Using Java Standard Library

I think the Apache Commons Lang library's StringEscapeUtils.unescapeHtml3() and unescapeHtml4() methods are what you are looking for. See https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/StringEscapeUtils.html.

Twitter Bootstrap Use collapse.js on table cells [Almost Done]

I'm not sure you have gotten past this yet, but I had to work on something very similar today and I got your fiddle working like you are asking, basically what I did was make another table row under it, and then used the accordion control. I tried using just collapse but could not get it working and saw an example somewhere on SO that used accordion.

Here's your updated fiddle: http://jsfiddle.net/whytheday/2Dj7Y/11/

Since I need to post code here is what each collapsible "section" should look like ->

<tr data-toggle="collapse" data-target="#demo1" class="accordion-toggle">
    <td>1</td>
    <td>05 May 2013</td>
    <td>Credit Account</td>
    <td class="text-success">$150.00</td>
    <td class="text-error"></td>
    <td class="text-success">$150.00</td>
</tr>

<tr>
    <td colspan="6" class="hiddenRow">
        <div class="accordion-body collapse" id="demo1">Demo1</div>
    </td>
</tr>

Download and save PDF file with Python requests module

regarding Kevin answer to write in a folder tmp, it should be like this:

with open('./tmp/metadata.pdf', 'wb') as f:
    f.write(response.content)

he forgot . before the address and of-course your folder tmp should have been created already

reading from app.config file

Try:

string value = ConfigurationManager.AppSettings[key];

For more details check: Reading Keys from App.Config

How can I compare two strings in java and define which of them is smaller than the other alphabetically?

You can use

str1.compareTo(str2);

If str1 is lexicographically less than str2, a negative number will be returned, 0 if equal or a positive number if str1 is greater.

E.g.,

"a".compareTo("b"); // returns a negative number, here -1
"a".compareTo("a"); // returns  0
"b".compareTo("a"); // returns a positive number, here 1
"b".compareTo(null); // throws java.lang.NullPointerException

Best way to concatenate List of String objects?

Have you seen this Coding Horror blog entry?

The Sad Tragedy of Micro-Optimization Theater

I am not shure whether or not it is "neater", but from a performance-standpoint it probably won't matter much.

How to check file MIME type with javascript before upload?

Here is an extension of Roberto14's answer that does the following:

THIS WILL ONLY ALLOW IMAGES

Checks if FileReader is available and falls back to extension checking if it is not available.

Gives an error alert if not an image

If it is an image it loads a preview

** You should still do server side validation, this is more a convenience for the end user than anything else. But it is handy!

<form id="myform">
    <input type="file" id="myimage" onchange="readURL(this)" />
    <img id="preview" src="#" alt="Image Preview" />
</form>

<script>
function readURL(input) {
    if (window.FileReader && window.Blob) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            reader.onload = function (e) {
                var img = new Image();
                img.onload = function() {
                    var preview = document.getElementById('preview');
                    preview.src = e.target.result;
                    };
                img.onerror = function() { 
                    alert('error');
                    input.value = '';
                    };
                img.src = e.target.result;
                }
            reader.readAsDataURL(input.files[0]);
            }
        }
    else {
        var ext = input.value.split('.');
        ext = ext[ext.length-1].toLowerCase();      
        var arrayExtensions = ['jpg' , 'jpeg', 'png', 'bmp', 'gif'];
        if (arrayExtensions.lastIndexOf(ext) == -1) {
            alert('error');
            input.value = '';
            }
        else {
            var preview = document.getElementById('preview');
            preview.setAttribute('alt', 'Browser does not support preview.');
            }
        }
    }
</script>

Removing unwanted table cell borders with CSS

Modify your HTML like this:

<table border="0" cellpadding="0" cellspacing="0">
    <thead>
        <tr><td>1</td><td>2</td><td>3</td></tr>
     </thead>
    <tbody>
        <tr><td>a</td><td>b></td><td>c</td></tr>
        <tr class='odd'><td>x</td><td>y</td><td>z</td></tr>
    </tbody>
</table>

(I added border="0" cellpadding="0" cellspacing="0")

In CSS, you could do the following:

table {
    border-collapse: collapse;
}

How to determine device screen size category (small, normal, large, xlarge) using code?

Thanks for the answers above, that helped me a lot :-) But for those (like me) forced to still support Android 1.5 we can use java reflection for backward compatible:

Configuration conf = getResources().getConfiguration();
int screenLayout = 1; // application default behavior
try {
    Field field = conf.getClass().getDeclaredField("screenLayout");
    screenLayout = field.getInt(conf);
} catch (Exception e) {
    // NoSuchFieldException or related stuff
}
// Configuration.SCREENLAYOUT_SIZE_MASK == 15
int screenType = screenLayout & 15;
// Configuration.SCREENLAYOUT_SIZE_SMALL == 1
// Configuration.SCREENLAYOUT_SIZE_NORMAL == 2
// Configuration.SCREENLAYOUT_SIZE_LARGE == 3
// Configuration.SCREENLAYOUT_SIZE_XLARGE == 4
if (screenType == 1) {
    ...
} else if (screenType == 2) {
    ...
} else if (screenType == 3) {
    ...
} else if (screenType == 4) {
    ...
} else { // undefined
    ...
}

Plot two graphs in same plot in R

we can also use lattice library

library(lattice)
x <- seq(-2,2,0.05)
y1 <- pnorm(x)
y2 <- pnorm(x,1,1)
xyplot(y1 + y2 ~ x, ylab = "y1 and y2", type = "l", auto.key = list(points = FALSE,lines = TRUE))

For specific colors

xyplot(y1 + y2 ~ x,ylab = "y1 and y2", type = "l", auto.key = list(points = F,lines = T), par.settings = list(superpose.line = list(col = c("red","green"))))

enter image description here

Check if a string contains an element from a list (of strings)

Have you tested the speed?

i.e. Have you created a sample set of data and profiled it? It may not be as bad as you think.

This might also be something you could spawn off into a separate thread and give the illusion of speed!

ip address validation in python using regex

Why not use a library function to validate the ip address?

>>> ip="241.1.1.112343434" 
>>> socket.inet_aton(ip)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
socket.error: illegal IP address string passed to inet_aton

How to convert unsigned long to string

you can write a function which converts from unsigned long to str, similar to ltostr library function.

char *ultostr(unsigned long value, char *ptr, int base)
{
  unsigned long t = 0, res = 0;
  unsigned long tmp = value;
  int count = 0;

  if (NULL == ptr)
  {
    return NULL;
  }

  if (tmp == 0)
  {
    count++;
  }

  while(tmp > 0)
  {
    tmp = tmp/base;
    count++;
  }

  ptr += count;

  *ptr = '\0';

  do
  {
    res = value - base * (t = value / base);
    if (res < 10)
    {
      * -- ptr = '0' + res;
    }
    else if ((res >= 10) && (res < 16))
    {
        * --ptr = 'A' - 10 + res;
    }
  } while ((value = t) != 0);

  return(ptr);
}

you can refer to my blog here which explains implementation and usage with example.

How to add option to select list in jQuery

Doing it this way has always worked for me, I hope this helps.

var ddl = $("#dropListBuilding");   
for (k = 0; k < buildings.length; k++)
   ddl.append("<option value='" + buildings[k]+ "'>" + buildings[k] + "</option>");

Check if the file exists using VBA

I'm not certain what's wrong with your code specifically, but I use this function I found online (URL in the comments) for checking if a file exists:

Private Function File_Exists(ByVal sPathName As String, Optional Directory As Boolean) As Boolean
    'Code from internet: http://vbadud.blogspot.com/2007/04/vba-function-to-check-file-existence.html
    'Returns True if the passed sPathName exist
    'Otherwise returns False
    On Error Resume Next
    If sPathName <> "" Then

        If IsMissing(Directory) Or Directory = False Then

            File_Exists = (Dir$(sPathName) <> "")
        Else

            File_Exists = (Dir$(sPathName, vbDirectory) <> "")
        End If

    End If
End Function

How can I declare and use Boolean variables in a shell script?

My receipe to (my own) idiocy:

# setting ----------------
commonMode=false
if [[ $something == 'COMMON' ]]; then
    commonMode=true
fi

# using ----------------
if $commonMode; then
    echo 'YES, Common Mode'
else
    echo 'NO, no Common Mode'
fi

$commonMode && echo 'commonMode is ON  ++++++'
$commonMode || echo 'commonMode is OFF xxxxxx'

How can I set the form action through JavaScript?

You cannot invoke JavaScript functions in standard HTML attributes other than onXXX. Just assign it during window onload.

<script type="text/javascript">
    window.onload = function() {
        document.myform.action = get_action();
    }

    function get_action() {
        return form_action;
    }
</script>

<form name="myform">
    ...
</form>

You see that I've given the form a name, so that it's easily accessible in document.

Alternatively, you can also do it during submit event:

<script type="text/javascript">
    function get_action(form) {
        form.action = form_action;
    }
</script>

<form onsubmit="get_action(this);">
    ...
</form>

Can I pass column name as input parameter in SQL stored Procedure

Please Try with this. I hope it will work for you.

Create Procedure Test
(
    @Table VARCHAR(500),
    @Column VARCHAR(100),
    @Value  VARCHAR(300)
)
AS
BEGIN

DECLARE @sql nvarchar(1000)

SET @sql = 'SELECT * FROM ' + @Table + ' WHERE ' + @Column + ' = ' + @Value

--SELECT @sql
exec (@sql)

END

-----execution----

/** Exec Test Products,IsDeposit,1 **/

IE9 jQuery AJAX with CORS returns "Access is denied"

Building on the solution by MoonScript, you could try this instead:

https://github.com/intuit/xhr-xdr-adapter/blob/master/src/xhr-xdr-adapter.js

The benefit is that since it's a lower level solution, it will enable CORS (to the extent possible) on IE 8/9 with other frameworks, not just with jQuery. I've had success using it with AngularJS, as well as jQuery 1.x and 2.x.

How do I set log4j level on the command line?

Based on @lijat, here is a simplified implementation. In my spring-based application I simply load this as a bean.

public static void configureLog4jFromSystemProperties()
{
  final String LOGGER_PREFIX = "log4j.logger.";

  for(String propertyName : System.getProperties().stringPropertyNames())
  {
    if (propertyName.startsWith(LOGGER_PREFIX)) {
      String loggerName = propertyName.substring(LOGGER_PREFIX.length());
      String levelName = System.getProperty(propertyName, "");
      Level level = Level.toLevel(levelName); // defaults to DEBUG
      if (!"".equals(levelName) && !levelName.toUpperCase().equals(level.toString())) {
        logger.error("Skipping unrecognized log4j log level " + levelName + ": -D" + propertyName + "=" + levelName);
        continue;
      }
      logger.info("Setting " + loggerName + " => " + level.toString());
      Logger.getLogger(loggerName).setLevel(level);
    }
  }
}

Is False == 0 and True == 1 an implementation detail or is it guaranteed by the language?

In Python 2.x this is not guaranteed as it is possible for True and False to be reassigned. However, even if this happens, boolean True and boolean False are still properly returned for comparisons.

In Python 3.x True and False are keywords and will always be equal to 1 and 0.

Under normal circumstances in Python 2, and always in Python 3:

False object is of type bool which is a subclass of int:

object
   |
 int
   |
 bool

It is the only reason why in your example, ['zero', 'one'][False] does work. It would not work with an object which is not a subclass of integer, because list indexing only works with integers, or objects that define a __index__ method (thanks mark-dickinson).

Edit:

It is true of the current python version, and of that of Python 3. The docs for python 2 and the docs for Python 3 both say:

There are two types of integers: [...] Integers (int) [...] Booleans (bool)

and in the boolean subsection:

Booleans: These represent the truth values False and True [...] Boolean values behave like the values 0 and 1, respectively, in almost all contexts, the exception being that when converted to a string, the strings "False" or "True" are returned, respectively.

There is also, for Python 2:

In numeric contexts (for example when used as the argument to an arithmetic operator), they [False and True] behave like the integers 0 and 1, respectively.

So booleans are explicitly considered as integers in Python 2 and 3.

So you're safe until Python 4 comes along. ;-)

WordPress - Check if user is logged in

get_current_user_id() will return the current user id (an integer), or will return 0 if the user is not logged in.

if (get_current_user_id()) {
   // display navbar here
}

More details here get_current_user_id().

How does a hash table work?

For all those looking for programming parlance, here is how it works. Internal implementation of advanced hashtables has many intricacies and optimisations for storage allocation/deallocation and search, but top-level idea will be very much the same.

(void) addValue : (object) value
{
   int bucket = calculate_bucket_from_val(value);
   if (bucket) 
   {
       //do nothing, just overwrite
   }
   else   //create bucket
   {
      create_extra_space_for_bucket();
   }
   put_value_into_bucket(bucket,value);
}

(bool) exists : (object) value
{
   int bucket = calculate_bucket_from_val(value);
   return bucket;
}

where calculate_bucket_from_val() is the hashing function where all the uniqueness magic must happen.

The rule of thumb is: For a given value to be inserted, bucket must be UNIQUE & DERIVABLE FROM THE VALUE that it is supposed to STORE.

Bucket is any space where the values are stored - for here I have kept it int as an array index, but it maybe a memory location as well.

Add/remove class with jquery based on vertical scroll?

Add some transition effect to it if you like:

http://jsbin.com/boreme/17/edit?html,css,js

.clearHeader {
  height:50px;
  background:lightblue;
  position:fixed;
  top:0;
  left:0;
  width:100%;

  -webkit-transition: background 2s; /* For Safari 3.1 to 6.0 */
  transition: background 2s;
}

.clearHeader.darkHeader {
 background:#000;
}

Moment.js with Vuejs

With your code, the vue.js is trying to access the moment() method from its scope.

Hence you should use a method like this:

methods: {
  moment: function () {
    return moment();
  }
},

If you want to pass a date to the moment.js, I suggest to use filters:

filters: {
  moment: function (date) {
    return moment(date).format('MMMM Do YYYY, h:mm:ss a');
  }
}

<span>{{ date | moment }}</span>

[demo]

Multiple line comment in Python

#Single line

'''
multi-line
comment
'''

"""
also, 
multi-line comment
"""

Excel concatenation quotes

Try this:

CONCATENATE(""""; B2 ;"""")

@widor provided a nice solution alternative too - integrated with mine:

CONCATENATE(char(34); B2 ;char(34))

What characters can be used for up/down triangle (arrow without stem) for display in HTML?

This one seems to imply that 030 and 031 are up and down triangles.

(As bobince pointed out, this doesn't seem to be an ASCII standard)

Setting Short Value Java

There is no such thing as a byte or short literal. You need to cast to short using (short)100

Playing MP4 files in Firefox using HTML5 video

I can confirm that mp4 just will not work in the video tag. No matter how much you try to mess with the type tag and the codec and the mime types from the server.

Crazy, because for the same exact video, on the same test page, the old embed tag for an mp4 works just fine in firefox. I spent all yesterday messing with this. Firefox is like IE all of a sudden, hours and hours of time, not billable. Yay.

Speaking of IE, it fails FAR MORE gracefully on this. When it can't match up the format it falls to the content between the tags, so it is possible to just put video around object around embed and everything works great. Firefox, nope, despite failing, it puts up the poster image (greyed out so that isn't even useful as a fallback) with an error message smack in the middle. So now the options are put in browser recognition code (meaning we've gained nothing on embedding videos in the last ten years) or ditch html5.

How can I issue a single command from the command line through sql plus?

Have you tried something like this?

sqlplus username/password@database < "EXECUTE some_proc /"

Seems like in UNIX you can do:

sqlplus username/password@database <<EOF
EXECUTE some_proc;
EXIT;
EOF

But I'm not sure what the windows equivalent of that would be.

Why am I seeing "TypeError: string indices must be integers"?

item is most likely a string in your code; the string indices are the ones in the square brackets, e.g., gravatar_id. So I'd first check your data variable to see what you received there; I guess that data is a list of strings (or at least a list containing at least one string) while it should be a list of dictionaries.

TSQL select into Temp table from dynamic sql

A working example.

DECLARE @TableName AS VARCHAR(100)
SELECT @TableName = 'YourTableName'

EXECUTE ('SELECT * INTO #TEMP  FROM ' + @TableName +'; SELECT * FROM #TEMP;')

Second solution with accessible temp table

DECLARE @TableName AS VARCHAR(100)
SELECT @TableName = 'YOUR_TABLE_NAME'

EXECUTE ('CREATE VIEW vTemp AS
        SELECT *
        FROM ' + @TableName)
SELECT * INTO #TEMP  FROM vTemp 

--DROP THE VIEW HERE      
DROP VIEW vTemp

/*START USING TEMP TABLE
************************/
--EX:
SELECT * FROM #TEMP


--DROP YOUR TEMP TABLE HERE
DROP TABLE #TEMP

How to create a floating action button (FAB) in android, using AppCompat v21?

@Justin Pollard xml code works really good. As a side note you can add a ripple effect with the following xml lines.

    <item>
    <ripple
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:color="?android:colorControlHighlight" >
        <item android:id="@android:id/mask">
            <shape android:shape="oval" >
                <solid android:color="#FFBB00" />
            </shape>
        </item>
        <item>
            <shape android:shape="oval" >
                <solid android:color="@color/ColorPrimary" />
            </shape>
        </item>
    </ripple>
</item>

How to shuffle an ArrayList

Use this method and pass your array in parameter

Collections.shuffle(arrayList);

This method return void so it will not give you a new list but as we know that array is passed as a reference type in Java so it will shuffle your array and save shuffled values in it. That's why you don't need any return type.

You can now use arraylist which is shuffled.

Can an Android NFC phone act as an NFC tag?

Its possible to make Android device behave as an NFC Tag. Such a behaviour is called Card Emulation.

  • Card emulation can be host-based(HCE) or secure-element based(CE).
  • In HCE, an application running on the Android main processor responds to the reader. So, the phone needs to be ON.
  • In CE, an applet residing in the Secure element responds to the reader. Here, its sufficient to have the NFC controller powered, with rest of the device suspended.
  • One of these or both approaches can be active simultaneously.
    A routing table instructs the NFC controller where route the Reader's commands to.

How to enter a series of numbers automatically in Excel

Enter the formula =ROW() into any cell and that cell will show the row number as its value.

If you want 1001, 1002 etc just enter =1000+ROW()

Logging POST data from $request_body

This solution works like a charm (updated in 2017 to honor that log_format needs to be in the http part of the nginx config):

log_format postdata $request_body;

server {
    # (...)

    location = /post.php {
       access_log  /var/log/nginx/postdata.log  postdata;
       fastcgi_pass php_cgi;
    }
}

I think the trick is making nginx believe that you will call a cgi script.

Vagrant ssh authentication failure

1. Locate the private key in the host:

vagrant ssh-config
#

Output:

Host default
  ...
  Port 2222
  ...
  IdentityFile /home/me/.vagrant.d/[...]/virtualbox/vagrant_private_key
  ...

2. Store the private key path and the port number in variables:

Use these two commands with the output from above:

pk="/home/me/.vagrant.d/.../virtualbox/vagrant_private_key"
port=2222
#

3. Generate a public key and upload it to the guest machine:

Copy/pasta, no changes needed:

ssh-keygen -y -f $pk > authorized_keys
scp -P $port authorized_keys vagrant@localhost:~/.ssh/
vagrant ssh -c "chmod 600 ~/.ssh/authorized_keys"
rm authorized_keys
#

Java array assignment (multiple values)

for example i tried all above for characters it fails but that worked for me >> reserved a pointer then assign values

char A[];
A = new char[]{'a', 'b', 'a', 'c', 'd', 'd', 'e', 'f', 'q', 'r'};

Regex to match string containing two names in any order

Vim has a branch operator \& that is useful when searching for a line containing a set of words, in any order. Moreover, extending the set of required words is trivial.

For example,

/.*jack\&.*james

will match a line containing jack and james, in any order.

See this answer for more information on usage. I am not aware of any other regex flavor that implements branching; the operator is not even documented on the Regular Expression wikipedia entry.

How to remove all debug logging calls before building the release version of an Android app?

enter image description here

This is what i used to do on my android projects..

In Android Studio we can do similar operation by, Ctrl+Shift+F to find from whole project (Command+Shift+F in MacOs) and Ctrl+Shift+R to Replace ((Command+Shift+R in MacOs))

Hiding and Showing TabPages in tabControl

It looks easier for me to clear all TabPages add add those wished:

PropertyTabControl.TabPages.Clear();
        PropertyTabControl.TabPages.Add(AspectTabPage);
        PropertyTabControl.TabPages.Add(WerkstattTabPage);

or

PropertyTabControl.TabPages.Clear();
        PropertyTabControl.TabPages.Add(TerminTabPage);

Multi-dimensional arraylist or list in C#?

You can create a list of lists

   public class MultiDimList: List<List<string>> {  }

or a Dictionary of key-accessible Lists

   public class MultiDimDictList: Dictionary<string, List<int>>  { }
   MultiDimDictList myDicList = new MultiDimDictList ();
   myDicList.Add("ages", new List<int>()); 
   myDicList.Add("Salaries", new List<int>()); 
   myDicList.Add("AccountIds", new List<int>()); 

Generic versions, to implement suggestion in comment from @user420667

  public class MultiDimList<T>: List<List<T>> {  }

and for the dictionary,

   public class MultiDimDictList<K, T>: Dictionary<K, List<T>>  { }

  // to use it, in client code
   var myDicList = new MultiDimDictList<string, int> ();
   myDicList.Add("ages", new List<T>()); 
   myDicList["ages"].Add(23);
   myDicList["ages"].Add(32);
   myDicList["ages"].Add(18);

   myDicList.Add("salaries", new List<T>());
   myDicList["salaries"].Add(80000);
   myDicList["salaries"].Add(100000);

   myDicList.Add("accountIds", new List<T>()); 
   myDicList["accountIds"].Add(321123);
   myDicList["accountIds"].Add(342653);

or, even better, ...

   public class MultiDimDictList<K, T>: Dictionary<K, List<T>>  
   {
       public void Add(K key, T addObject)
       {
           if(!ContainsKey(key)) Add(key, new List<T>());
           if (!base[key].Contains(addObject)) base[key].Add(addObject);
       }           
   }


  // and to use it, in client code
    var myDicList = new MultiDimDictList<string, int> ();
    myDicList.Add("ages", 23);
    myDicList.Add("ages", 32);
    myDicList.Add("ages", 18);
    myDicList.Add("salaries", 80000);
    myDicList.Add("salaries", 110000);
    myDicList.Add("accountIds", 321123);
    myDicList.Add("accountIds", 342653);

EDIT: to include an Add() method for nested instance:

public class NestedMultiDimDictList<K, K2, T>: 
           MultiDimDictList<K, MultiDimDictList<K2, T>>: 
{
       public void Add(K key, K2 key2, T addObject)
       {
           if(!ContainsKey(key)) Add(key, 
                  new MultiDimDictList<K2, T>());
           if (!base[key].Contains(key2)) 
               base[key].Add(key2, addObject);
       }    
}

how to get the ipaddress of a virtual box running on local machine

Login to virtual machine use below command to check ip address. (anyone will work)

  1. ifconfig
  2. ip addr show

If you used NAT for your virtual machine settings(your machine ip will be 10.0.2.15), then you have to use port forwarding to connect to machine. IP address will be 127.0.0.1

If you used bridged networking/Host only networking, then you will have separate Ip address. Use that IP address to connect virtual machine

Show red border for all invalid fields after submitting form angularjs

Reference article: Show red color border for invalid input fields angualrjs

I used ng-class on all input fields.like below

<input type="text" ng-class="{submitted:newEmployee.submitted}" placeholder="First Name" data-ng-model="model.firstName" id="FirstName" name="FirstName" required/>

when I click on save button I am changing newEmployee.submitted value to true(you can check it in my question). So when I click on save, a class named submitted gets added to all input fields(there are some other classes initially added by angularjs).

So now my input field contains classes like this

class="ng-pristine ng-invalid submitted"

now I am using below css code to show red border on all invalid input fields(after submitting the form)

input.submitted.ng-invalid
{
  border:1px solid #f00;
}

Thank you !!

Update:

We can add the ng-class at the form element instead of applying it to all input elements. So if the form is submitted, a new class(submitted) gets added to the form element. Then we can select all the invalid input fields using the below selector

form.submitted .ng-invalid
{
    border:1px solid #f00;
}

Filtering collections in C#

Using LINQ is relatively much slower than using a predicate supplied to the Lists FindAll method. Also be careful with LINQ as the enumeration of the list is not actually executed until you access the result. This can mean that, when you think you have created a filtered list, the content may differ to what you expected when you actually read it.

Writing a Python list of lists to a csv file

Ambers's solution also works well for numpy arrays:

from pylab import *
import csv

array_=arange(0,10,1)
list_=[array_,array_*2,array_*3]
with open("output.csv", "wb") as f:
    writer = csv.writer(f)
    writer.writerows(list_)

Groovy Shell warning "Could not open/create prefs root node ..."

Dennis answer is correct. However I would like to explain the solution in a bit more detailed way (for Windows User):

  1. Go into your Start Menu and type regedit into the search field.
  2. Navigate to path HKEY_LOCAL_MACHINE\Software\JavaSoft (Windows 10 seems to now have this here: HKEY_LOCAL_MACHINE\Software\WOW6432Node\JavaSoft)
  3. Right click on the JavaSoft folder and click on New -> Key
  4. Name the new Key Prefs and everything should work.

Alternatively, save and execute a *.reg file with the following content:

Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\Software\JavaSoft\Prefs]

How to hide command output in Bash

A process normally has two outputs to screen: stdout (standard out), and stderr (standard error).

Normally informational messages go to sdout, and errors and alerts go to stderr.

You can turn off stdout for a command by doing

MyCommand >/dev/null

and turn off stderr by doing:

MyCommand 2>/dev/null

If you want both off, you can do:

MyCommand 2>&1 >/dev/null

The 2>&1 says send stderr to the same place as stdout.

A good Sorted List for Java

What about using a HashMap? Insertion, deletion, and retrieval are all O(1) operations. If you wanted to sort everything, you could grab a List of the values in the Map and run them through an O(n log n) sorting algorithm.

edit

A quick search has found LinkedHashMap, which maintains insertion order of your keys. It's not an exact solution, but it's pretty close.

Alternative to the HTML Bold tag

The <b> tag is alive and well. <b> is not deprecated, but its use has been clarified and limited. <b> has no semantic meaning, nor does it convey vocal emphasis such as might be spoken by a screen reader. <b> does, however, convey printed empasis, as does the <i> tag. Both have a specific place in typograpghy, but not in spoken communication, mes frères.

To quote from http://www.whatwg.org/

The b element represents a span of text to be stylistically offset from the normal prose without conveying any extra importance, such as key words in a document abstract, product names in a review, or other spans of text whose typical typographic presentation is boldened.

what is the size of an enum type data in C++?

Because it's the size of an instance of the type - presumably enum values are stored as (32-bit / 4-byte) ints here.

Pass Arraylist as argument to function

It depends on how and where you declared your array list. If it is an instance variable in the same class like your AnalyseArray() method you don't have to pass it along. The method will know the list and you can simply use the A in whatever purpose you need.

If they don't know each other, e.g. beeing a local variable or declared in a different class, define that your AnalyseArray() method needs an ArrayList parameter

public void AnalyseArray(ArrayList<Integer> theList){}

and then work with theList inside that method. But don't forget to actually pass it on when calling the method.AnalyseArray(A);

PS: Some maybe helpful Information to Variables and parameters.

How to concatenate two strings in SQL Server 2005

Try something like

SELECT 'rupesh''s' + 'malviya'

+ (String Concatenation)

Emulate Samsung Galaxy Tab

Go to this link ... https://github.com/bsodmike/android-avd-profiles-2016/blob/master/Samsung%20Galaxy%20Tab%20A%2010.1%20(2016).xml

Save as xml file in your computer. Go on Android Studio => Tools => AVD Manager => + Create Virtual Device => Import Hardware Profiles ... choose the saved file and the device will be available on the tablet's section.

Happy Android developments guys!!!

Convert boolean result into number/integer

if you want integer x value change if 1 to 0 and if 0 to 1 you can use (x + 1) % 2

How to generate keyboard events?

regarding the recommended answer's code,

For my bot the recommended answer did not work. This is because I'm using Chrome which is requiring me to use KEYEVENTF_SCANCODE in my dwFlags.

To get his code to work I had to modify these code blocks:

class KEYBDINPUT(ctypes.Structure):
    _fields_ = (("wVk",         wintypes.WORD),
                ("wScan",       wintypes.WORD),
                ("dwFlags",     wintypes.DWORD),
                ("time",        wintypes.DWORD),
                ("dwExtraInfo", wintypes.ULONG_PTR))

    def __init__(self, *args, **kwds):
        super(KEYBDINPUT, self).__init__(*args, **kwds)
        # some programs use the scan code even if KEYEVENTF_SCANCODE
        # isn't set in dwFflags, so attempt to map the correct code.
        #if not self.dwFlags & KEYEVENTF_UNICODE:l
            #self.wScan = user32.MapVirtualKeyExW(self.wVk,
                                                 #MAPVK_VK_TO_VSC, 0)
            # ^MAKE SURE YOU COMMENT/REMOVE THIS CODE^

def PressKey(keyCode):
    input = INPUT(type=INPUT_KEYBOARD,
              ki=KEYBDINPUT(wScan=keyCode,
                            dwFlags=KEYEVENTF_SCANCODE))
    user32.SendInput(1, ctypes.byref(input), ctypes.sizeof(input))

def ReleaseKey(keyCode):
    input = INPUT(type=INPUT_KEYBOARD,
              ki=KEYBDINPUT(wScan=keyCode,
                            dwFlags=KEYEVENTF_SCANCODE | KEYEVENTF_KEYUP))
    user32.SendInput(1, ctypes.byref(input), ctypes.sizeof(input))

time.sleep(5) # sleep to open browser tab
PressKey(0x26) # press right arrow key
time.sleep(2) # hold for 2 seconds
ReleaseKey(0x26) # release right arrow key

I hope this helps someone's headache!

How do I get an empty array of any size in python?

Just declare the list and append each element. For ex:

a = []
a.append('first item')
a.append('second item')

Laravel Blade html image

as of now, you can use

<img src="{{ asset('images/foo.png') }}" alt="tag">

UICollectionView - Horizontal scroll, horizontal layout?

1st approach

What about using UIPageViewController with an array of UICollectionViewControllers? You'd have to fetch proper number of items in each UICollectionViewController, but it shouldn't be hard. You'd get exactly the same look as the Springboard has.

2nd approach

I've thought about this and in my opinion you have to set:

self.collectionView.pagingEnabled = YES;

and create your own collection view layout by subclassing UICollectionViewLayout. From the custom layout object you can access self.collectionView, so you'll know what is the size of the collection view's frame, numberOfSections and numberOfItemsInSection:. With that information you can calculate cells' frames (in prepareLayout) and collectionViewContentSize. Here're some articles about creating custom layouts:

3rd approach

You can do this (or an approximation of it) without creating the custom layout. Add UIScrollView in the blank view, set paging enabled in it. In the scroll view add the a collection view. Then add to it a width constraint, check in code how many items you have and set its constant to the correct value, e.g. (self.view.frame.size.width * numOfScreens). Here's how it looks (numbers on cells show the indexPath.row): https://www.dropbox.com/s/ss4jdbvr511azxz/collection_view.mov If you're not satisfied with the way cells are ordered, then I'm afraid you'd have to go with 1. or 2.

Threads vs Processes in Linux

Linux (and indeed Unix) gives you a third option.

Option 1 - processes

Create a standalone executable which handles some part (or all parts) of your application, and invoke it separately for each process, e.g. the program runs copies of itself to delegate tasks to.

Option 2 - threads

Create a standalone executable which starts up with a single thread and create additional threads to do some tasks

Option 3 - fork

Only available under Linux/Unix, this is a bit different. A forked process really is its own process with its own address space - there is nothing that the child can do (normally) to affect its parent's or siblings address space (unlike a thread) - so you get added robustness.

However, the memory pages are not copied, they are copy-on-write, so less memory is usually used than you might imagine.

Consider a web server program which consists of two steps:

  1. Read configuration and runtime data
  2. Serve page requests

If you used threads, step 1 would be done once, and step 2 done in multiple threads. If you used "traditional" processes, steps 1 and 2 would need to be repeated for each process, and the memory to store the configuration and runtime data duplicated. If you used fork(), then you can do step 1 once, and then fork(), leaving the runtime data and configuration in memory, untouched, not copied.

So there are really three choices.

How to completely hide the navigation bar in iPhone / HTML5

The problem with all of the answers given so far is that on the something borrowed site, the Mac bar remains totally hidden when scrolling up, and the provided answers don't accomplish that.

If you just use scrollTo and then the user later scrolls up, the nav bar is revealed again, so it seems you have to put the whole site inside of a div and force scrolling to happen inside of that div rather than on the body which keeps the nav bar hidden during scrolling in any direction.

You can, however, still reveal the nav bar by touching near the top of the screen on apple devices.

SQL - IF EXISTS UPDATE ELSE INSERT INTO

  1. Create a UNIQUE constraint on your subs_email column, if one does not already exist:

    ALTER TABLE subs ADD UNIQUE (subs_email)
    
  2. Use INSERT ... ON DUPLICATE KEY UPDATE:

    INSERT INTO subs
      (subs_name, subs_email, subs_birthday)
    VALUES
      (?, ?, ?)
    ON DUPLICATE KEY UPDATE
      subs_name     = VALUES(subs_name),
      subs_birthday = VALUES(subs_birthday)
    

You can use the VALUES(col_name) function in the UPDATE clause to refer to column values from the INSERT portion of the INSERT ... ON DUPLICATE KEY UPDATE - dev.mysql.com

  1. Note that I have used parameter placeholders in the place of string literals, as one really should be using parameterised statements to defend against SQL injection attacks.

How to remove underline from a name on hover

To keep the color and prevent an underline on the link:

legend.green-color a{
    color:green;
    text-decoration: none;
}

Python argparse command line flags without arguments

Adding a quick snippet to have it ready to execute:

Source: myparser.py

import argparse
parser = argparse.ArgumentParser(description="Flip a switch by setting a flag")
parser.add_argument('-w', action='store_true')

args = parser.parse_args()
print args.w

Usage:

python myparser.py -w
>> True

Laravel 5 Carbon format datetime

$suborder['payment_date'] = Carbon::parse($item['created_at'])->format('M d Y');

How to add meta tag in JavaScript

You can add it:

var meta = document.createElement('meta');
meta.httpEquiv = "X-UA-Compatible";
meta.content = "IE=edge";
document.getElementsByTagName('head')[0].appendChild(meta);

...but I wouldn't be surprised if by the time that ran, the browser had already made its decisions about how to render the page.

The real answer here has to be to output the correct tag from the server in the first place. (Sadly, you can't just not have the tag if you need to support IE. :-| )

creating batch script to unzip a file without additional zip tools

Here's my overview about built-in zi/unzip (compress/decompress) capabilities in windows - How can I compress (/ zip ) and uncompress (/ unzip ) files and folders with batch file without using any external tools?

To unzip file you can use this script :

zipjs.bat unzip -source C:\myDir\myZip.zip -destination C:\MyDir -keep yes -force no

Radio Buttons ng-checked with ng-model

I solved my problem simply using ng-init for default selection instead of ng-checked

<div ng-init="person.billing=FALSE"></div>
<input id="billing-no" type="radio" name="billing" ng-model="person.billing" ng-value="FALSE" />
<input id="billing-yes" type="radio" name="billing" ng-model="person.billing" ng-value="TRUE" />

get index of DataTable column with name

You can use DataColumn.Ordinal to get the index of the column in the DataTable. So if you need the next column as mentioned use Column.Ordinal + 1:

row[row.Table.Columns["ColumnName"].Ordinal + 1] = someOtherValue;

What static analysis tools are available for C#?

Aside from the excellent list by madgnome, I would add a duplicate code detector that is based off the command line (but is free):

http://sourceforge.net/projects/duplo/

how to set default culture info for entire c# application

With 4.0, you will need to manage this yourself by setting the culture for each thread as Alexei describes. But with 4.5, you can define a culture for the appdomain and that is the preferred way to handle this. The relevant apis are CultureInfo.DefaultThreadCurrentCulture and CultureInfo.DefaultThreadCurrentUICulture.

Easiest way to develop simple GUI in Python

Try with Kivy! kivy.org It's quite easy, multi platform and a really good documentation

Rails get index of "each" loop

The two answers are good. And I also suggest you a similar method:

<% @images.each.with_index do |page, index| %>
<% end %>

You might not see the difference between this and the accepted answer. Let me direct your eyes to these method calls: .each.with_index see how it's .each and then .with_index.

Error including image in Latex

To include png and jpg, you need to specify the Bounding Box explicitly.

\includegraphics[bb=0 0 1280 960]{images/some_image.png}

Where 1280 and 960 are respectively width and height.

How to replace a set of tokens in a Java String?

In the past, I've solved this kind of problem with StringTemplate and Groovy Templates.

Ultimately, the decision of using a templating engine or not should be based on the following factors:

  • Will you have many of these templates in the application?
  • Do you need the ability to modify the templates without restarting the application?
  • Who will be maintaining these templates? A Java programmer or a business analyst involved on the project?
  • Will you need to the ability to put logic in your templates, like conditional text based on values in the variables?
  • Will you need the ability to include other templates in a template?

If any of the above applies to your project, I would consider using a templating engine, most of which provide this functionality, and more.

difference between iframe, embed and object elements

iframe have "sandbox" attribute that may block pop up etc

What is the most accurate way to retrieve a user's correct IP address in PHP?

As someone said previously, the key here is for what reason you want to store user's ips.

I'll give an example from a registration system I work on and of course the solution just to contribute sth in this old discussion that comes frequently in my searches.

Many php registration libraries use ip to throttle/lock out failed attempts based on user's ip. Consider this table:

-- mysql
DROP TABLE IF EXISTS `attempts`;
CREATE TABLE `attempts` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `ip` varchar(39) NOT NULL, /*<<=====*/
  `expiredate` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 -- sqlite
...

Then, when a user tries to do a login or anything related with servicing like a password reset, a function is called at the start:

public function isBlocked() {
      /*
       * used one of the above methods to capture user's ip!!!
       */
      $ip = $this->ip;
      // delete attempts from this ip with 'expiredate' in the past
      $this->deleteAttempts($ip, false);
      $query = $this->dbh->prepare("SELECT count(*) FROM {$this->token->get('table_attempts')} WHERE ip = ?");
      $query->execute(array($ip));
      $attempts = $query->fetchColumn();
      if ($attempts < intval($this->token->get('attempts_before_verify'))) {
         return "allow";
      }
      if ($attempts < intval($this->token->get('attempts_before_ban'))) {
         return "captcha";
      }
      return "block";
   }

Say, for example, $this->token->get('attempts_before_ban') === 10 and 2 users come for the same ips as is the case in the previous codes where headers can be spoofed, then after 5 attempts each both are banned! Even worst, if all come from the same proxy then only the first 10 users will be logged and all the rest will be banned!

The critical here is that we need a unique index on table attempts and we can get it from a combination like:

 `ip` varchar(39) NOT NULL,
 `jwt_load varchar(100) NOT NULL

where jwt_load comes from a http cookie that follows the json web token technology where we store only the encrypted payload that should contain an arbitrary/unique value for every user. Of course the request should be modified to: "SELECT count(*) FROM {$this->token->get('table_attempts')} WHERE ip = ? AND jwt_load = ?" and the class should also initiate a private $jwt.

What bitrate is used for each of the youtube video qualities (360p - 1080p), in regards to flowplayer?

Looking at this official google link: Youtube Live encoder settings, bitrates and resolutions they have this table:

                   240p       360p        480p        720p        1080p
Resolution      426 x 240   640 x 360   854x480     1280x720    1920x1080
Video Bitrates                   
Maximum         700 Kbps    1000 Kbps   2000 Kbps   4000 Kbps   6000 Kbps
Recommended     400 Kbps    750 Kbps    1000 Kbps   2500 Kbps   4500 Kbps
Minimum         300 Kbps    400 Kbps    500 Kbps    1500 Kbps   3000 Kbps

It would appear as though this is the case, although the numbers dont sync up to the google table above:

// the bitrates, video width and file names for this clip
      bitrates: [
        { url: "bbb-800.mp4", width: 480, bitrate: 800 }, //360p video
        { url: "bbb-1200.mp4", width: 720, bitrate: 1200 }, //480p video
        { url: "bbb-1600.mp4", width: 1080, bitrate: 1600 } //720p video
      ],

How to get index in Handlebars each helper?

In handlebar version 3.0 onwards,

{{#each users as |user userId|}}
  Id: {{userId}} Name: {{user.name}}
{{/each}}

In this particular example, user will have the same value as the current context and userId will have the index value for the iteration. Refer - http://handlebarsjs.com/block_helpers.html in block helpers section

GitHub Error Message - Permission denied (publickey)

I was using github earlier for one of my php project. While using github, I was using ssh instead of https. I had my machine set up like that and every time I used to commit and push the code, it would ask me my rsa key password.

After some days, I stopped working on the php project and forgot my rsa password. Recently, I started working on a java project and moved to bitbucket. Since, I had forgotten the password and there is no way to recover it I guess, I decided to use the https(recommended) protocol for the new project and got the same error asked in the question.

How I solved it?

  1. Ran this command to tell my git to use https instead of ssh:

    git config --global url."https://".insteadOf git://
    
  2. Remove any remote if any

    git remote rm origin
    
  3. Redo everything from git init to git push and it works!

PS: I also un-installed ssh from my machine during the debug process thinking that, removing it will fix the problem. Yes I know!! :)

AngularJS not detecting Access-Control-Allow-Origin header?

I experienced this exact same issue. For me, the OPTIONS request would go through, but the POST request would say "aborted." This led me to believe that the browser was never making the POST request at all. Chrome said something like "Caution provisional headers are shown" in the request headers but no response headers were shown. In the end I turned to debugging on Firefox which led me to find out my server was responding with an error and no CORS headers were present on the response. Chrome was actually receiving the response, but not allowing the response to be shown in the network view.

How to convert all text to lowercase in Vim

I assume you want lowercase the text. Solution is pretty simple:

ggVGu

Explanation:

  1. gg - goes to first line of text
  2. V - turns on Visual selection, in line mode
  3. G - goes to end of file (at the moment you have whole text selected)
  4. u - lowercase selected area

Making WPF applications look Metro-styled, even in Windows 7? (Window Chrome / Theming / Theme)

Based on Kapitán Mlíko's answer with source above, I would change it to use the following:

Marlett Font Example

It's a better practice to use the Marlett font rather than Path Data points for the Minimize, Restore/Maximize and Close buttons.

<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" VerticalAlignment="Top" WindowChrome.IsHitTestVisibleInChrome="True" Grid.Row="0">
<Button Command="{Binding Source={x:Static SystemCommands.MinimizeWindowCommand}}" ToolTip="minimize" Style="{StaticResource WindowButtonStyle}">
    <Button.Content>
        <Grid Width="30" Height="25">
            <TextBlock Text="0" FontFamily="Marlett" FontSize="14" VerticalAlignment="Center" HorizontalAlignment="Center" Padding="3.5,0,0,3" />
        </Grid>
    </Button.Content>
</Button>
<Grid Margin="1,0,1,0">
    <Button x:Name="Restore" Command="{Binding Source={x:Static SystemCommands.RestoreWindowCommand}}" ToolTip="restore" Visibility="Collapsed" Style="{StaticResource WindowButtonStyle}">
        <Button.Content>
            <Grid Width="30" Height="25" UseLayoutRounding="True">
                <TextBlock Text="2" FontFamily="Marlett" FontSize="14" VerticalAlignment="Center" HorizontalAlignment="Center" Padding="2,0,0,1" />
            </Grid>
        </Button.Content>
    </Button>
    <Button x:Name="Maximize" Command="{Binding Source={x:Static SystemCommands.MaximizeWindowCommand}}" ToolTip="maximize" Style="{StaticResource WindowButtonStyle}">
        <Button.Content>
            <Grid Width="31" Height="25">
                <TextBlock Text="1" FontFamily="Marlett" FontSize="14" VerticalAlignment="Center" HorizontalAlignment="Center" Padding="2,0,0,1" />
            </Grid>
        </Button.Content>
    </Button>
</Grid>
<Button Command="{Binding Source={x:Static SystemCommands.CloseWindowCommand}}" ToolTip="close"  Style="{StaticResource WindowButtonStyle}">
    <Button.Content>
        <Grid Width="30" Height="25">
            <TextBlock Text="r" FontFamily="Marlett" FontSize="14" VerticalAlignment="Center" HorizontalAlignment="Center" Padding="0,0,0,1" />
        </Grid>
    </Button.Content>
</Button>

Convert a RGB Color Value to a Hexadecimal String

You can use

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

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

AngularJs ReferenceError: angular is not defined

You should put the include angular line first, before including any other js file

How to measure elapsed time in Python?

Use profiler module. It gives a very detailed profile.

import profile
profile.run('main()')

it outputs something like:

          5 function calls in 0.047 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.000    0.000 :0(exec)
        1    0.047    0.047    0.047    0.047 :0(setprofile)
        1    0.000    0.000    0.000    0.000 <string>:1(<module>)
        0    0.000             0.000          profile:0(profiler)
        1    0.000    0.000    0.047    0.047 profile:0(main())
        1    0.000    0.000    0.000    0.000 two_sum.py:2(twoSum)

I've found it very informative.

Getting the thread ID from a thread

GetThreadId returns the ID of a given native thread. There are ways to make it work with managed threads, I'm sure, all you need to find is the thread handle and pass it to that function.

GetCurrentThreadId returns the ID of the current thread.

GetCurrentThreadId has been deprecated as of .NET 2.0: the recommended way is the Thread.CurrentThread.ManagedThreadId property.

Laravel check if collection is empty

This is the fastest way:

if ($coll->isEmpty()) {...}

Other solutions like count do a bit more than you need which costs slightly more time.

Plus, the isEmpty() name quite precisely describes what you want to check there so your code will be more readable.

Apply vs transform on a group object

Two major differences between apply and transform

There are two major differences between the transform and apply groupby methods.

  • Input:
  • apply implicitly passes all the columns for each group as a DataFrame to the custom function.
  • while transform passes each column for each group individually as a Series to the custom function.
  • Output:
  • The custom function passed to apply can return a scalar, or a Series or DataFrame (or numpy array or even list).
  • The custom function passed to transform must return a sequence (a one dimensional Series, array or list) the same length as the group.

So, transform works on just one Series at a time and apply works on the entire DataFrame at once.

Inspecting the custom function

It can help quite a bit to inspect the input to your custom function passed to apply or transform.

Examples

Let's create some sample data and inspect the groups so that you can see what I am talking about:

import pandas as pd
import numpy as np
df = pd.DataFrame({'State':['Texas', 'Texas', 'Florida', 'Florida'], 
                   'a':[4,5,1,3], 'b':[6,10,3,11]})

     State  a   b
0    Texas  4   6
1    Texas  5  10
2  Florida  1   3
3  Florida  3  11

Let's create a simple custom function that prints out the type of the implicitly passed object and then raised an error so that execution can be stopped.

def inspect(x):
    print(type(x))
    raise

Now let's pass this function to both the groupby apply and transform methods to see what object is passed to it:

df.groupby('State').apply(inspect)

<class 'pandas.core.frame.DataFrame'>
<class 'pandas.core.frame.DataFrame'>
RuntimeError

As you can see, a DataFrame is passed into the inspect function. You might be wondering why the type, DataFrame, got printed out twice. Pandas runs the first group twice. It does this to determine if there is a fast way to complete the computation or not. This is a minor detail that you shouldn't worry about.

Now, let's do the same thing with transform

df.groupby('State').transform(inspect)
<class 'pandas.core.series.Series'>
<class 'pandas.core.series.Series'>
RuntimeError

It is passed a Series - a totally different Pandas object.

So, transform is only allowed to work with a single Series at a time. It is impossible for it to act on two columns at the same time. So, if we try and subtract column a from b inside of our custom function we would get an error with transform. See below:

def subtract_two(x):
    return x['a'] - x['b']

df.groupby('State').transform(subtract_two)
KeyError: ('a', 'occurred at index a')

We get a KeyError as pandas is attempting to find the Series index a which does not exist. You can complete this operation with apply as it has the entire DataFrame:

df.groupby('State').apply(subtract_two)

State     
Florida  2   -2
         3   -8
Texas    0   -2
         1   -5
dtype: int64

The output is a Series and a little confusing as the original index is kept, but we have access to all columns.


Displaying the passed pandas object

It can help even more to display the entire pandas object within the custom function, so you can see exactly what you are operating with. You can use print statements by I like to use the display function from the IPython.display module so that the DataFrames get nicely outputted in HTML in a jupyter notebook:

from IPython.display import display
def subtract_two(x):
    display(x)
    return x['a'] - x['b']

Screenshot: enter image description here


Transform must return a single dimensional sequence the same size as the group

The other difference is that transform must return a single dimensional sequence the same size as the group. In this particular instance, each group has two rows, so transform must return a sequence of two rows. If it does not then an error is raised:

def return_three(x):
    return np.array([1, 2, 3])

df.groupby('State').transform(return_three)
ValueError: transform must return a scalar value for each group

The error message is not really descriptive of the problem. You must return a sequence the same length as the group. So, a function like this would work:

def rand_group_len(x):
    return np.random.rand(len(x))

df.groupby('State').transform(rand_group_len)

          a         b
0  0.962070  0.151440
1  0.440956  0.782176
2  0.642218  0.483257
3  0.056047  0.238208

Returning a single scalar object also works for transform

If you return just a single scalar from your custom function, then transform will use it for each of the rows in the group:

def group_sum(x):
    return x.sum()

df.groupby('State').transform(group_sum)

   a   b
0  9  16
1  9  16
2  4  14
3  4  14

Convert Base64 string to an image file?

That's an old thread, but in case you want to upload the image having same extension-

    $image = $request->image;
    $imageInfo = explode(";base64,", $image);
    $imgExt = str_replace('data:image/', '', $imageInfo[0]);      
    $image = str_replace(' ', '+', $imageInfo[1]);
    $imageName = "post-".time().".".$imgExt;
    Storage::disk('public_feeds')->put($imageName, base64_decode($image));

You can create 'public_feeds' in laravel's filesystem.php-

   'public_feeds' => [
        'driver' => 'local',
        'root'   => public_path() . '/uploads/feeds',
    ],

Assign a variable inside a Block to a variable outside a Block

Just use the __block prefix to declare and assign any type of variable inside a block.

For example:

__block Person *aPerson = nil;

__block NSString *name = nil;

React-router v4 this.props.history.push(...) not working

Don't use with Router.

handleSubmit(e){
   e.preventDefault();
   this.props.form.validateFieldsAndScroll((err,values)=>{
      if(!err){
        this.setState({
            visible:false
        });
        this.props.form.resetFields();
        console.log(values.username);
        const path = '/list/';
        this.props.history.push(path);
      }
   })
}

It works well.

Checking character length in ruby

Ruby provides a built-in function for checking the length of a string. Say it's called s:

if s.length <= 25
  # We're OK
else
  # Too long
end

UIView bottom border?

I wrote a general method that will add a border on whichever sides you wish in any UIView. You can define thickness, color, margins and zOrder for each side.

/*
 view: the view to draw border around
 thickness: thickness of the border on the given side
 color: color of the border on the given side
 margin: space between the border's outer edge and the view's frame edge on the given side.
 zOrder: defines the order to add the borders to the view.  The borders will be added by zOrder from lowest to highest, thus making the highest priority border visible when two borders overlap at the corners.
*/

    +(void) drawBorderAroundUIView:(UIView *) view thicknessLeft:(CGFloat) thicknessLeft colorLeft:(UIColor *)colorLeft marginLeft:(CGFloat) marginLeft zOrderLeft:(int) zOrderLeft thicknessRight:(CGFloat) thicknessRight colorRight:(UIColor *)colorRight marginRight:(CGFloat) marginRight zOrderRight:(int) zOrderRight thicknessTop:(CGFloat) thicknessTop colorTop:(UIColor *)colorTop marginTop:(CGFloat) marginTop zOrderTop:(int) zOrderTop thicknessBottom:(CGFloat) thicknessBottom colorBottom:(UIColor *)colorBottom marginBottom:(CGFloat) marginBottom zOrderBottom:(int) zOrderBottom{
    //make margins be the outside edge and make positive margin represent a smaller rectangle
    marginBottom = -1 * marginBottom - thicknessBottom;
    marginTop = -1 * marginTop - thicknessTop;
    marginLeft = -1 * marginLeft - thicknessLeft;
    marginRight = -1 * marginRight - thicknessRight;

    //get reference points for corners
    CGPoint upperLeftCorner = CGPointZero;
    CGPoint lowerLeftCorner = CGPointMake(upperLeftCorner.x, upperLeftCorner.y + view.frame.size.height);
    CGPoint upperRightCorner = CGPointMake(upperLeftCorner.x + view.frame.size.width, upperLeftCorner.y);

    //left
    CALayer *leftBorder = [CALayer layer];
    leftBorder.frame = CGRectMake(upperLeftCorner.x - thicknessLeft - marginLeft, upperLeftCorner.y - thicknessTop - marginTop, thicknessLeft, view.frame.size.height + marginTop + marginBottom + thicknessBottom + thicknessTop);
    leftBorder.backgroundColor = colorLeft.CGColor;

    //right
    CALayer *rightBorder = [CALayer layer];
    rightBorder.frame = CGRectMake(upperRightCorner.x + marginRight, upperRightCorner.y - thicknessTop - marginTop, thicknessRight, view.frame.size.height + marginTop + marginBottom + thicknessBottom + thicknessTop);
    rightBorder.backgroundColor = colorRight.CGColor;

    //top
    CALayer *topBorder = [CALayer layer];
    topBorder.frame = CGRectMake(upperLeftCorner.x - thicknessLeft - marginLeft, upperLeftCorner.y - thicknessTop - marginTop, view.frame.size.width + marginLeft + marginRight + thicknessLeft + thicknessRight, thicknessTop);
    topBorder.backgroundColor = colorTop.CGColor;

    //bottom
    CALayer *bottomBorder = [CALayer layer];
    bottomBorder.frame = CGRectMake(upperLeftCorner.x - thicknessLeft - marginLeft, lowerLeftCorner.y + marginBottom, view.frame.size.width + marginLeft + marginRight + thicknessLeft + thicknessRight, thicknessBottom);
    bottomBorder.backgroundColor = colorBottom.CGColor;

    //define dictionary keys to be used for adding borders in order of zOrder
    NSString *borderDK = @"border";
    NSString *zOrderDK = @"zOrder";

    //storing borders in dictionaries in preparation to add them in order of zOrder
    NSDictionary *leftBorderDictionary = [NSDictionary dictionaryWithObjectsAndKeys:leftBorder, borderDK, [NSNumber numberWithInt:zOrderLeft], zOrderDK, nil];
    NSDictionary *rightBorderDictionary = [NSDictionary dictionaryWithObjectsAndKeys:rightBorder, borderDK, [NSNumber numberWithInt:zOrderRight], zOrderDK, nil];
    NSDictionary *topBorderDictionary = [NSDictionary dictionaryWithObjectsAndKeys:topBorder, borderDK, [NSNumber numberWithInt:zOrderTop], zOrderDK, nil];
    NSDictionary *bottomBorderDictionary = [NSDictionary dictionaryWithObjectsAndKeys:bottomBorder, borderDK, [NSNumber numberWithInt:zOrderBottom], zOrderDK, nil];

    NSMutableArray *borders = [NSMutableArray arrayWithObjects:leftBorderDictionary, rightBorderDictionary, topBorderDictionary, bottomBorderDictionary, nil];

    //add borders in order of zOrder (lowest -> highest).  Thus the highest zOrder will be added last so it will be on top.
    while (borders.count)
    {
        //look for the next lowest zOrder border to add
        NSDictionary *nextBorderToLayDown = [borders objectAtIndex:0];
        for (int indexOfBorder = 0; indexOfBorder < borders.count; indexOfBorder++)
        {
            NSDictionary *borderAtIndex = [borders objectAtIndex:indexOfBorder];
            if ([[borderAtIndex objectForKey:zOrderDK] intValue] < [[nextBorderToLayDown objectForKey:zOrderDK] intValue])
            {
                nextBorderToLayDown = borderAtIndex;
            }
        }
        //add the border to the view
        [view.layer addSublayer:[nextBorderToLayDown objectForKey:borderDK]];
        [borders removeObject:nextBorderToLayDown];
    }
}

jQuery - hashchange event

I just ran into the same problem (lack of hashchange event in IE7). A workaround that suited for my purposes was to bind the click event of the hash-changing links.

<a class='hash-changer' href='#foo'>Foo</a>

<script type='text/javascript'>

if (("onhashchange" in window) && !($.browser.msie)) { 

    //modern browsers 
    $(window).bind('hashchange', function() {
        var hash = window.location.hash.replace(/^#/,'');
        //do whatever you need with the hash
    });

} else {

    //IE and browsers that don't support hashchange
    $('a.hash-changer').bind('click', function() {
        var hash = $(this).attr('href').replace(/^#/,'');
        //do whatever you need with the hash
    });

}

</script>

PKIX path building failed: unable to find valid certification path to requested target

I've run into this a few times and it was due to a certificate chain being incomplete. If you are using the standard java trust store, it may not have a certificate that is needed to complete the certificate chain which is required to validate the certificate of the SSL site you are connecting to.

I ran into this problem with some DigiCert certificates and had to manually add the intermediary cert myself.

Should I use scipy.pi, numpy.pi, or math.pi?

One thing to note is that not all libraries will use the same meaning for pi, of course, so it never hurts to know what you're using. For example, the symbolic math library Sympy's representation of pi is not the same as math and numpy:

import math
import numpy
import scipy
import sympy

print(math.pi == numpy.pi)
> True
print(math.pi == scipy.pi)
> True
print(math.pi == sympy.pi)
> False

/usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found

I've had a similar issue, and I've resolved it by statically linking libstdc++ into the program I was compiling, like so:

$ LIBS=-lstdc++ ./configure ... etc.

instead of the usual

$ ./configure ... etc.

There might be problems with this solution to do with loading shared libraries at runtime, but I haven't looked into the issue deeply enough to comment.

Why not use Double or Float to represent currency?

If your computation involves various steps, arbitrary precision arithmetic won't cover you 100%.

The only reliable way to use a perfect representation of results(Use a custom Fraction data type that will batch division operations to the last step) and only convert to decimal notation in the last step.

Arbitrary precision won't help because there always can be numbers that has so many decimal places, or some results such as 0.6666666... No arbitrary representation will cover the last example. So you will have small errors in each step.

These errors will add-up, may eventually become not easy to ignore anymore. This is called Error Propagation.

Changing directory in Google colab (breaking out of the python interpreter)

If you want to use the cd or ls functions , you need proper identifiers before the function names ( % and ! respectively) use %cd and !ls to navigate

.

!ls    # to find the directory you're in ,
%cd ./samplefolder  #if you wanna go into a folder (say samplefolder)

or if you wanna go out of the current folder

%cd ../      

and then navigate to the required folder/file accordingly

dereferencing pointer to incomplete type

this error usually shows if the name of your struct is different from the initialization of your struct in the code, so normally, c will find the name of the struct you put and if the original struct is not found, this would usually appear, or if you point a pointer pointed into that pointer, the error will show up.

List of phone number country codes

There is a fairly well maintained repo on github that has a CSV (with semicolon delimiters), XML, and JSON source of countries, country codes, and other information.

git: diff between file in local repo and origin

Full answer to the original question that was talking about a possible different path on local and remote is below

  1. git fetch origin
  2. git diff master -- [local-path] origin/master -- [remote-path]

Assuming the local path is docs/file1.txt and remote path is docs2/file1.txt, use git diff master -- docs/file1.txt origin/master -- docs2/file1.txt

This is adapted from GitHub help page here and Code-Apprentice answer above