Programs & Examples On #Rockbox

Rockbox is a free replacement firmware for digital music players. It runs on a wide range of players

What is a .pid file and what does it contain?

Pidfile contains pid of a process. It is a convention allowing long running processes to be more self-aware. Server process can inspect it to stop itself, or have heuristic that its other instance is already running. Pidfiles can also be used to conventiently kill risk manually, e.g. pkill -F <some.pid>

Running an outside program (executable) in Python?

That's the correct usage, but perhaps the spaces in the path name are messing things up for some reason.

You may want to run the program under cmd.exe as well so you can see any output from flow.exe that might be indicating an error.

Is there an easy way to convert Android Application to IPad, IPhone

I'm not sure how helpful this answer is for your current application, but it may prove helpful for the next applications that you will be developing.

As iOS does not use Java like Android, your options are quite limited:

1) if your application is written mostly in C/C++ using JNI, you can write a wrapper and interface it with the iOS (i.e. provide callbacks from iOS to your JNI written function). There may be frameworks out there that help you do this easier, but there's still the problem of integrating the application and adapting it to the framework (and of course the fact that the application has to be written in C/C++).

2) rewrite it for iOS. I don't know whether there are any good companies that do this for you. Also, due to the variety of applications that can be written which can use different services and API, there may not be any software that can port it for you (I guess this kind of software is like a gold mine heh) or do a very good job at that.

3) I think that there are Java->C/C++ converters, but there won't help you at all when it comes to API differences. Also, you may find yourself struggling more to get the converted code working on any of the platforms rather than rewriting your application from scratch for iOS.

The problem depends quite a bit on the services and APIs your application is using. I haven't really look this up, but there may be some APIs that provide certain functionality in Android that iOS doesn't provide.

Using C/C++ and natively compiling it for the desired platform looks like the way to go for Android-iOS-Win7Mobile cross-platform development. This gets you somewhat of an application core/kernel which you can use to do the actual application logic.

As for the OS specific parts (APIs) that your application is using, you'll have to set up communication interfaces between them and your application's core.

Origin is not allowed by Access-Control-Allow-Origin

In Ruby Sinatra

response['Access-Control-Allow-Origin'] = '*' 

for everyone or

response['Access-Control-Allow-Origin'] = 'http://yourdomain.name' 

android.app.Application cannot be cast to android.app.Activity

You can also try this one.

override fun registerWith( registry: PluginRegistry) {
        GeneratedPluginRegistrant.registerWith(registry as FlutterEngine)       
    //registry.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin")
    }

I think this one is far better solution than creating a new class.

calling parent class method from child class object in java

If you override a parent method in its child, child objects will always use the overridden version. But; you can use the keyword super to call the parent method, inside the body of the child method.

public class PolyTest{
    public static void main(String args[]){
        new Child().foo();
    }

}
class Parent{
    public void foo(){
        System.out.println("I'm the parent.");
    }
}

class Child extends Parent{
    @Override
    public void foo(){
        //super.foo();
        System.out.println("I'm the child.");
    }
}

This would print:

I'm the child.

Uncomment the commented line and it would print:

I'm the parent.

I'm the child.

You should look for the concept of Polymorphism.

In a Bash script, how can I exit the entire script if a certain condition occurs?

I often include a function called run() to handle errors. Every call I want to make is passed to this function so the entire script exits when a failure is hit. The advantage of this over the set -e solution is that the script doesn't exit silently when a line fails, and can tell you what the problem is. In the following example, the 3rd line is not executed because the script exits at the call to false.

function run() {
  cmd_output=$(eval $1)
  return_value=$?
  if [ $return_value != 0 ]; then
    echo "Command $1 failed"
    exit -1
  else
    echo "output: $cmd_output"
    echo "Command succeeded."
  fi
  return $return_value
}
run "date"
run "false"
run "date"

Resize image proportionally with CSS?

You always need something like this

html
{
    width: 100%;
    height: 100%;
}

at the top of your css file

How to convert a multipart file to File?

MultipartFile.transferTo(File) is nice, but don't forget to clean the temp file after all.

// ask JVM to ask operating system to create temp file
File tempFile = File.createTempFile(TEMP_FILE_PREFIX, TEMP_FILE_POSTFIX);

// ask JVM to delete it upon JVM exit if you forgot / can't delete due exception
tempFile.deleteOnExit();

// transfer MultipartFile to File
multipartFile.transferTo(tempFile);

// do business logic here
result = businessLogic(tempFile);

// tidy up
tempFile.delete();

Check out Razzlero's comment about File.deleteOnExit() executed upon JVM exit (which may be extremely rare) details below.

Get records of current month

Try this query:

SELECT *
FROM table 
WHERE MONTH(FROM_UNIXTIME(columnName))= MONTH(CURDATE())

How to make for loops in Java increase by increments other than 1

In your example, j+=3 increments by 3.

(Not much else to say here, if it's syntax related I'd suggest Googling first, but I'm new here so I could be wrong.)

Build .so file from .c file using gcc command line

To generate a shared library you need first to compile your C code with the -fPIC (position independent code) flag.

gcc -c -fPIC hello.c -o hello.o

This will generate an object file (.o), now you take it and create the .so file:

gcc hello.o -shared -o libhello.so

EDIT: Suggestions from the comments:

You can use

gcc -shared -o libhello.so -fPIC hello.c

to do it in one step. – Jonathan Leffler

I also suggest to add -Wall to get all warnings, and -g to get debugging information, to your gcc commands. – Basile Starynkevitch

VueJS conditionally add an attribute for an element

<input :required="condition">

You don't need <input :required="test ? true : false"> because if test is truthy you'll already get the required attribute, and if test is falsy you won't get the attribute. The true : false part is redundant, much like this...

if (condition) {
    return true;
} else {
    return false;
}
// or this...
return condition ? true : false;
// can *always* be replaced by...
return (condition); // parentheses generally not needed

The simplest way of doing this binding, then, is <input :required="condition">

Only if the test (or condition) can be misinterpreted would you need to do something else; in that case Syed's use of !! does the trick.
  <input :required="!!condition">

How can I add private key to the distribution certificate?

Since the existing answers were written, Xcode's interface has been updated and they're no longer correct (notably the Click on Window, Organiser // Expand the Teams section step). Now the instructions for importing an existing certificate are as follows:

To export selected certificates

  1. Choose Xcode > Preferences.
  2. Click Accounts at the top of the window.
  3. Select the team you want to view, and click View Details.
  4. Control-click the certificate you want to export in the Signing Identities table and choose Export from the pop-up menu.

Export certificate demo

  1. Enter a filename in the Save As field and a password in both the Password and Verify fields. The file is encrypted and password protected.
  2. Click Save. The file is saved to the location you specified with a .p12 extension.

Source (Apple's documentation)

To import it, I found that Xcode's let-me-help-you menu didn't recognise the .p12 file. Instead, I simply imported it manually into Keychain, then Xcode built and archived without complaining.

No Main class found in NetBeans

In the toolbar search for press the arrow and select Customize... It will open project properties.In the categories select RUN. Look for Main Class. Clear all the Main Class character and type your class name. Click on OK. And run again. The problem is solved.

How to add a local repo and treat it as a remote repo

You have your arguments to the remote add command reversed:

git remote add <NAME> <PATH>

So:

git remote add bak /home/sas/dev/apps/smx/repo/bak/ontologybackend/.git

See git remote --help for more information.

simple way to display data in a .txt file on a webpage?

If you just want to throw the contents of the file onto the screen you can try using PHP.

<?php
    $myfilename = "mytextfile.txt";
    if(file_exists($myfilename)){
      echo file_get_contents($myfilename);
    }
?>

Simplest way to set image as JPanel background

public demo1() {
    initComponents();
    ImageIcon img = new ImageIcon("C:\\Users\\AMIT TIWARI\\Documents\\NetBeansProjects\\try\\src\\com\\dd.jpeg"); //full path of image
    Image img2 = img.getImage().getScaledInstance(mylabel.getWidth(), mylabel.getHeight(),1);
    ImageIcon img3 = new ImageIcon(img2);
    mylabel.setIcon(img3);
}

Which to use <div class="name"> or <div id="name">?

Read the spec for the attributes and for CSS.

  • id must be unique. class does not have to be
  • id has higher (highest!) specificity in CSS
  • Elements can have multiple non-ordinal classes (separated by spaces), but only one id
  • It is faster to select an element by it's ID when querying the DOM
  • id can be used as an anchor target (using the fragment of the request) for any element. name only works with anchors (<a>)

Java for loop syntax: "for (T obj : objects)"

Yes, It is called the for-each loop. Objects in the collectionName will be assigned one after one from the beginning of that collection, to the created object reference, 'objectName'. So in each iteration of the loop, the 'objectName' will be assigned an object from the 'collectionName' collection. The loop will terminate once when all the items(objects) of the 'collectionName' Collection have finished been assigning or simply the objects to get are over.

for (ObjectType objectName : collectionName.getObjects()){ //loop body> //You can use the 'objectName' here as needed and different objects will be //reepresented by it in each iteration. }

MySQL Error 1153 - Got a packet bigger than 'max_allowed_packet' bytes

You probably have to change it for both the client (you are running to do the import) AND the daemon mysqld that is running and accepting the import.

For the client, you can specify it on the command line:

mysql --max_allowed_packet=100M -u root -p database < dump.sql

Also, change the my.cnf or my.ini file under the mysqld section and set:

max_allowed_packet=100M

or you could run these commands in a MySQL console connected to that same server:

set global net_buffer_length=1000000; 
set global max_allowed_packet=1000000000;

(Use a very large value for the packet size.)

Loop through each row of a range in Excel

Something like this:

Dim rng As Range
Dim row As Range
Dim cell As Range

Set rng = Range("A1:C2")

For Each row In rng.Rows
  For Each cell in row.Cells
    'Do Something
  Next cell
Next row

Oracle Convert Seconds to Hours:Minutes:Seconds

My version. Show Oracle DB uptime in format DDd HHh MMm SSs

select to_char(trunc((((86400*x)/60)/60)/24)) || 'd ' ||
   to_char(trunc(((86400*x)/60)/60)-24*(trunc((((86400*x)/60)/60)/24)), 'FM00') || 'h ' ||
   to_char(trunc((86400*x)/60)-60*(trunc(((86400*x)/60)/60)), 'FM00') || 'm ' ||
   to_char(trunc(86400*x)-60*(trunc((86400*x)/60)), 'FM00') || 's' "UPTIME"
 from (select (sysdate - t.startup_time) x from V$INSTANCE t);

idea from Date / Time Arithmetic with Oracle 9/10

Navigation drawer: How do I set the selected item at startup?

API 23 provides the following method:

navigationView.setCheckedItem(R.id.nav_item_id);

However, for some reason this function did not cause the code behind the navigation item to run. The method certainly highlights the item in the navigation drawer, or 'checks' it, but it does not seem to call the OnNavigationItemSelectedListener resulting in a blank screen on start-up if your start-up screen depends on navigation drawer selections. It is possible to manually call the listener, but it seems hacky:

if (savedInstanceState == null) this.onNavigationItemSelected(navigationView.getMenu().getItem(0));

The above code assumes:

  1. You have implemented NavigationView.OnNavigationItemSelectedListener in your activity
  2. You have already called:
    navigationView.setNavigationItemSelectedListener(this);
  3. The item you wish to select is located in position 0

Get root view from current activity

anyview.getRootView(); will be the easiest way.

phpinfo() is not working on my CentOS server

I accidentally set the wrong file permissions. After chmod 644 phpinfo.php the info indeed showed up as expected.

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

If you've just killed a big query, it will take time to rollback. If you issue another query before the killed query is done rolling back, you might get a lock timeout error. That's what happened to me. The solution was just to wait a bit.

Details:

I had issued a DELETE query to remove about 900,000 out of about 1 million rows.

I ran this by mistake (removes only 10% of the rows): DELETE FROM table WHERE MOD(id,10) = 0

Instead of this (removes 90% of the rows): DELETE FROM table WHERE MOD(id,10) != 0

I wanted to remove 90% of the rows, not 10%. So I killed the process in the MySQL command line, knowing that it would roll back all the rows it had deleted so far.

Then I ran the correct command immediately, and got a lock timeout exceeded error soon after. I realized that the lock might actually be the rollback of the killed query still happening in the background. So I waited a few seconds and re-ran the query.

Npm install cannot find module 'semver'

Having just encountered this on Arch Linux 4.13.3, I solved the issue by simply reinstalling semver:

pacman -S semver

List of <p:ajax> events

Unfortunatelly, Ajax events are poorly documented and I haven't found any comprehensive list. For example, User Guide v. 3.5 lists itemChange event for p:autoComplete, but forgets to mention change event.

If you want to find out which events are supported:

  1. Download and unpack primefaces source jar
  2. Find the JavaScript file, where your component is defined (for example, most form components such as SelectOneMenu are defined in forms.js)
  3. Search for this.cfg.behaviors references

For example, this section is responsible for launching toggleSelect event in SelectCheckboxMenu component:

fireToggleSelectEvent: function(checked) {
    if(this.cfg.behaviors) {
        var toggleSelectBehavior = this.cfg.behaviors['toggleSelect'];

        if(toggleSelectBehavior) {
            var ext = {
                params: [{name: this.id + '_checked', value: checked}]
            }
        }

        toggleSelectBehavior.call(this, null, ext);
    }
},

Java: how do I check if a Date is within a certain range?

your logic would work fine . As u mentioned the dates ur getting from the database are in timestamp , You just need to convert timestamp to date first and then use this logic.

Also dont forget to check for null dates.

here m sharing a bit to convert from Timestamp to date.

public static Date convertTimeStamptoDate(String val) throws Exception {

    DateFormat df = null;
    Date date = null;

    try {
        df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        date = df.parse(val);
        // System.out.println("Date Converted..");
        return date;
    } catch (Exception ex) {
        System.out.println(ex);
        return convertDate2(val);
    } finally {
        df = null;
        date = null;
    }
}

How to get response status code from jQuery.ajax?

It is probably more idiomatic jQuery to use the statusCode property of the parameter object passed to the the $.ajax function:

$.ajax({
  statusCode: {
    500: function(xhr) {
      if(window.console) console.log(xhr.responseText);
    }
  }
});

However, as Livingston Samuel said, it is not possible to catch 301 status codes in javascript.

Define an <img>'s src attribute in CSS

just this as img tag is a content element

img {
    content:url(http://example.com/image.png);
}

Pipenv: Command Not Found

Where Python store packages

Before jumping into the command that will install pipenv, it is worth understanding where pip installs Python packages.

Global site-packages is where Python installs packages that will be available to all users and all Python applications on the system. You can check the global site package with the command

python -m site

For example, on Linux with Python 3.7 the path is usually

/usr/lib/python3.7/dist-packages/setuptools

User site-packages is where Python installs packages available only for you. But the packages will still be visible to all Python projects that you create. You can get the path with

python -m site --user-base

On Linux with Python 3.7 the path is usually

~/.local/lib/python3.7/site-packages

Using Python 3.x

On most Linux and other Unices, usually Python 2 and Python 3 is installed side-by-side. The default Python 3 executable is almost always python3. pip may be available as either of the following, depending on your Linux distribution

pip3
python3-pip
python36-pip
python3.6-pip

Linux

Avoid using pip with sudo! Yes, it's the most convenient way to install Python packages and the executable is available at /usr/local/bin/pipenv, but it also mean that specific package is always visible for all users, and all Python projects that you create. Instead, use per-user site packages instead with --user

pip3 install --user pipenv

pipenv is available at

~/.local/bin/pipenv

macOS

On macOS, Homebrew is the recommended way to install Python. You can easily upgrade Python, install multiple versions of Python and switch between versions using Homebrew.

If you are using Homebrew'ed Python, pip install --user is disabled. The global site-package is located at

/usr/local/lib/python3.y/site-packages

and you can safely install Python packages here. Python 3.y also searches for modules in:

 /Library/Python/3.y/site-packages
 ~/Library/Python/3.y/lib/python/site-packages

Windows

For legacy reasons, Python is installed in C:\Python37. The Python executable is usually named py.exe, and you can run pip with py -m pip.

Global site packages is installed in

C:\Python37\lib\site-packages

Since you don't usually share your Windows devices, it is also OK to install a package globally

py -m pip install pipenv

pipenv is now available at

C:\Python37\Scripts\pipenv.exe

I don't recommend install Python packages in Windows with --user, because the default user site-package directory is in your Windows roaming profile

C:\Users\user\AppData\Roaming\Python\Python37\site-packages 

The roaming profile is used in Terminal Services (Remote Desktop, Citrix, etc) and when you log on / off in a corporate environment. Slow login, logoff and reboot in Windows can be caused by a large roaming profile.

How do I go about adding an image into a java project with eclipse?

Place the image in a source folder, not a regular folder. That is: right-click on project -> New -> Source Folder. Place the image in that source folder. Then:

InputStream input = classLoader.getResourceAsStream("image.jpg");

Note that the path is omitted. That's because the image is directly in the root of the path. You can add folders under your source folder to break it down further if you like. Or you can put the image under your existing source folder (usually called src).

google console error `OR-IEH-01`

It looks like your Google Play registration payment didn’t process. This can happen sometimes if a card has expired, the credit card or credit card verification (CVC) number was entered incorrectly, or if your billing address doesn't match the address in your Google Payments account.

Here’s how you can find the details of your transaction:

  1. Sign in to your Google Payments account at https://payments.google.com.

  2. On the left menu, select the “Subscriptions and services” page.

  3. On the “Other purchase activity” card, click View purchases.

  4. Click the “Google Play” registration transaction to see your payment method.

  5. You can click “Payment methods” on the left menu if you need to edit the addresses on your Google Payments account.

To add a new credit or debit card to your account, you can follow the instructions on the Google Payments Help Center (https://support.google.com/payments/answer/6220309).

Why has it failed to load main-class manifest attribute from a JAR file?

I faced the same problem. This unix command is not able to find the main class. This is because the runtime and compile time JDK versions are different. Make the jar through eclipse after changing the java compiler version. The following link helped me.

http://crunchify.com/exception-in-thread-main-java-lang-unsupportedclassversionerror-comcrunchifymain-unsupported-major-minor-version-51-0/

Try running the jar created after this step and then execute it

How to select rows with one or more nulls from a pandas DataFrame without listing columns explicitly?

If you want to filter rows by a certain number of columns with null values, you may use this:

df.iloc[df[(df.isnull().sum(axis=1) >= qty_of_nuls)].index]

So, here is the example:

Your dataframe:

>>> df = pd.DataFrame([range(4), [0, np.NaN, 0, np.NaN], [0, 0, np.NaN, 0], range(4), [np.NaN, 0, np.NaN, np.NaN]])
>>> df
     0    1    2    3
0  0.0  1.0  2.0  3.0
1  0.0  NaN  0.0  NaN
2  0.0  0.0  NaN  0.0
3  0.0  1.0  2.0  3.0
4  NaN  0.0  NaN  NaN

If you want to select the rows that have two or more columns with null value, you run the following:

>>> qty_of_nuls = 2
>>> df.iloc[df[(df.isnull().sum(axis=1) >=qty_of_nuls)].index]
     0    1    2   3
1  0.0  NaN  0.0 NaN
4  NaN  0.0  NaN NaN

How to convert text column to datetime in SQL

This works:

SELECT STR_TO_DATE(dateColumn, '%c/%e/%Y %r') FROM tabbleName WHERE 1

How to watch and reload ts-node when TypeScript files change

Here's an alternative to the HeberLZ's answer, using npm scripts.

My package.json:

  "scripts": {
    "watch": "nodemon -e ts -w ./src -x npm run watch:serve",
    "watch:serve": "ts-node --inspect src/index.ts"
  },
  • -e flag sets the extenstions to look for,
  • -w sets the watched directory,
  • -x executes the script.

--inspect in the watch:serve script is actually a node.js flag, it just enables debugging protocol.

Google OAuth 2 authorization - Error: redirect_uri_mismatch

In my case I added

https://websitename.com/sociallogin/social/callback/?hauth.done=Google

in Authorized redirect URIs section and it worked for me

document.getElementById("remember").visibility = "hidden"; not working on a checkbox

This is the job for style property:

document.getElementById("remember").style.visibility = "visible";

Heap vs Binary Search Tree (BST)

Summary

          Type      BST (*)   Heap
Insert    average   log(n)    1
Insert    worst     log(n)    log(n) or n (***)
Find any  worst     log(n)    n
Find max  worst     1 (**)    1
Create    worst     n log(n)  n
Delete    worst     log(n)    log(n)

All average times on this table are the same as their worst times except for Insert.

  • *: everywhere in this answer, BST == Balanced BST, since unbalanced sucks asymptotically
  • **: using a trivial modification explained in this answer
  • ***: log(n) for pointer tree heap, n for dynamic array heap

Advantages of binary heap over a BST

  • average time insertion into a binary heap is O(1), for BST is O(log(n)). This is the killer feature of heaps.

    There are also other heaps which reach O(1) amortized (stronger) like the Fibonacci Heap, and even worst case, like the Brodal queue, although they may not be practical because of non-asymptotic performance: Are Fibonacci heaps or Brodal queues used in practice anywhere?

  • binary heaps can be efficiently implemented on top of either dynamic arrays or pointer-based trees, BST only pointer-based trees. So for the heap we can choose the more space efficient array implementation, if we can afford occasional resize latencies.

  • binary heap creation is O(n) worst case, O(n log(n)) for BST.

Advantage of BST over binary heap

  • search for arbitrary elements is O(log(n)). This is the killer feature of BSTs.

    For heap, it is O(n) in general, except for the largest element which is O(1).

"False" advantage of heap over BST

  • heap is O(1) to find max, BST O(log(n)).

    This is a common misconception, because it is trivial to modify a BST to keep track of the largest element, and update it whenever that element could be changed: on insertion of a larger one swap, on removal find the second largest. Can we use binary search tree to simulate heap operation? (mentioned by Yeo).

    Actually, this is a limitation of heaps compared to BSTs: the only efficient search is that for the largest element.

Average binary heap insert is O(1)

Sources:

Intuitive argument:

  • bottom tree levels have exponentially more elements than top levels, so new elements are almost certain to go at the bottom
  • heap insertion starts from the bottom, BST must start from the top

In a binary heap, increasing the value at a given index is also O(1) for the same reason. But if you want to do that, it is likely that you will want to keep an extra index up-to-date on heap operations How to implement O(logn) decrease-key operation for min-heap based Priority Queue? e.g. for Dijkstra. Possible at no extra time cost.

GCC C++ standard library insert benchmark on real hardware

I benchmarked the C++ std::set (Red-black tree BST) and std::priority_queue (dynamic array heap) insert to see if I was right about the insert times, and this is what I got:

enter image description here

  • benchmark code
  • plot script
  • plot data
  • tested on Ubuntu 19.04, GCC 8.3.0 in a Lenovo ThinkPad P51 laptop with CPU: Intel Core i7-7820HQ CPU (4 cores / 8 threads, 2.90 GHz base, 8 MB cache), RAM: 2x Samsung M471A2K43BB1-CRC (2x 16GiB, 2400 Mbps), SSD: Samsung MZVLB512HAJQ-000L7 (512GB, 3,000 MB/s)

So clearly:

  • heap insert time is basically constant.

    We can clearly see dynamic array resize points. Since we are averaging every 10k inserts to be able to see anything at all above system noise, those peaks are in fact about 10k times larger than shown!

    The zoomed graph excludes essentially only the array resize points, and shows that almost all inserts fall under 25 nanoseconds.

  • BST is logarithmic. All inserts are much slower than the average heap insert.

  • BST vs hashmap detailed analysis at: What data structure is inside std::map in C++?

GCC C++ standard library insert benchmark on gem5

gem5 is a full system simulator, and therefore provides an infinitely accurate clock with with m5 dumpstats. So I tried to use it to estimate timings for individual inserts.

enter image description here

Interpretation:

  • heap is still constant, but now we see in more detail that there are a few lines, and each higher line is more sparse.

    This must correspond to memory access latencies are done for higher and higher inserts.

  • TODO I can't really interpret the BST fully one as it does not look so logarithmic and somewhat more constant.

    With this greater detail however we can see can also see a few distinct lines, but I'm not sure what they represent: I would expect the bottom line to be thinner, since we insert top bottom?

Benchmarked with this Buildroot setup on an aarch64 HPI CPU.

BST cannot be efficiently implemented on an array

Heap operations only need to bubble up or down a single tree branch, so O(log(n)) worst case swaps, O(1) average.

Keeping a BST balanced requires tree rotations, which can change the top element for another one, and would require moving the entire array around (O(n)).

Heaps can be efficiently implemented on an array

Parent and children indexes can be computed from the current index as shown here.

There are no balancing operations like BST.

Delete min is the most worrying operation as it has to be top down. But it can always be done by "percolating down" a single branch of the heap as explained here. This leads to an O(log(n)) worst case, since the heap is always well balanced.

If you are inserting a single node for every one you remove, then you lose the advantage of the asymptotic O(1) average insert that heaps provide as the delete would dominate, and you might as well use a BST. Dijkstra however updates nodes several times for each removal, so we are fine.

Dynamic array heaps vs pointer tree heaps

Heaps can be efficiently implemented on top of pointer heaps: Is it possible to make efficient pointer-based binary heap implementations?

The dynamic array implementation is more space efficient. Suppose that each heap element contains just a pointer to a struct:

  • the tree implementation must store three pointers for each element: parent, left child and right child. So the memory usage is always 4n (3 tree pointers + 1 struct pointer).

    Tree BSTs would also need further balancing information, e.g. black-red-ness.

  • the dynamic array implementation can be of size 2n just after a doubling. So on average it is going to be 1.5n.

On the other hand, the tree heap has better worst case insert, because copying the backing dynamic array to double its size takes O(n) worst case, while the tree heap just does new small allocations for each node.

Still, the backing array doubling is O(1) amortized, so it comes down to a maximum latency consideration. Mentioned here.

Philosophy

  • BSTs maintain a global property between a parent and all descendants (left smaller, right bigger).

    The top node of a BST is the middle element, which requires global knowledge to maintain (knowing how many smaller and larger elements are there).

    This global property is more expensive to maintain (log n insert), but gives more powerful searches (log n search).

  • Heaps maintain a local property between parent and direct children (parent > children).

    The top node of a heap is the big element, which only requires local knowledge to maintain (knowing your parent).

Comparing BST vs Heap vs Hashmap:

  • BST: can either be either a reasonable:

    • unordered set (a structure that determines if an element was previously inserted or not). But hashmap tends to be better due to O(1) amortized insert.
    • sorting machine. But heap is generally better at that, which is why heapsort is much more widely known than tree sort
  • heap: is just a sorting machine. Cannot be an efficient unordered set, because you can only check for the smallest/largest element fast.

  • hash map: can only be an unordered set, not an efficient sorting machine, because the hashing mixes up any ordering.

Doubly-linked list

A doubly linked list can be seen as subset of the heap where first item has greatest priority, so let's compare them here as well:

  • insertion:
    • position:
      • doubly linked list: the inserted item must be either the first or last, as we only have pointers to those elements.
      • binary heap: the inserted item can end up in any position. Less restrictive than linked list.
    • time:
      • doubly linked list: O(1) worst case since we have pointers to the items, and the update is really simple
      • binary heap: O(1) average, thus worse than linked list. Tradeoff for having more general insertion position.
  • search: O(n) for both

An use case for this is when the key of the heap is the current timestamp: in that case, new entries will always go to the beginning of the list. So we can even forget the exact timestamp altogether, and just keep the position in the list as the priority.

This can be used to implement an LRU cache. Just like for heap applications like Dijkstra, you will want to keep an additional hashmap from the key to the corresponding node of the list, to find which node to update quickly.

Comparison of different Balanced BST

Although the asymptotic insert and find times for all data structures that are commonly classified as "Balanced BSTs" that I've seen so far is the same, different BBSTs do have different trade-offs. I haven't fully studied this yet, but it would be good to summarize these trade-offs here:

  • Red-black tree. Appears to be the most commonly used BBST as of 2019, e.g. it is the one used by the GCC 8.3.0 C++ implementation
  • AVL tree. Appears to be a bit more balanced than BST, so it could be better for find latency, at the cost of slightly more expensive finds. Wiki summarizes: "AVL trees are often compared with red–black trees because both support the same set of operations and take [the same] time for the basic operations. For lookup-intensive applications, AVL trees are faster than red–black trees because they are more strictly balanced. Similar to red–black trees, AVL trees are height-balanced. Both are, in general, neither weight-balanced nor mu-balanced for any mu < 1/2; that is, sibling nodes can have hugely differing numbers of descendants."
  • WAVL. The original paper mentions advantages of that version in terms of bounds on rebalancing and rotation operations.

See also

Similar question on CS: https://cs.stackexchange.com/questions/27860/whats-the-difference-between-a-binary-search-tree-and-a-binary-heap

How do I force a vertical scrollbar to appear?

Give your body tag an overflow: scroll;

body {
    overflow: scroll;
}

or if you only want a vertical scrollbar use overflow-y

body {
    overflow-y: scroll;
}

The most sophisticated way for creating comma-separated Strings from a Collection/Array/List?

There's a lot of manual solutions to this, but I wanted to reiterate and update Julie's answer above. Use google collections Joiner class.

Joiner.on(", ").join(34, 26, ..., 2)

It handles var args, iterables and arrays and properly handles separators of more than one char (unlike gimmel's answer). It will also handle null values in your list if you need it to.

How can I get nth element from a list?

You can use !!, but if you want to do it recursively then below is one way to do it:

dataAt :: Int -> [a] -> a
dataAt _ [] = error "Empty List!"
dataAt y (x:xs)  | y <= 0 = x
                 | otherwise = dataAt (y-1) xs

Xcode : Adding a project as a build dependency

Just close the Project you want to add , then drag and drop the file .

how to loop through json array in jquery?

Try this:

for(var i = 0; i < data.length; i++){
    console.log(data[i].com)
}

Twitter Bootstrap Datepicker within modal window

This solutions worked perfectly for me to render the datepicker on top of bootstrap modal.

http://jsfiddle.net/cmpgtuwy/654/

HTML

<br/>
<div class="wrapper">
Some content goes here<br />
Some more content.
<div class="row">
<div class="col-xs-4">

<!-- padding for jsfiddle -->
<div class="input-group date" id="dtp">
<input type="text" class="form-control" />  
<span class="input-group-addon">
  <span class="glyphicon-calendar glyphicon"></span>
</span>
</div>
</div>
</div>
</div>

Javascript

$('#dtp').datetimepicker({
format: 'MMM D, YYYY',
widgetParent: 'body'});


$('#dtp').on('dp.show', function() {
      var datepicker = $('body').find('.bootstrap-datetimepicker-widget:last');
      if (datepicker.hasClass('bottom')) {
        var top = $(this).offset().top + $(this).outerHeight();
        var left = $(this).offset().left;
        datepicker.css({
          'top': top + 'px',
          'bottom': 'auto',
          'left': left + 'px'
        });
      }
      else if (datepicker.hasClass('top')) {
        var top = $(this).offset().top - datepicker.outerHeight();
        var left = $(this).offset().left;
        datepicker.css({
          'top': top + 'px',
          'bottom': 'auto',
          'left': left + 'px'
        });
      }
    });

CSS

.wrapper {
height: 100px;
overflow: auto;}
body {
position: relative;
}

How do I escape a single quote in SQL Server?

This should work: use a back slash and put a double quote

"UPDATE my_table SET row =\"hi, my name's tim.\";

Loop Through Each HTML Table Column and Get the Data using jQuery

When you create your table, put your td with class = "suma"

$(function(){   

   //funcion suma todo

   var sum = 0;
   $('.suma').each(function(x,y){
       sum += parseInt($(this).text());                                   
   })           
   $('#lblTotal').text(sum);   

   // funcion suma por check                                           

    $( "input:checkbox").change(function(){
    if($(this).is(':checked')){     
        $(this).parent().parent().find('td:last').addClass('suma2');
   }else{       
        $(this).parent().parent().find('td:last').removeClass('suma2');
   }    
   suma2Total();                                                           
   })                                                      

   function suma2Total(){
      var sum2 = 0;
      $('.suma2').each(function(x,y){
        sum2 += parseInt($(this).text());       
      })
      $('#lblTotal2').text(sum2);                                              
   }                                                                      
});

Ejemplo completo

Comparing Java enum members: == or equals()?

Using anything other than == to compare enum constants is nonsense. It's like comparing class objects with equals – don't do it!

However, there was a nasty bug (BugId 6277781) in Sun JDK 6u10 and earlier that might be interesting for historical reasons. This bug prevented proper use of == on deserialized enums, although this is arguably somewhat of a corner case.

How do we use runOnUiThread in Android?

Just wrap it as a function, then call this function from your background thread.

public void debugMsg(String msg) {
    final String str = msg;
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            mInfo.setText(str);
        }
    });
}

how to dynamically add options to an existing select in vanilla javascript

I guess something like this would do the job.

var option = document.createElement("option");
option.text = "Text";
option.value = "myvalue";
var select = document.getElementById("daySelect");
select.appendChild(option);

Importing variables from another file?

script1.py

title="Hello world"

script2.py is where we using script1 variable

Method 1:

import script1
print(script1.title)

Method 2:

from script1 import title
print(title)

Reading in double values with scanf in c

Format specifier in printf should be %f for doubl datatypes since float datatyles eventually convert to double datatypes inside printf.

There is no provision to print float data. Please find the discussion here : Correct format specifier for double in printf

String.Format alternative in C++

For completeness, the boost way would be to use boost::format

cout << boost::format("%s %s > %s") % a % b % c;

Take your pick. The boost solution has the advantage of type safety with the sprintf format (for those who find the << syntax a bit clunky).

How to output HTML from JSP <%! ... %> block?

I suppose this would help:

<%! 
   String someOutput() {
     return "Some Output";
  }
%>
...
<%= someOutput() %>

Anyway, it isn't a good idea to have code in a view.

What is the best Java library to use for HTTP POST, GET etc.?

I want to mention the Ning Async Http Client Library. I've never used it but my colleague raves about it as compared to the Apache Http Client, which I've always used in the past. I was particularly interested to learn it is based on Netty, the high-performance asynchronous i/o framework, with which I am more familiar and hold in high esteem.

Java converting int to hex and back again

It overflows, because the number is negative.

Try this and it will work:

int n = (int) Long.parseLong("ffff8000", 16);

Displaying Windows command prompt output and redirecting it to a file

send output to console, append to console log, delete output from current command

dir  >> usb-create.1 && type usb-create.1 >> usb-create.log | type usb-create.1 && del usb-create.1

Log record changes in SQL server in an audit table

Hey It's very simple see this

@OLD_GUEST_NAME = d.GUEST_NAME from deleted d;

this variable will store your old deleted value and then you can insert it where you want.

for example-

Create trigger testupdate on test for update, delete
  as
declare @tableid varchar(50);
declare @testid varchar(50);
declare @newdata varchar(50);
declare @olddata varchar(50);


select @tableid = count(*)+1 from audit_test
select @testid=d.tableid from inserted d;
select @olddata = d.data from deleted d;
select @newdata = i.data from inserted i;

insert into audit_test (tableid, testid, olddata, newdata) values (@tableid, @testid, @olddata, @newdata)

go

How to generate a git patch for a specific commit?

Try:

git format-patch -1 <sha>

or

git format-patch -1 HEAD

According to the documentation link above, the -1 flag tells git how many commits should be included in the patch;

-<n>

     Prepare patches from the topmost commits.


Apply the patch with the command:

git am < file.patch

SQL - ORDER BY 'datetime' DESC

Try:

SELECT post_datetime 
FROM post 
WHERE type = 'published' 
ORDER BY post_datetime DESC 
LIMIT 3

How to handle anchor hash linking in AngularJS

I could do this like so:

<li>
<a href="#/#about">About</a>
</li>

How to calculate a logistic sigmoid function in Python?

I feel many might be interested in free parameters to alter the shape of the sigmoid function. Second for many applications you want to use a mirrored sigmoid function. Third you might want to do a simple normalization for example the output values are between 0 and 1.

Try:

def normalized_sigmoid_fkt(a, b, x):
   '''
   Returns array of a horizontal mirrored normalized sigmoid function
   output between 0 and 1
   Function parameters a = center; b = width
   '''
   s= 1/(1+np.exp(b*(x-a)))
   return 1*(s-min(s))/(max(s)-min(s)) # normalize function to 0-1

And to draw and compare:

def draw_function_on_2x2_grid(x): 
    fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)
    plt.subplots_adjust(wspace=.5)
    plt.subplots_adjust(hspace=.5)

    ax1.plot(x, normalized_sigmoid_fkt( .5, 18, x))
    ax1.set_title('1')

    ax2.plot(x, normalized_sigmoid_fkt(0.518, 10.549, x))
    ax2.set_title('2')

    ax3.plot(x, normalized_sigmoid_fkt( .7, 11, x))
    ax3.set_title('3')

    ax4.plot(x, normalized_sigmoid_fkt( .2, 14, x))
    ax4.set_title('4')
    plt.suptitle('Different normalized (sigmoid) function',size=10 )

    return fig

Finally:

x = np.linspace(0,1,100)
Travel_function = draw_function_on_2x2_grid(x)

Sigmoid functions graph

Eclipse - "Workspace in use or cannot be created, chose a different one."

Running eclipse in Administrator Mode fixed it for me. You can do this by [Right Click] -> Run as Administrator on the eclipse.exe from your install dir.

I was on a working environment with win7 machine having restrictive permission. I also did remove the .lock and .log files but that did not help. It can be a combination of all as well that made it work.

Can I call an overloaded constructor from another constructor of the same class in C#?

EDIT: According to the comments on the original post this is a C# question.

Short answer: yes, using the this keyword.

Long answer: yes, using the this keyword, and here's an example.

class MyClass
{
   private object someData;

   public MyClass(object data)
   {
      this.someData = data;
   }

   public MyClass() : this(new object())
   {
      // Calls the previous constructor with a new object, 
      // setting someData to that object
   }
}

Using awk to print all columns from the nth to the last

Perl:

@m=`ls -ltr dir | grep ^d | awk '{print \$6,\$7,\$8,\$9}'`;
foreach $i (@m)
{
        print "$i\n";

}

mysql after insert trigger which updates another table's column

Maybe remove the semi-colon after set because now the where statement doesn't belong to the update statement. Also the idRequest could be a problem, better write BookingRequest.idRequest

Adding hours to JavaScript Date object?

There is an add in the Datejs library.

And here are the JavaScript date methods. kennebec wisely mentioned getHours() and setHours();

remove duplicates from sql union

If you are using T-SQL you could use a temporary table in a stored procedure and update or insert the records of your query accordingly.

Difference between a User and a Login in SQL Server

I think there is a really good MSDN blog post about this topic by Laurentiu Cristofor:

The first important thing that needs to be understood about SQL Server security is that there are two security realms involved - the server and the database. The server realm encompasses multiple database realms. All work is done in the context of some database, but to get to do the work, one needs to first have access to the server and then to have access to the database.

Access to the server is granted via logins. There are two main categories of logins: SQL Server authenticated logins and Windows authenticated logins. I will usually refer to these using the shorter names of SQL logins and Windows logins. Windows authenticated logins can either be logins mapped to Windows users or logins mapped to Windows groups. So, to be able to connect to the server, one must have access via one of these types or logins - logins provide access to the server realm.

But logins are not enough, because work is usually done in a database and databases are separate realms. Access to databases is granted via users.

Users are mapped to logins and the mapping is expressed by the SID property of logins and users. A login maps to a user in a database if their SID values are identical. Depending on the type of login, we can therefore have a categorization of users that mimics the above categorization for logins; so, we have SQL users and Windows users and the latter category consists of users mapped to Windows user logins and of users mapped to Windows group logins.

Let's take a step back for a quick overview: a login provides access to the server and to further get access to a database, a user mapped to the login must exist in the database.

that's the link to the full post.

single line comment in HTML

No, <!-- ... --> is the only comment syntax in HTML.

Generate war file from tomcat webapp folder

Its just like creating a WAR file of your project, you can do it in several ways (from Eclipse, command line, maven).

If you want to do from command line, the command is

jar -cvf my_web_app.war * 

Which means, "compress everything in this directory into a file named my_web_app.war" (c=create, v=verbose, f=file)

grep for multiple strings in file on different lines (ie. whole file, not line based search)?

This is a blending of glenn jackman's and kurumi's answers which allows an arbitrary number of regexes instead of an arbitrary number of fixed words or a fixed set of regexes.

#!/usr/bin/awk -f
# by Dennis Williamson - 2011-01-25

BEGIN {
    for (i=ARGC-2; i>=1; i--) {
        patterns[ARGV[i]] = 0;
        delete ARGV[i];
    }
}

{
    for (p in patterns)
        if ($0 ~ p)
            matches[p] = 1
            # print    # the matching line could be printed
}

END {
    for (p in patterns) {
        if (matches[p] != 1)
            exit 1
    }
}

Run it like this:

./multigrep.awk Dansk Norsk Svenska 'Language: .. - A.*c' dvdfile.dat

How to fix Uncaught InvalidValueError: setPosition: not a LatLng or LatLngLiteral: in property lat: not a number?

I had the same problem when setting the center of the map with map.setCenter(). Using Number() solved for me. Had to use parseFloat to truncate the data.

code snippet:

 var centerLat = parseFloat(data.lat).toFixed(0);
 var centerLng = parseFloat(data.long).toFixed(0);
 map.setCenter({
      lat: Number(centerLat),
      lng: Number(centerLng)
 });

How do I clear the std::queue efficiently?

I do this (Using C++14):

std::queue<int> myqueue;
myqueue = decltype(myqueue){};

This way is useful if you have a non-trivial queue type that you don't want to build an alias/typedef for. I always make sure to leave a comment around this usage, though, to explain to unsuspecting / maintenance programmers that this isn't crazy, and done in lieu of an actual clear() method.

How to achieve function overloading in C?

Normally a wart to indicate the type is appended or prepended to the name. You can get away with macros is some instances, but it rather depends what you're trying to do. There's no polymorphism in C, only coercion.

Simple generic operations can be done with macros:

#define max(x,y) ((x)>(y)?(x):(y))

If your compiler supports typeof, more complicated operations can be put in the macro. You can then have the symbol foo(x) to support the same operation different types, but you can't vary the behaviour between different overloads. If you want actual functions rather than macros, you might be able to paste the type to the name and use a second pasting to access it (I haven't tried).

How does the "position: sticky;" property work?

Check if an ancestor element has overflow set (e.g. overflow:hidden); try toggling it. You may have to go up the DOM tree higher than you expect =).

This may affect your position:sticky on a descendant element.

Namespace for [DataContract]

[DataContract] and [DataMember] attribute are found in System.ServiceModel namespace which is in System.ServiceModel.dll .

System.ServiceModel uses the System and System.Runtime.Serialization namespaces to serialize the datamembers.

asp.net mvc @Html.CheckBoxFor

If only one checkbox should be checked in the same time use RadioButtonFor instead:

      @Html.RadioButtonFor(model => model.Type,1, new { @checked = "checked" }) fultime
      @Html.RadioButtonFor(model => model.Type,2) party
      @Html.RadioButtonFor(model => model.Type,3) next option...

If one more one could be checked in the same time use excellent extension: CheckBoxListFor:

Hope,it will help

How to export data from Excel spreadsheet to Sql Server 2008 table

From your SQL Server Management Studio, you open Object Explorer, go to your database where you want to load the data into, right click, then pick Tasks > Import Data.

This opens the Import Data Wizard, which typically works pretty well for importing from Excel. You can pick an Excel file, pick what worksheet to import data from, you can choose what table to store it into, and what the columns are going to be. Pretty flexible indeed.

You can run this as a one-off, or you can store it as a SQL Server Integration Services (SSIS) package into your file system, or into SQL Server itself, and execute it over and over again (even scheduled to run at a given time, using SQL Agent).

Update: yes, yes, yes, you can do all those things you keep asking - have you even tried at least once to run that wizard??

OK, here it comes - step by step:

Step 1: pick your Excel source

enter image description here

Step 2: pick your SQL Server target database

enter image description here

Step 3: pick your source worksheet (from Excel) and your target table in your SQL Server database; see the "Edit Mappings" button!

enter image description here

Step 4: check (and change, if needed) your mappings of Excel columns to SQL Server columns in the table:

enter image description here

Step 5: if you want to use it later on, save your SSIS package to SQL Server:

enter image description here

Step 6: - success! This is on a 64-bit machine, works like a charm - just do it!!

What does the explicit keyword mean?

Suppose, you have a class String:

class String {
public:
    String(int n); // allocate n bytes to the String object
    String(const char *p); // initializes object with char *p
};

Now, if you try:

String mystring = 'x';

The character 'x' will be implicitly converted to int and then the String(int) constructor will be called. But, this is not what the user might have intended. So, to prevent such conditions, we shall define the constructor as explicit:

class String {
public:
    explicit String (int n); //allocate n bytes
    String(const char *p); // initialize sobject with string p
};

Check if all values of array are equal

This works. You create a method on Array by using prototype.

if (Array.prototype.allValuesSame === undefined) {
  Array.prototype.allValuesSame = function() {
    for (let i = 1; i < this.length; i++) {
      if (this[i] !== this[0]) {
        return false;
      }
    }
    return true;
  }
}

Call this in this way:

let a = ['a', 'a', 'a'];
let b = a.allValuesSame(); // true
a = ['a', 'b', 'a'];
b = a.allValuesSame();     // false

Reading a registry key in C#

string InstallPath = (string)Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\MyApplication\AppPath", "Installed", null);    
if (InstallPath != null)
{
    // Do stuff
}

That code should get your value. You'll need to be

using Microsoft.Win32;

for that to work though.

execute function after complete page load

If you wanna call a js function in your html page use onload event. The onload event occurs when the user agent finishes loading a window or all frames within a FRAMESET. This attribute may be used with BODY and FRAMESET elements.

<body onload="callFunction();">
....
</body>

Can I specify maxlength in css?

As others have answered, there is no current way to add maxlength directly to a CSS class.

However, this creative solution can achieve what you are looking for.

I have the jQuery in a file named maxLengths.js which I reference in site (site.master for ASP)

run the snippet to see it in action, works well.

jquery, css, html:

_x000D_
_x000D_
$(function () {_x000D_
    $(".maxLenAddress1").keypress(function (event) {_x000D_
_x000D_
        if ($(this).val().length == 5) { /* obv 5 is too small for an address field, just want to use as an example though */_x000D_
            return false;_x000D_
        } else {_x000D_
            return true;_x000D_
        }_x000D_
_x000D_
    });_x000D_
});
_x000D_
.maxLenAddress1{} /* this is here mostly for intellisense usage, but can be altered if you like */
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
_x000D_
<input type="text" class="maxLenAddress1" />
_x000D_
_x000D_
_x000D_

The advantage of using this: if it is decided the max length for this type of field needs to be pushed out or in across your entire application you can change it in one spot. Comes in handy for field lengths for things like customer codes, full name fields, email fields, any field common across your application.

Overlapping elements in CSS

You can try using the transform: translate property by passing the appropriate values inside the parenthesis using the inspect element in Google chrome.

You have to set translate property in such way that both the <div> overlap each other then You can use JavaScript to show and hide both the <div> according to your requirements

React - Preventing Form Submission

You have prevent the default action of the event and return false from the function.

function onTestClick(e) {
    e.preventDefault();
    return false;
}

How to get response as String using retrofit without using GSON or any other library in android

** Update ** A scalars converter has been added to retrofit that allows for a String response with less ceremony than my original answer below.

Example interface --

public interface GitHubService {
    @GET("/users/{user}")
    Call<String> listRepos(@Path("user") String user);
}

Add the ScalarsConverterFactory to your retrofit builder. Note: If using ScalarsConverterFactory and another factory, add the scalars factory first.

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(BASE_URL)
    .addConverterFactory(ScalarsConverterFactory.create())
    // add other factories here, if needed.
    .build();

You will also need to include the scalars converter in your gradle file --

implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'

--- Original Answer (still works, just more code) ---

I agree with @CommonsWare that it seems a bit odd that you want to intercept the request to process the JSON yourself. Most of the time the POJO has all the data you need, so no need to mess around in JSONObject land. I suspect your specific problem might be better solved using a custom gson TypeAdapter or a retrofit Converter if you need to manipulate the JSON. However, retrofit provides more the just JSON parsing via Gson. It also manages a lot of the other tedious tasks involved in REST requests. Just because you don't want to use one of the features, doesn't mean you have to throw the whole thing out. There are times you just want to get the raw stream, so here is how to do it -

First, if you are using Retrofit 2, you should start using the Call API. Instead of sending an object to convert as the type parameter, use ResponseBody from okhttp --

public interface GitHubService {
    @GET("/users/{user}")
    Call<ResponseBody> listRepos(@Path("user") String user);
}

then you can create and execute your call --

GitHubService service = retrofit.create(GitHubService.class);
Call<ResponseBody> result = service.listRepos(username);
result.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Response<ResponseBody> response) {
        try {
            System.out.println(response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFailure(Throwable t) {
        e.printStackTrace();
    }
});

Note The code above calls string() on the response object, which reads the entire response into a String. If you are passing the body off to something that can ingest streams, you can call charStream() instead. See the ResponseBody docs.

Textarea that can do syntax highlighting on the fly?

I would recommend EditArea for live editing of a syntax hightlighted textarea.

How to create file execute mode permissions in Git on Windows?

There's no need to do this in two commits, you can add the file and mark it executable in a single commit:

C:\Temp\TestRepo>touch foo.sh

C:\Temp\TestRepo>git add foo.sh

C:\Temp\TestRepo>git ls-files --stage
100644 e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 0       foo.sh

As you note, after adding, the mode is 0644 (ie, not executable). However, we can mark it as executable before committing:

C:\Temp\TestRepo>git update-index --chmod=+x foo.sh

C:\Temp\TestRepo>git ls-files --stage
100755 e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 0       foo.sh

And now the file is mode 0755 (executable).

C:\Temp\TestRepo>git commit -m"Executable!"
[master (root-commit) 1f7a57a] Executable!
 1 file changed, 0 insertions(+), 0 deletions(-)
 create mode 100755 foo.sh

And now we have a single commit with a single executable file.

Showing an image from console in Python

You can also using the Python module Ipython, which in addition to displaying an image in the Spyder console can embed images in Jupyter notebook. In Spyder, the image will be displayed in full size, not scaled to fit the console.

from IPython.display import Image, display
display(Image(filename="mypic.png"))

JavaScript: Create and destroy class instance through class method

1- There is no way to actually destroy an object in javascript, but using delete, we could remove a reference from an object:

var obj = {};
obj.mypointer = null;
delete obj.mypointer;

2- The important point about the delete keyword is that it does not actually destroy the object BUT if only after deleting that reference to the object, there is no other reference left in the memory pointed to the same object, that object would be marked as collectible. The delete keyword deletes the reference but doesn't GC the actual object. it means if you have several references of the same object, the object will be collected just after you delete all the pointed references.

3- there are also some tricks and workarounds that could help us out, when we want to make sure we do not leave any memory leaks behind. for instance if you have an array consisting several objects, without any other pointed reference to those objects, if you recreate the array all those objects would be killed. For instance if you have var array = [{}, {}] overriding the value of the array like array = [] would remove the references to the two objects inside the array and those two objects would be marked as collectible.

4- for your solution the easiest way is just this:

var storage = {};
storage.instance = new Class();
//since 'storage.instance' is your only reference to the object, whenever you wanted to destroy do this:
storage.instance = null;
// OR
delete storage.instance;

As mentioned above, either setting storage.instance = null or delete storage.instance would suffice to remove the reference to the object and allow it to be cleaned up by the GC. The difference is that if you set it to null then the storage object still has a property called instance (with the value null). If you delete storage.instance then the storage object no longer has a property named instance.

and WHAT ABOUT destroy method ??

the paradoxical point here is if you use instance.destroy in the destroy function you have no access to the actual instance pointer, and it won't let you delete it.

The only way is to pass the reference to the destroy function and then delete it:

// Class constructor
var Class = function () {
     this.destroy = function (baseObject, refName) {
         delete baseObject[refName];
     };
};

// instanciate
var storage = {};
storage.instance = new Class();
storage.instance.destroy(object, "instance");
console.log(storage.instance); // now it is undefined

BUT if I were you I would simply stick to the first solution and delete the object like this:

storage.instance = null;
// OR
delete storage.instance;

WOW it was too much :)

Allow Access-Control-Allow-Origin header using HTML5 fetch API

This worked for me :

npm install -g local-cors-proxy

API endpoint that we want to request that has CORS issues:

https://www.yourdomain.com/test/list

Start Proxy:

lcp --proxyUrl https://www.yourdomain.com

 Proxy Active 

 Proxy Url: http://www.yourdomain.com:28080
 Proxy Partial: proxy
 PORT: 8010

Then in your client code, new API endpoint:

http://localhost:8010/proxy/test/list

End result will be a request to https://www.yourdomain.ie/test/list without the CORS issues!

Sending data from HTML form to a Python script in Flask

The form tag needs some attributes set:

  1. action: The URL that the form data is sent to on submit. Generate it with url_for. It can be omitted if the same URL handles showing the form and processing the data.
  2. method="post": Submits the data as form data with the POST method. If not given, or explicitly set to get, the data is submitted in the query string (request.args) with the GET method instead.
  3. enctype="multipart/form-data": When the form contains file inputs, it must have this encoding set, otherwise the files will not be uploaded and Flask won't see them.

The input tag needs a name parameter.

Add a view to handle the submitted data, which is in request.form under the same key as the input's name. Any file inputs will be in request.files.

@app.route('/handle_data', methods=['POST'])
def handle_data():
    projectpath = request.form['projectFilepath']
    # your code
    # return a response

Set the form's action to that view's URL using url_for:

<form action="{{ url_for('handle_data') }}" method="post">
    <input type="text" name="projectFilepath">
    <input type="submit">
</form>

How can I compile my Perl script so it can be executed on systems without perl installed?

pp can create an executable that includes perl and your script (and any module dependencies), but it will be specific to your architecture, so you couldn't run it on both Windows and linux for instance.

From its doc:

To make a stand-alone executable, suitable for running on a machine that doesn't have perl installed:

   % pp -o packed.exe source.pl        # makes packed.exe
   # Now, deploy 'packed.exe' to target machine...
   $ packed.exe                        # run it

(% and $ there are command prompts on different machines).

Using ffmpeg to change framerate

Simply specify the desired framerate in "-r " option before the input file:

ffmpeg -y -r 24 -i seeing_noaudio.mp4 seeing.mp4

Options affect the next file AFTER them. "-r" before an input file forces to reinterpret its header as if the video was encoded at the given framerate. No recompression is necessary. There was a small utility avifrate.exe to patch avi file headers directly to change the framerate. ffmpeg command above essentially does the same, but has to copy the entire file.

Why isn't ProjectName-Prefix.pch created automatically in Xcode 6?

I suspect because of modules, which remove the need for the #import <Cocoa/Cocoa.h>.

As to where to put code that you would put in a prefix header, there is no code you should put in a prefix header. Put your imports into the files that need them. Put your definitions into their own files. Put your macros...nowhere. Stop writing macros unless there is no other way (such as when you need __FILE__). If you do need macros, put them in a header and include it.

The prefix header was necessary for things that are huge and used by nearly everything in the whole system (like Foundation.h). If you have something that huge and ubiquitous, you should rethink your architecture. Prefix headers make code reuse hard, and introduce subtle build problems if any of the files listed can change. Avoid them until you have a serious build time problem that you can demonstrate is dramatically improved with a prefix header.

In that case you can create one and pass it into clang, but it's incredibly rare that it's a good idea.


EDIT: To your specific question about a HUD you use in all your view controllers, yes, you should absolutely import it into every view controller that actually uses it. This makes the dependencies clear. When you reuse your view controller in a new project (which is common if you build your controllers well), you will immediately know what it requires. This is especially important for categories, which can make code very hard to reuse if they're implicit.

The PCH file isn't there to get rid of listing dependencies. You should still import UIKit.h or Foundation.h as needed, as the Xcode templates do. The reason for the PCH is to improve build times when dealing with really massive headers (like in UIKit).

How to make layout with View fill the remaining space?

For those having the same glitch with <LinearLayout...> as I did:

It is important to specify android:layout_width="fill_parent", it will not work with wrap_content.

OTOH, you may omit android:layout_weight = "0", it is not required.

My code is basically the same as the code in https://stackoverflow.com/a/25781167/755804 (by Vivek Pandey)

Check if a number is odd or even in python

One of the simplest ways is to use de modulus operator %. If n % 2 == 0, then your number is even.

Hope it helps,

JavaScript - Replace all commas in a string

The third parameter of String.prototype.replace() function was never defined as a standard, so most browsers simply do not implement it.

The best way is to use regular expression with g (global) flag.

_x000D_
_x000D_
var myStr = 'this,is,a,test';_x000D_
var newStr = myStr.replace(/,/g, '-');_x000D_
_x000D_
console.log( newStr );  // "this-is-a-test"
_x000D_
_x000D_
_x000D_

Still have issues?

It is important to note, that regular expressions use special characters that need to be escaped. As an example, if you need to escape a dot (.) character, you should use /\./ literal, as in the regex syntax a dot matches any single character (except line terminators).

_x000D_
_x000D_
var myStr = 'this.is.a.test';_x000D_
var newStr = myStr.replace(/\./g, '-');_x000D_
_x000D_
console.log( newStr );  // "this-is-a-test"
_x000D_
_x000D_
_x000D_

If you need to pass a variable as a replacement string, instead of using regex literal you may create RegExp object and pass a string as the first argument of the constructor. The normal string escape rules (preceding special characters with \ when included in a string) will be necessary.

_x000D_
_x000D_
var myStr = 'this.is.a.test';_x000D_
var reStr = '\\.';_x000D_
var newStr = myStr.replace(new RegExp(reStr, 'g'), '-');_x000D_
_x000D_
console.log( newStr );  // "this-is-a-test"
_x000D_
_x000D_
_x000D_

Bash tool to get nth line from a file

Wow, all the possibilities!

Try this:

sed -n "${lineNum}p" $file

or one of these depending upon your version of Awk:

awk  -vlineNum=$lineNum 'NR == lineNum {print $0}' $file
awk -v lineNum=4 '{if (NR == lineNum) {print $0}}' $file
awk '{if (NR == lineNum) {print $0}}' lineNum=$lineNum $file

(You may have to try the nawk or gawk command).

Is there a tool that only does the print that particular line? Not one of the standard tools. However, sed is probably the closest and simplest to use.

how to delete installed library form react native project

  1. If it is a library based only on javascript, than you can just run npm uninstall --save package_name or npm uninstall --save-dev package_name
  2. If you've installed a library with native content that requires linking, and you've linked it with npm then you can do: npm unlink package_name then follow step 1
  3. If you've installed a library with native content manually, then just undo all the steps you took to add the library in the first place. Then follow step 1.

note rnpm as is deprecated

How do I get the different parts of a Flask request's url?

If you are using Python, I would suggest by exploring the request object:

dir(request)

Since the object support the method dict:

request.__dict__

It can be printed or saved. I use it to log 404 codes in Flask:

@app.errorhandler(404)
def not_found(e):
    with open("./404.csv", "a") as f:
        f.write(f'{datetime.datetime.now()},{request.__dict__}\n')
    return send_file('static/images/Darknet-404-Page-Concept.png', mimetype='image/png')

Get Number of Rows returned by ResultSet in Java

First, you should create Statement which can be move cursor by command:

Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

Then retrieve the ResultSet as below:

ResultSet rs = stmt.executeQuery(...);

Move cursor to the latest row and get it:

if (rs.last()) {
    int rows = rs.getRow();
    // Move to beginning
    rs.beforeFirst();
    ...
}

Then rows variable will contains number of rows returned by sql

Why binary_crossentropy and categorical_crossentropy give different performances for the same problem?

I came across an "inverted" issue — I was getting good results with categorical_crossentropy (with 2 classes) and poor with binary_crossentropy. It seems that problem was with wrong activation function. The correct settings were:

  • for binary_crossentropy: sigmoid activation, scalar target
  • for categorical_crossentropy: softmax activation, one-hot encoded target

How to stretch children to fill cross-axis?

  • The children of a row-flexbox container automatically fill the container's vertical space.

  • Specify flex: 1; for a child if you want it to fill the remaining horizontal space:

_x000D_
_x000D_
.wrapper {_x000D_
  display: flex;_x000D_
  flex-direction: row;_x000D_
  align-items: stretch;_x000D_
  width: 100%;_x000D_
  height: 5em;_x000D_
  background: #ccc;_x000D_
}_x000D_
.wrapper > .left_x000D_
{_x000D_
  background: #fcc;_x000D_
}_x000D_
.wrapper > .right_x000D_
{_x000D_
  background: #ccf;_x000D_
  flex: 1; _x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="left">Left</div>_x000D_
  <div class="right">Right</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

  • Specify flex: 1; for both children if you want them to fill equal amounts of the horizontal space:

_x000D_
_x000D_
.wrapper {_x000D_
  display: flex;_x000D_
  flex-direction: row;_x000D_
  align-items: stretch;_x000D_
  width: 100%;_x000D_
  height: 5em;_x000D_
  background: #ccc;_x000D_
}_x000D_
.wrapper > div _x000D_
{_x000D_
  flex: 1; _x000D_
}_x000D_
.wrapper > .left_x000D_
{_x000D_
  background: #fcc;_x000D_
}_x000D_
.wrapper > .right_x000D_
{_x000D_
  background: #ccf;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="left">Left</div>_x000D_
  <div class="right">Right</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to select lines between two marker patterns which may occur multiple times with awk/sed

Use awk with a flag to trigger the print when necessary:

$ awk '/abc/{flag=1;next}/mno/{flag=0}flag' file
def1
ghi1
jkl1
def2
ghi2
jkl2

How does this work?

  • /abc/ matches lines having this text, as well as /mno/ does.
  • /abc/{flag=1;next} sets the flag when the text abc is found. Then, it skips the line.
  • /mno/{flag=0} unsets the flag when the text mno is found.
  • The final flag is a pattern with the default action, which is to print $0: if flag is equal 1 the line is printed.

For a more detailed description and examples, together with cases when the patterns are either shown or not, see How to select lines between two patterns?.

SQL LIKE condition to check for integer?

That will select (by a regex) every book which has a title starting with a number, is that what you want?

SELECT * FROM books WHERE title ~ '^[0-9]'

if you want integers which start with specific digits, you could use:

SELECT * FROM books WHERE CAST(price AS TEXT) LIKE '123%'

or use (if all your numbers have the same number of digits (a constraint would be useful then))

SELECT * FROM books WHERE price BETWEEN 123000 AND 123999;

How can I create database tables from XSD files?

The best way to create the SQL database schema using an XSD file is a program called Altova XMLSpy, this is very simple:

  1. Create a new project
  2. On the DTDs / Schemas folder right clicking and selecting add files
  3. Selects the XSD file
  4. Open the XSD file added by double-clicking
  5. Go to the toolbar and look Conversion
  6. They select Create structure database from XML schema
  7. Selects the data source
  8. And finally give it to export the route calls immediately leave their scrip schemas with SQL Server to execute the query.

Hope it helps.

How to set shape's opacity?

Use this one, I've written this to my app,

<?xml version="1.0" encoding="utf-8"?>
<!--  res/drawable/rounded_edittext.xml -->
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" android:padding="10dp">
    <solid android:color="#882C383E"/>
    <corners
        android:bottomRightRadius="5dp"
        android:bottomLeftRadius="5dp"
        android:topLeftRadius="5dp"
        android:topRightRadius="5dp"/>
</shape>

C# Syntax - Example of a Lambda Expression - ForEach() over Generic List

You can traverse each string in the list and even you can search in the whole generic using a single statement this makes searching easier.

public static void main(string[] args)
{
List names = new List();

names.Add(“Saurabh”);
names.Add("Garima");
names.Add(“Vivek”);
names.Add(“Sandeep”);

string stringResult = names.Find( name => name.Equals(“Garima”));
}

When to use std::size_t?

size_t is returned by various libraries to indicate that the size of that container is non-zero. You use it when you get once back :0

However, in the your example above looping on a size_t is a potential bug. Consider the following:

for (size_t i = thing.size(); i >= 0; --i) {
  // this will never terminate because size_t is a typedef for
  // unsigned int which can not be negative by definition
  // therefore i will always be >= 0
  printf("the never ending story. la la la la");
}

the use of unsigned integers has the potential to create these types of subtle issues. Therefore imho I prefer to use size_t only when I interact with containers/types that require it.

Box shadow in IE7 and IE8

in ie8 you can try

-ms-filter: "progid:DXImageTransform.Microsoft.Shadow(Strength=5, Direction=135, Color='#c0c0c0')";
 filter: progid:DXImageTransform.Microsoft.Shadow(Strength=5, Direction=135, Color='#c0c0c0');

caveat: in ie8 you loose smooth fonts for some reason, they will look ragged

Are the decimal places in a CSS width respected?

Although fractional pixels may appear to round up on individual elements (as @SkillDrick demonstrates very well) it's important to know that the fractional pixels are actually respected in the actual box model.

This can best be seen when elements are stacked next to (or on top of) each other; in other words, if I were to place 400 0.5 pixel divs side by side, they would have the same width as a single 200 pixel div. If they all actually rounded up to 1px (as looking at individual elements would imply) we'd expect the 200px div to be half as long.

This can be seen in this runnable code snippet:

_x000D_
_x000D_
body {_x000D_
  color:            white;_x000D_
  font-family:      sans-serif;_x000D_
  font-weight:      bold;_x000D_
  background-color: #334;_x000D_
}_x000D_
_x000D_
.div_house div {_x000D_
  height:           10px;_x000D_
  background-color: orange;_x000D_
  display:          inline-block;_x000D_
}_x000D_
_x000D_
div#small_divs div {_x000D_
  width:            0.5px;_x000D_
}_x000D_
_x000D_
div#large_div div {_x000D_
  width:            200px;_x000D_
}
_x000D_
<div class="div_house" id="small_divs">_x000D_
  <p>0.5px div x 400</p>_x000D_
  <div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>_x000D_
</div>_x000D_
<br>_x000D_
<div class="div_house" id="large_div">_x000D_
  <p>200px div x 1</p>_x000D_
  <div></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Is there a library function for Root mean square error (RMSE) in python?

This is probably faster?:

n = len(predictions)
rmse = np.linalg.norm(predictions - targets) / np.sqrt(n)

Convert String to equivalent Enum value

Use static method valueOf(String) defined for each enum.

For example if you have enum MyEnum you can say MyEnum.valueOf("foo")

JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value

Well, what I do on every project is a mix of the options above.

First, add the jsr310 dependency:

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
</dependency>

Important detail: put this dependency on the top of your depedencies list. I already see a project where the Localdate error persists even with this dependency on the pom.xml. But changing the order of the depedency the error was gone.

On your /src/main/resources/application.yml file, setup the write-dates-as-timestamps property:

spring:
  jackson:
    serialization:
      write-dates-as-timestamps: false

And create a ObjectMapper bean as this:

@Configuration
public class WebConfigurer {

    @Bean
    @Primary
    public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.build();
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        return objectMapper;
    }

}

Following this configuration, the conversion always work on Spring Boot 1.5.x without any error.

Bonus: Spring AMQP Queue configuration

Working with Spring AMQP, pay attention if you have a new instance of Jackson2JsonMessageConverter (common thing when creating a SimpleRabbitListenerContainerFactory). You need to pass the ObjectMapper bean to it, like:

Jackson2JsonMessageConverter converter = new Jackson2JsonMessageConverter(objectMapper);

Otherwise, you will receive the same error.

Modifying a query string without reloading the page

Building off of Fabio's answer, I created two functions that will probably be useful for anyone stumbling upon this question. With these two functions, you can call insertParam() with a key and value as an argument. It will either add the URL parameter or, if a query param already exists with the same key, it will change that parameter to the new value:

//function to remove query params from a URL
function removeURLParameter(url, parameter) {
    //better to use l.search if you have a location/link object
    var urlparts= url.split('?');   
    if (urlparts.length>=2) {

        var prefix= encodeURIComponent(parameter)+'=';
        var pars= urlparts[1].split(/[&;]/g);

        //reverse iteration as may be destructive
        for (var i= pars.length; i-- > 0;) {    
            //idiom for string.startsWith
            if (pars[i].lastIndexOf(prefix, 0) !== -1) {  
                pars.splice(i, 1);
            }
        }

        url= urlparts[0] + (pars.length > 0 ? '?' + pars.join('&') : "");
        return url;
    } else {
        return url;
    }
}

//function to add/update query params
function insertParam(key, value) {
    if (history.pushState) {
        // var newurl = window.location.protocol + "//" + window.location.host + search.pathname + '?myNewUrlQuery=1';
        var currentUrlWithOutHash = window.location.origin + window.location.pathname + window.location.search;
        var hash = window.location.hash
        //remove any param for the same key
        var currentUrlWithOutHash = removeURLParameter(currentUrlWithOutHash, key);

        //figure out if we need to add the param with a ? or a &
        var queryStart;
        if(currentUrlWithOutHash.indexOf('?') !== -1){
            queryStart = '&';
        } else {
            queryStart = '?';
        }

        var newurl = currentUrlWithOutHash + queryStart + key + '=' + value + hash
        window.history.pushState({path:newurl},'',newurl);
    }
}

Why aren't programs written in Assembly more often?

Well I have been writing a lot of assembly "in the old days", and I can assure you that I am much more productive when I write programs in a high level language.

How to get the real path of Java application at runtime?

Since the application path of a JAR and an application running from inside an IDE differs, I wrote the following code to consistently return the correct current directory:

import java.io.File;
import java.net.URISyntaxException;

public class ProgramDirectoryUtilities
{
    private static String getJarName()
    {
        return new File(ProgramDirectoryUtilities.class.getProtectionDomain()
                .getCodeSource()
                .getLocation()
                .getPath())
                .getName();
    }

    private static boolean runningFromJAR()
    {
        String jarName = getJarName();
        return jarName.contains(".jar");
    }

    public static String getProgramDirectory()
    {
        if (runningFromJAR())
        {
            return getCurrentJARDirectory();
        } else
        {
            return getCurrentProjectDirectory();
        }
    }

    private static String getCurrentProjectDirectory()
    {
        return new File("").getAbsolutePath();
    }

    private static String getCurrentJARDirectory()
    {
        try
        {
            return new File(ProgramDirectoryUtilities.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()).getParent();
        } catch (URISyntaxException exception)
        {
            exception.printStackTrace();
        }

        return null;
    }
}

Simply call getProgramDirectory() and you should be good either way.

JavaScript string and number conversion

These questions come up all the time due to JavaScript's typing system. People think they are getting a number when they're getting the string of a number.

Here are some things you might see that take advantage of the way JavaScript deals with strings and numbers. Personally, I wish JavaScript had used some symbol other than + for string concatenation.

Step (1) Concatenate "1", "2", "3" into "123"

result = "1" + "2" + "3";

Step (2) Convert "123" into 123

result = +"123";

Step (3) Add 123 + 100 = 223

result = 123 + 100;

Step (4) Convert 223 into "223"

result = "" + 223;

If you know WHY these work, you're less likely to get into trouble with JavaScript expressions.

"webxml attribute is required" error in Maven

It does look like you have web.xml in the right location, but even so, this error is often caused by the directory structure not matching what Maven expects to see. For example, if you start out with an Eclipse webapp that you are trying to build with Maven.

If that is the issue, a quick fix is to create a
src/main/java and a
src/main/webapp directory (and other directories if you need them) and just move your files.

Here is an overview of the maven directory layout: http://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html

What is the best or most commonly used JMX Console / Client

I would prefer using JConsole for application monitoring, and it does have graphical view. If you’re using JDK 5.0 or above then it’s the best. Please refer to this using jconsole page for more details.

I have been primarily using it for GC tuning and finding bottlenecks.

How to unzip files programmatically in Android?

While the answers that are already here work well, I found that they were slightly slower than I had hoped for. Instead I used zip4j, which I think is the best solution because of its speed. It also allowed for different options for the amount of compression, which I found useful.

How to filter array when object key value is in array

This is a fast solution with a temporary object.

_x000D_
_x000D_
var records = [{ "empid": 1, "fname": "X", "lname": "Y" }, { "empid": 2, "fname": "A", "lname": "Y" }, { "empid": 3, "fname": "B", "lname": "Y" }, { "empid": 4, "fname": "C", "lname": "Y" }, { "empid": 5, "fname": "C", "lname": "Y" }],_x000D_
    empid = [1, 4, 5],_x000D_
    object = {},_x000D_
    result;_x000D_
_x000D_
records.forEach(function (a) {_x000D_
    object[a.empid] = a;_x000D_
});_x000D_
_x000D_
result = empid.map(function (a) {_x000D_
    return object[a];_x000D_
});_x000D_
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
_x000D_
_x000D_
_x000D_

Why use prefixes on member variables in C++ classes

I can't say how widespred it is, but speaking personally, I always (and have always) prefixed my member variables with 'm'. E.g.:

class Person {
   .... 
   private:
       std::string mName;
};

It's the only form of prefixing I do use (I'm very anti Hungarian notation) but it has stood me in good stead over the years. As an aside, I generally detest the use of underscores in names (or anywhere else for that matter), but do make an exception for preprocessor macro names, as they are usually all uppercase.

JetBrains / IntelliJ keyboard shortcut to collapse all methods

You Can Go To setting > editor > general > code folding and check "show code folding outline" .

Python: How to convert datetime format?

@Tim's answer only does half the work -- that gets it into a datetime.datetime object.

To get it into the string format you require, you use datetime.strftime:

print(datetime.strftime('%b %d,%Y'))

Jquery: Checking to see if div contains text, then action

Your code contains two problems:

  • The equality operator in JavaScript is ==, not =.
  • jQuery.text() joins all text nodes of matched elements into a single string. If you have two successive elements, of which the first contains 'some' and the second contains 'Text', then your code will incorrectly think that there exists an element that contains 'someText'.

I suggest the following instead:

if ($('#field > div.field-item:contains("someText")').length > 0) {
    $("#somediv").addClass("thisClass");
}

JsonParseException : Illegal unquoted character ((CTRL-CHAR, code 10)

On Salesforce platform this error is caused by /, the solution is to escape these as //.

Limiting the number of characters in a JTextField

You can do something like this (taken from here):

import java.awt.FlowLayout;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

class JTextFieldLimit extends PlainDocument {
  private int limit;
  JTextFieldLimit(int limit) {
    super();
    this.limit = limit;
  }

  JTextFieldLimit(int limit, boolean upper) {
    super();
    this.limit = limit;
  }

  public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
    if (str == null)
      return;

    if ((getLength() + str.length()) <= limit) {
      super.insertString(offset, str, attr);
    }
  }
}

public class Main extends JFrame {
  JTextField textfield1;

  JLabel label1;

  public void init() {
    setLayout(new FlowLayout());
    label1 = new JLabel("max 10 chars");
    textfield1 = new JTextField(15);
    add(label1);
    add(textfield1);
    textfield1.setDocument(new JTextFieldLimit(10));

    setSize(300,300);
    setVisible(true);
  }
}

Edit: Take a look at this previous SO post. You could intercept key press events and add/ignore them according to the current amount of characters in the textfield.

Making PHP var_dump() values display one line per value

Yes, try wrapping it with <pre>, e.g.:

echo '<pre>' , var_dump($variable) , '</pre>';

Why is it bad style to `rescue Exception => e` in Ruby?

That's a specific case of the rule that you shouldn't catch any exception you don't know how to handle. If you don't know how to handle it, it's always better to let some other part of the system catch and handle it.

Convert a PHP script into a stand-alone windows executable

Peachpie

http://www.peachpie.io

https://github.com/iolevel/peachpie

Peachpie is PHP 7 compiler based on Roslyn by Microsoft and drawing from popular Phalanger. It allows PHP to be executed within the .NET/.NETCore by compiling the PHP code to pure MSIL.

Phalanger

http://v4.php-compiler.net/

http://wiki.php-compiler.net/Phalanger_Wiki

https://github.com/devsense/phalanger

Phalanger is a project which was started at Charles University in Prague and was supported by Microsoft. It compiles source code written in the PHP scripting language into CIL (Common Intermediate Language) byte-code. It handles the beginning of a compiling process which is completed by the JIT compiler component of the .NET Framework. It does not address native code generation nor optimization. Its purpose is to compile PHP scripts into .NET assemblies, logical units containing CIL code and meta-data.

Bambalam

https://github.com/xZero707/Bamcompile/

Bambalam PHP EXE Compiler/Embedder is a free command line tool to convert PHP applications to standalone Windows .exe applications. The exe files produced are totally standalone, no need for php dlls etc. The php code is encoded using the Turck MMCache Encode library so it's a perfect solution if you want to distribute your application while protecting your source code. The converter is also suitable for producing .exe files for windowed PHP applications (created using for example the WinBinder library). It's also good for making stand-alone PHP Socket servers/clients (using the php_sockets.dll extension). It's NOT really a compiler in the sense that it doesn't produce native machine code from PHP sources, but it works!

ZZEE PHPExe

http://www.zzee.com/phpexe/

ZZEE PHPExe compiles PHP, HTML, Javascript, Flash and other web files into Windows GUI exes. You can rapidly develop Windows GUI applications by employing the familiar PHP web paradigm. You can use the same code for online and Windows applications with little or no modification. It is a Commercial product.

phc-win

http://wiki.swiftlytilting.com/Phc-win

The PHP extension bcompiler is used to compile PHP script code into PHP bytecode. This bytecode can be included just like any php file as long as the bcompiler extension is loaded. Once all the bytecode files have been created, a modified Embeder is used to pack all of the project files into the program exe.

Requires

  • php5ts.dll
  • php_win32std.dll
  • php_bcompiler.dll
  • php-embed.ini

ExeOutput

http://www.exeoutput.com/

Commercial

WinBinder

http://winbinder.org/

WinBinder is an open source extension to PHP, the script programming language. It allows PHP programmers to easily build native Windows applications, producing quick and rewarding results with minimum effort. Even short scripts with a few dozen lines can generate a useful program, thanks to the power and flexibility of PHP.

PHPDesktop

https://github.com/cztomczak/phpdesktop

PHP Desktop is an open source project founded by Czarek Tomczak in 2012 to provide a way for developing native desktop applications using web technologies such as PHP, HTML5, JavaScript & SQLite. This project is more than just a PHP to EXE compiler, it embeds a web-browser (Internet Explorer or Chrome embedded), a Mongoose web-server and a PHP interpreter. The development workflow you are used to remains the same, the step of turning an existing website into a desktop application is basically a matter of copying it to "www/" directory. Using SQLite database is optional, you could embed mysql/postgresql database in application's installer.

PHP Nightrain

https://github.com/kjellberg/nightrain

Using PHP Nightrain you will be able to deploy and run HTML, CSS, JavaScript and PHP web applications as a native desktop application on Windows, Mac and the Linux operating systems. Popular PHP Frameworks (e.g. CakePHP, Laravel, Drupal, etc…) are well supported!

phc-win "fork"

https://github.com/RDashINC/phc-win

A more-or-less forked version of phc-win, it uses the same techniques as phc-win but supports almost all modern PHP versions. (5.3, 5.4, 5.5, 5.6, etc) It also can use Enigma VB to combine the php5ts.dll with your exe, aswell as UPX compress it. Lastly, it has win32std and winbinder compilied statically into PHP.

EDIT

Another option is to use

http://www.appcelerator.com/products/titanium-cross-platform-application-development/

an online compiler that can build executables for a number of different platforms, from a number of different languages including PHP

TideSDK

http://www.tidesdk.org/

TideSDK is actually the renamed Titanium Desktop project. Titanium remained focused on mobile, and abandoned the desktop version, which was taken over by some people who have open sourced it and dubbed it TideSDK.

Generally, TideSDK uses HTML, CSS and JS to render applications, but it supports scripted languages like PHP, as a plug-in module, as well as other scripting languages like Python and Ruby.

Executing JavaScript without a browser?

Since nobody mentioned it: Since Java 1.6 The Java JDK also comes bundled with a JavaScript commandline and REPL.

It is based on Rhino: https://developer.mozilla.org/en/docs/Rhino

In Java 1.6 and 1.7 the command is called jrunscript (jrunscript.exe on Windows) and can be found in the bin folder of the JDK.

Starting from Java 1.8 there is bundled a new JavaScript implementation (Nashorn: https://blogs.oracle.com/nashorn/)

So in Java 1.8 the command is called jjs (jjs.exe on Windows)

Comparing Dates in Oracle SQL

Conclusion,

to_char works in its own way

So,

Always use this format YYYY-MM-DD for comparison instead of MM-DD-YY or DD-MM-YYYY or any other format

Redirecting to URL in Flask

You have to return a redirect:

import os
from flask import Flask,redirect

app = Flask(__name__)

@app.route('/')
def hello():
    return redirect("http://www.example.com", code=302)

if __name__ == '__main__':
    # Bind to PORT if defined, otherwise default to 5000.
    port = int(os.environ.get('PORT', 5000))
    app.run(host='0.0.0.0', port=port)

See the documentation on flask docs. The default value for code is 302 so code=302 can be omitted or replaced by other redirect code (one in 301, 302, 303, 305, and 307).

Prepend line to beginning of a file

Different Idea:

(1) You save the original file as a variable.

(2) You overwrite the original file with new information.

(3) You append the original file in the data below the new information.

Code:

with open(<filename>,'r') as contents:
      save = contents.read()
with open(<filename>,'w') as contents:
      contents.write(< New Information >)
with open(<filename>,'a') as contents:
      contents.write(save)

ASP MVC href to a controller/view

There are a couple of ways that you can accomplish this. You can do the following:

<li>
     @Html.ActionLink("Clients", "Index", "User", new { @class = "elements" }, null)
</li>

or this:

<li>
     <a href="@Url.Action("Index", "Users")" class="elements">
          <span>Clients</span>
     </a>
</li>

Lately I do the following:

<a href="@Url.Action("Index", null, new { area = string.Empty, controller = "User" }, Request.Url.Scheme)">
     <span>Clients</span>
</a>

The result would have http://localhost/10000 (or with whatever port you are using) to be appended to the URL structure like:

http://localhost:10000/Users

I hope this helps.

AngularJS: Uncaught Error: [$injector:modulerr] Failed to instantiate module?

I had to change the js file, so to include "function()" at the beginning of it, and also "()" at the end line. That solved the problem

Make Font Awesome icons in a circle?

This is the approach you don't need to use padding, just set the height and width for the a and let the flex handle with margin: 0 auto.

_x000D_
_x000D_
.social-links a{_x000D_
  text-align:center;_x000D_
 float: left;_x000D_
 width: 36px;_x000D_
 height: 36px;_x000D_
 border: 2px solid #909090;_x000D_
 border-radius: 100%;_x000D_
 margin-right: 7px; /*space between*/_x000D_
    display: flex;_x000D_
    align-items: flex-start;_x000D_
    transition: all 0.4s;_x000D_
    -webkit-transition: all 0.4s;_x000D_
} _x000D_
.social-links a i{_x000D_
 font-size: 20px;_x000D_
    align-self:center;_x000D_
 color: #909090;_x000D_
    transition: all 0.4s;_x000D_
    -webkit-transition: all 0.4s;_x000D_
    margin: 0 auto;_x000D_
}_x000D_
.social-links a i::before{_x000D_
  display:inline-block;_x000D_
  text-decoration:none;_x000D_
}_x000D_
.social-links a:hover{_x000D_
  background: rgba(0,0,0,0.2);_x000D_
}_x000D_
.social-links a:hover i{_x000D_
  color:#fff;_x000D_
}
_x000D_
<link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="social-links">_x000D_
    <a href="#"><i class="fa fa-facebook fa-lg"></i></a>_x000D_
    <a href="#"><i class="fa fa-twitter fa-lg"></i></a>_x000D_
    <a href="#"><i class="fa fa-google-plus fa-lg"></i></a>_x000D_
    <a href="#"><i class="fa fa-pinterest fa-lg"></i></a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

MVC 5 Access Claims Identity User Data

var claim = User.Claims.FirstOrDefault(c => c.Type == "claim type here");

Hide HTML element by id

If you want to do it via javascript rather than CSS you can use:

var link = document.getElementById('nav-ask');
link.style.display = 'none'; //or
link.style.visibility = 'hidden';

depending on what you want to do.

ImportError: No module named xlsxwriter

I have the same issue. It seems that pip is the problem. Try

pip uninstall xlsxwriter
easy_install xlsxwriter

How to set socket timeout in C when making multiple connections?

You can use the SO_RCVTIMEO and SO_SNDTIMEO socket options to set timeouts for any socket operations, like so:

    struct timeval timeout;      
    timeout.tv_sec = 10;
    timeout.tv_usec = 0;

    if (setsockopt (sockfd, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout,
                sizeof(timeout)) < 0)
        error("setsockopt failed\n");

    if (setsockopt (sockfd, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout,
                sizeof(timeout)) < 0)
        error("setsockopt failed\n");

Edit: from the setsockopt man page:

SO_SNDTIMEO is an option to set a timeout value for output operations. It accepts a struct timeval parameter with the number of seconds and microseconds used to limit waits for output operations to complete. If a send operation has blocked for this much time, it returns with a partial count or with the error EWOULDBLOCK if no data were sent. In the current implementation, this timer is restarted each time additional data are delivered to the protocol, implying that the limit applies to output portions ranging in size from the low-water mark to the high-water mark for output.

SO_RCVTIMEO is an option to set a timeout value for input operations. It accepts a struct timeval parameter with the number of seconds and microseconds used to limit waits for input operations to complete. In the current implementation, this timer is restarted each time additional data are received by the protocol, and thus the limit is in effect an inactivity timer. If a receive operation has been blocked for this much time without receiving additional data, it returns with a short count or with the error EWOULDBLOCK if no data were received. The struct timeval parameter must represent a positive time interval; otherwise, setsockopt() returns with the error EDOM.

Select a date from date picker using Selenium webdriver

try this,

http://seleniumcapsules.blogspot.com/2012/10/design-of-datepicker.html

  1. an icon used as a trigger;
  2. display a calendar when the icon is clicked;
  3. Previous Year button(<<), optional;
  4. Next Year Button(>>), optional;
  5. Previous Month button(<);
  6. Next Month button(>);
  7. day buttons;
  8. Weekday indicators;
  9. Calendar title i.e. "September, 2011" which representing current month and current year.

Declare a constant array

As others have mentioned, there is no official Go construct for this. The closest I can imagine would be a function that returns a slice. In this way, you can guarantee that no one will manipulate the elements of the original slice (as it is "hard-coded" into the array).

I have shortened your slice to make it...shorter...:

func GetLetterGoodness() []float32 {
    return []float32 { .0817,.0149,.0278,.0425,.1270,.0223 }
}

C#: Converting byte array to string and printing out to console

This is just an updated version of Jesse Webbs code that doesn't append the unnecessary trailing , character.

public static string PrintBytes(this byte[] byteArray)
{
    var sb = new StringBuilder("new byte[] { ");
    for(var i = 0; i < byteArray.Length;i++)
    {
        var b = byteArray[i];
        sb.Append(b);
        if (i < byteArray.Length -1)
        {
            sb.Append(", ");
        }
    }
    sb.Append(" }");
    return sb.ToString();
}

The output from this method would be:

new byte[] { 48, ... 135, 31, 178, 7, 157 }

Convert UTF-8 to base64 string

It's a little difficult to tell what you're trying to achieve, but assuming you're trying to get a Base64 string that when decoded is abcdef==, the following should work:

byte[] bytes = Encoding.UTF8.GetBytes("abcdef==");
string base64 = Convert.ToBase64String(bytes);
Console.WriteLine(base64);

This will output: YWJjZGVmPT0= which is abcdef== encoded in Base64.

Edit:

To decode a Base64 string, simply use Convert.FromBase64String(). E.g.

string base64 = "YWJjZGVmPT0=";
byte[] bytes = Convert.FromBase64String(base64);

At this point, bytes will be a byte[] (not a string). If we know that the byte array represents a string in UTF8, then it can be converted back to the string form using:

string str = Encoding.UTF8.GetString(bytes);
Console.WriteLine(str);

This will output the original input string, abcdef== in this case.

How to remove all options from a dropdown using jQuery / JavaScript

Anyone using JavaScript (as opposed to JQuery), might like to try this solution, where 'models' is the ID of the select field containing the list :-

var DDlist = document.getElementById("models");
while(DDlist.length>0){DDlist.remove(0);}

Difference between JE/JNE and JZ/JNZ

JE and JZ are just different names for exactly the same thing: a conditional jump when ZF (the "zero" flag) is equal to 1.

(Similarly, JNE and JNZ are just different names for a conditional jump when ZF is equal to 0.)

You could use them interchangeably, but you should use them depending on what you are doing:

  • JZ/JNZ are more appropriate when you are explicitly testing for something being equal to zero:

    dec  ecx
    jz   counter_is_now_zero
    
  • JE and JNE are more appropriate after a CMP instruction:

    cmp  edx, 42
    je   the_answer_is_42
    

    (A CMP instruction performs a subtraction, and throws the value of the result away, while keeping the flags; which is why you get ZF=1 when the operands are equal and ZF=0 when they're not.)

Object does not support item assignment error

The error seems clear: model objects do not support item assignment. MyModel.objects.latest('id')['foo'] = 'bar' will throw this same error.

It's a little confusing that your model instance is called projectForm...

To reproduce your first block of code in a loop, you need to use setattr

for k,v in session_results.iteritems():
    setattr(projectForm, k, v)

Laravel form html with PUT method for PUT routes

If you are using HTML Form element instead Laravel Form Builder, you must place method_field between your form opening tag and closing end. By doing this you may explicitly define form method type.

<form>
{{ method_field('PUT') }}
</form>

Git: See my last commit

This question is already answered above which states the file names in last commit by git log / other commands. If someone wants to see what all changed in last commit (line differences), you can use this command -

git show

This automatically displays the line differences in last commit.

href around input type submit

You can do do it. The input type submit should be inside of a form. Then all you have to do is write the link you want to redirect to inside the action attribute that is inside the form tag.

What is the difference between Jupyter Notebook and JupyterLab?

This answer shows the python perspective. Jupyter supports various languages besides python.

Both Jupyter Notebook and Jupyterlab are browser compatible interactive python (i.e. python ".ipynb" files) environments, where you can divide the various portions of the code into various individually executable cells for the sake of better readability. Both of these are popular in Data Science/Scientific Computing domain.

I'd suggest you to go with Jupyterlab for the advantages over Jupyter notebooks:

  1. In Jupyterlab, you can create ".py" files, ".ipynb" files, open terminal etc. Jupyter Notebook allows ".ipynb" files while providing you the choice to choose "python 2" or "python 3".
  2. Jupyterlab can open multiple ".ipynb" files inside a single browser tab. Whereas, Jupyter Notebook will create new tab to open new ".ipynb" files every time. Hovering between various tabs of browser is tedious, thus Jupyterlab is more helpful here.

I'd recommend using PIP to install Jupyterlab.

If you can't open a ".ipynb" file using Jupyterlab on Windows system, here are the steps:

  1. Go to the file --> Right click --> Open With --> Choose another app --> More Apps --> Look for another apps on this PC --> Click.
  2. This will open a file explorer window. Now go inside your Python installation folder. You should see Scripts folder. Go inside it.
  3. Once you find jupyter-lab.exe, select that and now it will open the .ipynb files by default on your PC.

System.Runtime.InteropServices.COMException (0x800A03EC)

It 'a permission problem when IIS is running I had this problem and I solved it in this way

I went on folders

C:\Windows\ System32\config\SystemProfile

and

C:\Windows\SysWOW64\config\SystemProfile

are protected system folders, they usually have the lock.

Right-click-> Card security-> Click on Edit-> Add untente "Autenticadet User" and assign permissions.

At this point everything is solved, if you still have problems try to give all permissions to "Everyone"

Finding the index of an item in a list

For one comparable

# Throws ValueError if nothing is found
some_list = ['foo', 'bar', 'baz'].index('baz')
# some_list == 2

Custom predicate

some_list = [item1, item2, item3]

# Throws StopIteration if nothing is found
# *unless* you provide a second parameter to `next`
index_of_value_you_like = next(
    i for i, item in enumerate(some_list)
    if item.matches_your_criteria())

Finding index of all items by predicate

index_of_staff_members = [
    i for i, user in enumerate(users)
    if user.is_staff()]

Check if space is in a string

You can try this, and if it will find any space it will return the position where the first space is.

if mystring.find(' ') != -1:
    print True
else:
    print False

Fatal error compiling: invalid target release: 1.8 -> [Help 1]

If you are using Eclipse IDE then go inside Window menu and select preferences and there you search for installed JREs and select the JRE you need to build the project

How to display binary data as image - extjs 4

In ExtJs, you can use

xtype: 'image'

to render a image.

Here is a fiddle showing rendering of binary data with extjs.

atob -- > converts ascii to binary

btoa -- > converts binary to ascii

Ext.application({
    name: 'Fiddle',

    launch: function () {
        var srcBase64 = "data:image/jpeg;base64," + btoa(atob("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8H8hYDwAFegHS8+X7mgAAAABJRU5ErkJggg=="));

        Ext.create("Ext.panel.Panel", {
            title: "Test",
            renderTo: Ext.getBody(),
            height: 400,
            items: [{
                xtype: 'image',
                width: 100,
                height: 100,
                src: srcBase64
            }]
        })
    }
});

https://fiddle.sencha.com/#view/editor&fiddle/28h0

What is the difference between JOIN and JOIN FETCH when using JPA and Hibernate

In this two queries, you are using JOIN to query all employees that have at least one department associated.

But, the difference is: in the first query you are returning only the Employes for the Hibernate. In the second query, you are returning the Employes and all Departments associated.

So, if you use the second query, you will not need to do a new query to hit the database again to see the Departments of each Employee.

You can use the second query when you are sure that you will need the Department of each Employee. If you not need the Department, use the first query.

I recomend read this link if you need to apply some WHERE condition (what you probably will need): How to properly express JPQL "join fetch" with "where" clause as JPA 2 CriteriaQuery?

Update

If you don't use fetch and the Departments continue to be returned, is because your mapping between Employee and Department (a @OneToMany) are setted with FetchType.EAGER. In this case, any HQL (with fetch or not) query with FROM Employee will bring all Departments. Remember that all mapping *ToOne (@ManyToOne and @OneToOne) are EAGER by default.

Setting Different Bar color in matplotlib Python

I assume you are using Series.plot() to plot your data. If you look at the docs for Series.plot() here:

http://pandas.pydata.org/pandas-docs/dev/generated/pandas.Series.plot.html

there is no color parameter listed where you might be able to set the colors for your bar graph.

However, the Series.plot() docs state the following at the end of the parameter list:

kwds : keywords
Options to pass to matplotlib plotting method

What that means is that when you specify the kind argument for Series.plot() as bar, Series.plot() will actually call matplotlib.pyplot.bar(), and matplotlib.pyplot.bar() will be sent all the extra keyword arguments that you specify at the end of the argument list for Series.plot().

If you examine the docs for the matplotlib.pyplot.bar() method here:

http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.bar

..it also accepts keyword arguments at the end of it's parameter list, and if you peruse the list of recognized parameter names, one of them is color, which can be a sequence specifying the different colors for your bar graph.

Putting it all together, if you specify the color keyword argument at the end of your Series.plot() argument list, the keyword argument will be relayed to the matplotlib.pyplot.bar() method. Here is the proof:

import pandas as pd
import matplotlib.pyplot as plt

s = pd.Series(
    [5, 4, 4, 1, 12],
    index = ["AK", "AX", "GA", "SQ", "WN"]
)

#Set descriptions:
plt.title("Total Delay Incident Caused by Carrier")
plt.ylabel('Delay Incident')
plt.xlabel('Carrier')

#Set tick colors:
ax = plt.gca()
ax.tick_params(axis='x', colors='blue')
ax.tick_params(axis='y', colors='red')

#Plot the data:
my_colors = 'rgbkymc'  #red, green, blue, black, etc.

pd.Series.plot(
    s, 
    kind='bar', 
    color=my_colors,
)

plt.show()

enter image description here

Note that if there are more bars than colors in your sequence, the colors will repeat.

How to change cursor from pointer to finger using jQuery?

It is very straight forward

HTML

<input type="text" placeholder="some text" />
<input type="button" value="button" class="button"/>
<button class="button">Another button</button>

jQuery

$(document).ready(function(){
  $('.button').css( 'cursor', 'pointer' );

  // for old IE browsers
  $('.button').css( 'cursor', 'hand' ); 
});

Check it out on JSfiddle

Laravel Eloquent Join vs Inner Join?

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

You could build it like this:

<?php

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

Build the feed model like so:

<?php

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

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

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

Then keep it up to date with something like:

<?php

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

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

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

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

<?php

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

How to validate inputs dynamically created using ng-repeat, ng-show (angular)

Added more complex example with "custom validation" on the side of controller http://jsfiddle.net/82PX4/3/

<div class='line' ng-repeat='line in ranges' ng-form='lineForm'>
    low: <input type='text' 
                name='low'
                ng-pattern='/^\d+$/' 
                ng-change="lowChanged(this, $index)" ng-model='line.low' />
    up: <input type='text' 
                name='up'
                ng-pattern='/^\d+$/'
                ng-change="upChanged(this, $index)" 
                ng-model='line.up' />
    <a href ng-if='!$first' ng-click='removeRange($index)'>Delete</a>
    <div class='error' ng-show='lineForm.$error.pattern'>
        Must be a number.
    </div>
    <div class='error' ng-show='lineForm.$error.range'>
        Low must be less the Up.
    </div>
</div>

Creating a zero-filled pandas data frame

If you would like the new data frame to have the same index and columns as an existing data frame, you can just multiply the existing data frame by zero:

df_zeros = df * 0

MS Access: how to compact current database in VBA

Try this. It works on the same database in which the code resides. Just call the CompactDB() function shown below. Make sure that after you add the function, you click the Save button in the VBA Editor window prior to running for the first time. I only tested it in Access 2010. Ba-da-bing, ba-da-boom.

Public Function CompactDB()

    Dim strWindowTitle As String

    On Error GoTo err_Handler

    strWindowTitle = Application.Name & " - " & Left(Application.CurrentProject.Name, Len(Application.CurrentProject.Name) - 4)
    strTempDir = Environ("Temp")
    strScriptPath = strTempDir & "\compact.vbs"
    strCmd = "wscript " & """" & strScriptPath & """"

    Open strScriptPath For Output As #1
    Print #1, "Set WshShell = WScript.CreateObject(""WScript.Shell"")"
    Print #1, "WScript.Sleep 1000"
    Print #1, "WshShell.AppActivate " & """" & strWindowTitle & """"
    Print #1, "WScript.Sleep 500"
    Print #1, "WshShell.SendKeys ""%yc"""
    Close #1

    Shell strCmd, vbHide
    Exit Function

    err_Handler:
    MsgBox "Error " & Err.Number & ": " & Err.Description
    Close #1

End Function

@Nullable annotation usage

Different tools may interpret the meaning of @Nullable differently. For example, the Checker Framework and FindBugs handle @Nullable differently.

javascript getting my textbox to display a variable

You're on the right track with using document.getElementById() as you have done for your first two text boxes. Use something like document.getElementById("textbox3") to retrieve the element. Then you can just set its value property: document.getElementById("textbox3").value = answer;

For the "Your answer is: --", I'd recommend wrapping the "--" in a <span/> (e.g. <span id="answerDisplay">--</span>). Then use document.getElementById("answerDisplay").textContent = answer; to display it.

WELD-001408: Unsatisfied dependencies for type Customer with qualifiers @Default

To inject an Object, its class must be known to the CDI mechanism. Usualy adding the @Named annotation will do the trick.

How do I make a textbox that only accepts numbers?

you could use TextChanged/ Keypress event, use a regex to filter on numbers and take some action.

Hibernate vs JPA vs JDO - pros and cons of each?

I am using JPA (OpenJPA implementation from Apache which is based on the KODO JDO codebase which is 5+ years old and extremely fast/reliable). IMHO anyone who tells you to bypass the specs is giving you bad advice. I put the time in and was definitely rewarded. With either JDO or JPA you can change vendors with minimal changes (JPA has orm mapping so we are talking less than a day to possibly change vendors). If you have 100+ tables like I do this is huge. Plus you get built0in caching with cluster-wise cache evictions and its all good. SQL/Jdbc is fine for high performance queries but transparent persistence is far superior for writing your algorithms and data input routines. I only have about 16 SQL queries in my whole system (50k+ lines of code).

How Best to Compare Two Collections in Java and Act on Them?

public static boolean doCollectionsContainSameElements(
        Collection<Integer> c1, Collection<Integer> c2){

    if (c1 == null || c2 == null) {
        return false;
    }
    else if (c1.size() != c2.size()) {
        return false;
    } else {    
        return c1.containsAll(c2) && c2.containsAll(c1);
    }       
}

How can I change the remote/target repository URL on Windows?

One more way to do this is:

git config remote.origin.url https://github.com/abc/abc.git

To see the existing URL just do:

git config remote.origin.url

Finding blocking/locking queries in MS SQL (mssql)

I found this query which helped me find my locked table and query causing the issue.

SELECT  L.request_session_id AS SPID, 
        DB_NAME(L.resource_database_id) AS DatabaseName,
        O.Name AS LockedObjectName, 
        P.object_id AS LockedObjectId, 
        L.resource_type AS LockedResource, 
        L.request_mode AS LockType,
        ST.text AS SqlStatementText,        
        ES.login_name AS LoginName,
        ES.host_name AS HostName,
        TST.is_user_transaction as IsUserTransaction,
        AT.name as TransactionName,
        CN.auth_scheme as AuthenticationMethod
FROM    sys.dm_tran_locks L
        JOIN sys.partitions P ON P.hobt_id = L.resource_associated_entity_id
        JOIN sys.objects O ON O.object_id = P.object_id
        JOIN sys.dm_exec_sessions ES ON ES.session_id = L.request_session_id
        JOIN sys.dm_tran_session_transactions TST ON ES.session_id = TST.session_id
        JOIN sys.dm_tran_active_transactions AT ON TST.transaction_id = AT.transaction_id
        JOIN sys.dm_exec_connections CN ON CN.session_id = ES.session_id
        CROSS APPLY sys.dm_exec_sql_text(CN.most_recent_sql_handle) AS ST
WHERE   resource_database_id = db_id()
ORDER BY L.request_session_id

How do I get into a Docker container's shell?

To bash into a running container, type this:

docker exec -t -i container_name /bin/bash

or

docker exec -ti container_name /bin/bash

or

docker exec -ti container_name sh

No Android SDK found - Android Studio

Try make New Project, and then choose same android version that you've installed sdk verions on "Target Android Device" dialog. In my case, error message gone.

What does Include() do in LINQ?

Let's say for instance you want to get a list of all your customers:

var customers = context.Customers.ToList();

And let's assume that each Customer object has a reference to its set of Orders, and that each Order has references to LineItems which may also reference a Product.

As you can see, selecting a top-level object with many related entities could result in a query that needs to pull in data from many sources. As a performance measure, Include() allows you to indicate which related entities should be read from the database as part of the same query.

Using the same example, this might bring in all of the related order headers, but none of the other records:

var customersWithOrderDetail = context.Customers.Include("Orders").ToList();

As a final point since you asked for SQL, the first statement without Include() could generate a simple statement:

SELECT * FROM Customers;

The final statement which calls Include("Orders") may look like this:

SELECT *
FROM Customers JOIN Orders ON Customers.Id = Orders.CustomerId;

How to access component methods from “outside” in ReactJS?

As of React 16.3 React.createRef can be used, (use ref.current to access)

var ref = React.createRef()

var parent = (
  <div>
    <Child ref={ref} />
    <button onClick={e=>console.log(ref.current)}
  </div>
);

React.renderComponent(parent, document.body)

Default fetch type for one-to-one, many-to-one and one-to-many in Hibernate

To answer your question, Hibernate is an implementation of the JPA standard. Hibernate has its own quirks of operation, but as per the Hibernate docs

By default, Hibernate uses lazy select fetching for collections and lazy proxy fetching for single-valued associations. These defaults make sense for most associations in the majority of applications.

So Hibernate will always load any object using a lazy fetching strategy, no matter what type of relationship you have declared. It will use a lazy proxy (which should be uninitialized but not null) for a single object in a one-to-one or many-to-one relationship, and a null collection that it will hydrate with values when you attempt to access it.

It should be understood that Hibernate will only attempt to fill these objects with values when you attempt to access the object, unless you specify fetchType.EAGER.

Java Interfaces/Implementation naming convention

I like interface names that indicate what contract an interface describes, such as "Comparable" or "Serializable". Nouns like "Truck" don't really describe truck-ness -- what are the Abilities of a truck?

Regarding conventions: I have worked on projects where every interface starts with an "I"; while this is somewhat alien to Java conventions, it makes finding interfaces very easy. Apart from that, the "Impl" suffix is a reasonable default name.

How to get the path of current worksheet in VBA?

Always nice to have:

Dim myPath As String     
Dim folderPath As String 

folderPath = Application.ActiveWorkbook.Path    
myPath = Application.ActiveWorkbook.FullName

ERROR: Sonar server 'http://localhost:9000' can not be reached

I got the same issue, and I changed to IP and it working well

Go to System References --> Network --> Advanced --> Open TCP/IP tabs --> copy the IPv4 Address.

change that IP instead localhost

Hope this can help

Python glob multiple filetypes

This worked for me!

split('.')[-1]

Will separate the filename suffix (*.xxx) so using if help to check it

    for filename in glob.glob(folder + '*.*'):
        print(folder+filename)
        if  filename.split('.')[-1] != 'tif' and \
            filename.split('.')[-1] != 'tiff' and \
            filename.split('.')[-1] != 'bmp' and \
            filename.split('.')[-1] != 'jpg' and \
            filename.split('.')[-1] != 'jpeg' and \
            filename.split('.')[-1] != 'png':
                continue
        # Your code

Get the value of bootstrap Datetimepicker in JavaScript

It seems the doc evolved.

One should now use : $("#datetimepicker1").data("DateTimePicker").date().

NB : Doing so return a Moment object, not a Date object

What does "static" mean in C?

In C programming, static is a reserved keyword which controls both lifetime as well as visibility. If we declare a variable as static inside a function then it will only visible throughout that function. In this usage, this static variable's lifetime will start when a function call and it will destroy after the execution of that function. you can see the following example:

#include<stdio.h> 
int counterFunction() 
{ 
  static int count = 0; 
  count++; 
  return count; 
} 

int main() 
{ 
  printf("First Counter Output = %d\n", counterFunction()); 
  printf("Second Counter Output = %d ", counterFunction()); 
  return 0; 
}

Above program will give us this Output:

First Counter Output = 1 
Second Counter Output = 1 

Because as soon as we call the function it will initialize the count = 0. And while we execute the counterFunction it will destroy the count variable.

How to deep copy a list?

E0_copy is not a deep copy. You don't make a deep copy using list() (Both list(...) and testList[:] are shallow copies).

You use copy.deepcopy(...) for deep copying a list.

deepcopy(x, memo=None, _nil=[])
    Deep copy operation on arbitrary Python objects.

See the following snippet -

>>> a = [[1, 2, 3], [4, 5, 6]]
>>> b = list(a)
>>> a
[[1, 2, 3], [4, 5, 6]]
>>> b
[[1, 2, 3], [4, 5, 6]]
>>> a[0][1] = 10
>>> a
[[1, 10, 3], [4, 5, 6]]
>>> b   # b changes too -> Not a deepcopy.
[[1, 10, 3], [4, 5, 6]]

Now see the deepcopy operation

>>> import copy
>>> b = copy.deepcopy(a)
>>> a
[[1, 10, 3], [4, 5, 6]]
>>> b
[[1, 10, 3], [4, 5, 6]]
>>> a[0][1] = 9
>>> a
[[1, 9, 3], [4, 5, 6]]
>>> b    # b doesn't change -> Deep Copy
[[1, 10, 3], [4, 5, 6]]

How to stop java process gracefully?

An another way: your application can open a server socet and wait for an information arrived to it. For example a string with a "magic" word :) and then react to make shutdown: System.exit(). You can send such information to the socke using an external application like telnet.

Character Limit in HTML

There are 2 main solutions:

The pure HTML one:

<input type="text" id="Textbox" name="Textbox" maxlength="10" />

The JavaScript one (attach it to a onKey Event):

function limitText(limitField, limitNum) {
    if (limitField.value.length > limitNum) {
        limitField.value = limitField.value.substring(0, limitNum);
    } 
}

But anyway, there is no good solution. You can not adapt to every client's bad HTML implementation, it's an impossible fight to win. That's why it's far better to check it on the server side, with a PHP / Python / whatever script.

How to disable a link using only CSS?

CSS can't do that. CSS is for presentation only. Your options are:

  • Don't include the href attribute in your <a> tags.
  • Use JavaScript, to find the anchor elements with that class, and remove their href or onclick attributes accordingly. jQuery would help you with that (NickF showed how to do something similar but better).

Set min-width either by content or 200px (whichever is greater) together with max-width

The problem is that flex: 1 sets flex-basis: 0. Instead, you need

.container .box {
  min-width: 200px;
  max-width: 400px;
  flex-basis: auto; /* default value */
  flex-grow: 1;
}

_x000D_
_x000D_
.container {_x000D_
  display: -webkit-flex;_x000D_
  display: flex;_x000D_
  -webkit-flex-wrap: wrap;_x000D_
  flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
.container .box {_x000D_
  -webkit-flex-grow: 1;_x000D_
  flex-grow: 1;_x000D_
  min-width: 100px;_x000D_
  max-width: 400px;_x000D_
  height: 200px;_x000D_
  background-color: #fafa00;_x000D_
  overflow: hidden;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

linux find regex

Well, you may try this '.*[0-9]'

Negative matching using grep (match lines that do not contain foo)

In your case, you presumably don't want to use grep, but add instead a negative clause to the find command, e.g.

find /home/baumerf/public_html/ -mmin -60 -not -name error_log

If you want to include wildcards in the name, you'll have to escape them, e.g. to exclude files with suffix .log:

find /home/baumerf/public_html/ -mmin -60 -not -name \*.log

Powershell's Get-date: How to get Yesterday at 22:00 in a variable?

I saw in at least one other place that people don't realize Date-Time takes in times as well, so I figured I'd share it here since it's really short to do so:

Get-Date # Following the OP's example, let's say it's Friday, March 12, 2010 9:00:00 AM
(Get-Date '22:00').AddDays(-1) # Thursday, March 11, 2010 10:00:00 PM

It's also the shortest way to strip time information and still use other parameters of Get-Date. For instance you can get seconds since 1970 this way (Unix timestamp):

Get-Date '0:00' -u '%s' # 1268352000

Or you can get an ISO 8601 timestamp:

Get-Date '0:00' -f 's' # 2010-03-12T00:00:00

Then again if you reverse the operands, it gives you a little more freedom with formatting with any date object:

'The sortable timestamp: {0:s}Z{1}Vs measly human format: {0:D}' -f (Get-Date '0:00'), "`r`n"
# The sortable timestamp: 2010-03-12T00:00:00Z
# Vs measly human format: Friday, March 12, 2010

However if you wanted to both format a Unix timestamp (via -u aka -UFormat), you'll need to do it separately. Here's an example of that:

'ISO 8601: {0:s}Z{1}Unix: {2}' -f (Get-Date '0:00'), "`r`n", (Get-Date '0:00' -u '%s')
# ISO 8601: 2010-03-12T00:00:00Z
# Unix: 1268352000

Hope this helps!

Difference of two date time in sql server

declare @dt1 datetime='2012/06/13 08:11:12', @dt2 datetime='2012/06/12 02:11:12'

select CAST((@dt2-@dt1) as time(0))

What is REST call and how to send a REST call?

REST is somewhat of a revival of old-school HTTP, where the actual HTTP verbs (commands) have semantic meaning. Til recently, apps that wanted to update stuff on the server would supply a form containing an 'action' variable and a bunch of data. The HTTP command would almost always be GET or POST, and would be almost irrelevant. (Though there's almost always been a proscription against using GET for operations that have side effects, in reality a lot of apps don't care about the command used.)

With REST, you might instead PUT /profiles/cHao and send an XML or JSON representation of the profile info. (Or rather, I would -- you would have to update your own profile. :) That'd involve logging in, usually through HTTP's built-in authentication mechanisms.) In the latter case, what you want to do is specified by the URL, and the request body is just the guts of the resource involved.

http://en.wikipedia.org/wiki/Representational_State_Transfer has some details.