Programs & Examples On #Bisection

Anything related to a class of algorithms where the result is found by searching either the upper or the lower half of a sorted set of items and repeating this procedure recursively. Commonly used to refer to the bisection method (to find a root of an equation) or to the bisection search algorithm (to search a sorted list for a matching element).

Binary search (bisection) in Python

Dave Abrahams' solution is good. Although I have would have done it minimalistic:

def binary_search(L, x):
    i = bisect.bisect_left(L, x)
    if i == len(L) or L[i] != x:
        return -1
    return i

How do I enable saving of filled-in fields on a PDF form?

You can use the free foxit reader to fill in the forms, and if you pay a little you can design the forms that way you want.

You can also us iText to programmaticly create those forms.

There are free online services that allow you to upload a pdf and you can add fields also.

It depends on how you want to do the designing.

EDIT: If you use foxit reader, you can save any form that is fillable.

Combine multiple JavaScript files into one JS file

Just combine the text files and then use something like the YUI Compressor.

Files can be easily combined using the command cat *.js > main.js and main.js can then be run through the YUI compressor using java -jar yuicompressor-x.y.z.jar -o main.min.js main.js.

Update Aug 2014

I've now migrated to using Gulp for javascript concatenation and compression as with various plugins and some minimal configuration you can do things like set up dependencies, compile coffeescript etc as well as compressing your JS.

Java - Create a new String instance with specified length and filled with specific character. Best solution?

Apache Commons Lang (probably useful enough to be on the classpath of any non-trivial project) has StringUtils.repeat():

String filled = StringUtils.repeat("*", 10);

Easy!

UIButton: set image for selected-highlighted state

If you have a good reason to do that, this will do the trick

add these targets:

[button addTarget:self action:@selector(buttonTouchDown:) forControlEvents:UIControlEventTouchDown];
[button addTarget:self action:@selector(buttonTouchUp:) forControlEvents:UIControlEventTouchUpInside];


-(void)buttonTouchDown:(id)sender{
    UIButton *button=(UIButton *)sender;
    if(button.selected){
        [button setImage:[UIImage imageNamed:@"pressed.png"] forState:UIControlStateNormal];
    }
}

-(void)buttonTouchUp:(id)sender{
    UIButton *button=(UIButton *)sender;
    [button setImage:[UIImage imageNamed:@"normal.png"] forState:UIControlStateNormal];
}

Custom li list-style with font-awesome icon

I'd like to provide an alternate, easier solution that is specific to FontAwesome. If you're using a different iconic font, JOPLOmacedo's answer is still perfectly fine for use.

FontAwesome now handles list styles internally with CSS classes.

Here's the official example:

<ul class="fa-ul">
  <li><span class="fa-li"><i class="fas fa-check-square"></i></span>List icons can</li>
  <li><span class="fa-li"><i class="fas fa-check-square"></i></span>be used to</li>
  <li><span class="fa-li"><i class="fas fa-spinner fa-pulse"></i></span>replace bullets</li>
  <li><span class="fa-li"><i class="far fa-square"></i></span>in lists</li>
</ul>

Paging UICollectionView by cells, not screen

Also you can create fake scroll view to handle scrolling.

Horizontal or Vertical

// === Defaults ===
let bannerSize = CGSize(width: 280, height: 170)
let pageWidth: CGFloat = 290 // ^ + paging
let insetLeft: CGFloat = 20
let insetRight: CGFloat = 20
// ================

var pageScrollView: UIScrollView!

override func viewDidLoad() {
    super.viewDidLoad()

    // Create fake scrollview to properly handle paging
    pageScrollView = UIScrollView(frame: CGRect(origin: .zero, size: CGSize(width: pageWidth, height: 100)))
    pageScrollView.isPagingEnabled = true
    pageScrollView.alwaysBounceHorizontal = true
    pageScrollView.showsVerticalScrollIndicator = false
    pageScrollView.showsHorizontalScrollIndicator = false
    pageScrollView.delegate = self
    pageScrollView.isHidden = true
    view.insertSubview(pageScrollView, belowSubview: collectionView)

    // Set desired gesture recognizers to the collection view
    for gr in pageScrollView.gestureRecognizers! {
        collectionView.addGestureRecognizer(gr)
    }
}

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if scrollView == pageScrollView {
        // Return scrolling back to the collection view
        collectionView.contentOffset.x = pageScrollView.contentOffset.x
    }
}

func refreshData() {
    ...

    refreshScroll()
}

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    refreshScroll()
}

/// Refresh fake scrolling view content size if content changes
func refreshScroll() {
    let w = collectionView.width - bannerSize.width - insetLeft - insetRight
    pageScrollView.contentSize = CGSize(width: pageWidth * CGFloat(banners.count) - w, height: 100)
}

JavaScript: Upload file

Pure JS

You can use fetch optionally with await-try-catch

let photo = document.getElementById("image-file").files[0];
let formData = new FormData();
     
formData.append("photo", photo);
fetch('/upload/image', {method: "POST", body: formData});

_x000D_
_x000D_
async function SavePhoto(inp) 
{
    let user = { name:'john', age:34 };
    let formData = new FormData();
    let photo = inp.files[0];      
         
    formData.append("photo", photo);
    formData.append("user", JSON.stringify(user)); 
    
    const ctrl = new AbortController()    // timeout
    setTimeout(() => ctrl.abort(), 5000);
    
    try {
       let r = await fetch('/upload/image', 
         {method: "POST", body: formData, signal: ctrl.signal}); 
       console.log('HTTP response code:',r.status); 
    } catch(e) {
       console.log('Huston we have problem...:', e);
    }
    
}
_x000D_
<input id="image-file" type="file" onchange="SavePhoto(this)" >
<br><br>
Before selecting the file open chrome console > network tab to see the request details.
<br><br>
<small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>

<br><br>
(in stack overflow snippets there is problem with error handling, however in <a href="https://jsfiddle.net/Lamik/b8ed5x3y/5/">jsfiddle version</a> for 404 errors 4xx/5xx are <a href="https://stackoverflow.com/a/33355142/860099">not throwing</a> at all but we can read response status which contains code)
_x000D_
_x000D_
_x000D_

Old school approach - xhr

let photo = document.getElementById("image-file").files[0];  // file from input
let req = new XMLHttpRequest();
let formData = new FormData();

formData.append("photo", photo);                                
req.open("POST", '/upload/image');
req.send(formData);

_x000D_
_x000D_
function SavePhoto(e) 
{
    let user = { name:'john', age:34 };
    let xhr = new XMLHttpRequest();
    let formData = new FormData();
    let photo = e.files[0];      
    
    formData.append("user", JSON.stringify(user));   
    formData.append("photo", photo);
    
    xhr.onreadystatechange = state => { console.log(xhr.status); } // err handling
    xhr.timeout = 5000;
    xhr.open("POST", '/upload/image'); 
    xhr.send(formData);
}
_x000D_
<input id="image-file" type="file" onchange="SavePhoto(this)" >
<br><br>
Choose file and open chrome console > network tab to see the request details.
<br><br>
<small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>

<br><br>
(the stack overflow snippets, has some problem with error handling - the xhr.status is zero (instead of 404) which is similar to situation when we run script from file on <a href="https://stackoverflow.com/a/10173639/860099">local disc</a> - so I provide also js fiddle version which shows proper http error code <a href="https://jsfiddle.net/Lamik/k6jtq3uh/2/">here</a>)
_x000D_
_x000D_
_x000D_

SUMMARY

  • In server side you can read original file name (and other info) which is automatically included to request by browser in filename formData parameter.
  • You do NOT need to set request header Content-Type to multipart/form-data - this will be set automatically by browser.
  • Instead of /upload/image you can use full address like http://.../upload/image.
  • If you want to send many files in single request use multiple attribute: <input multiple type=... />, and attach all chosen files to formData in similar way (e.g. photo2=...files[2];... formData.append("photo2", photo2);)
  • You can include additional data (json) to request e.g. let user = {name:'john', age:34} in this way: formData.append("user", JSON.stringify(user));
  • You can set timeout: for fetch using AbortController, for old approach by xhr.timeout= milisec
  • This solutions should work on all major browsers.

How do I get logs from all pods of a Kubernetes replication controller?

Another solution that I would consider is using K9S which is a great kube administration tool.

After installation, the usage is very straightforward:

 k9s -n my-namespace --context the_context_name_in_kubeconfig

(If kubeconfig is not in the default location add KUBECONFIG=path/to/kubeconfig prefix).

The default view will list all pods as a list:

enter image description here

We can change the view to other Kube controllers like replica set (question asked for replication controllers so notice they are deprecated), deployments, cron jobs, etc' by entering a colon : and start typing the desired controller - as we can see K9S provides autocompletion for us:

enter image description here

And we can see all replica sets in the current namespace:

enter image description here

We can just choose the desired replica set by clicking enter and then we'll see the list of all pods which are related to this replica set - we can then press on 'l' to view logs of each pod.

So, unlike in the case of stern, we still need to go on each pod and view its logs but I think it is very convenient with K9S - we first view all pods of a related controller and then investigate logs of each pod by simply navigating with enter, l and escape.

Fast and Lean PDF Viewer for iPhone / iPad / iOS - tips and hints?

For a simple and effective PDF viewer, when you require only limited functionality, you can now (iOS 4.0+) use the QuickLook framework:

First, you need to link against QuickLook.framework and #import <QuickLook/QuickLook.h>;

Afterwards, in either viewDidLoad or any of the lazy initialization methods:

QLPreviewController *previewController = [[QLPreviewController alloc] init];
previewController.dataSource = self;
previewController.delegate = self;
previewController.currentPreviewItemIndex = indexPath.row;
[self presentModalViewController:previewController animated:YES];
[previewController release];

Xlib: extension "RANDR" missing on display ":21". - Trying to run headless Google Chrome

jeues answer helped me nothing :-( after hours I finally found the solution for my system and I think this will help other people too. I had to set the LD_LIBRARY_PATH like this:

   export LD_LIBRARY_PATH=/usr/lib/x86_64-linux-gnu/

after that everything worked very well, even without any "-extension RANDR" switch.

How to delete SQLite database from Android programmatically

I have used the following for "formatting" the database on device after I have changed the structure of the database in assets. I simply uncomment the line in MainActivity when I wanted that the database is read from the assets again. This will reset the device database values and structure to mach with the preoccupied database in assets folder.

    //database initialization. Uncomment to clear the database
    //deleteDatabase("questions.db");

Next, I will implement a button that will run the deleteDatabase so that the user can reset its progress in the game.

Auto logout with Angularjs based on idle user

There should be different ways to do it and each approach should fit a particular application better than another. For most apps, you can simply just handle key or mouse events and enable/disable a logout timer appropriately. That said, on the top of my head, a "fancy" AngularJS-y solution is monitoring the digest loop, if none has been triggered for the last [specified duration] then logout. Something like this.

app.run(function($rootScope) {
  var lastDigestRun = new Date();
  $rootScope.$watch(function detectIdle() {
    var now = new Date();
    if (now - lastDigestRun > 10*60*60) {
       // logout here, like delete cookie, navigate to login ...
    }
    lastDigestRun = now;
  });
});

Find the version of an installed npm package

I added this to my .bashrc

function npmv {
    case $# in # number of arguments passed
    0) v="$(npm -v)" ; #store output from npm -v in variable
        echo "NPM version is: $v"; #can't use single quotes 
                                   #${v} would also work
    ;;   
    1) s="$(npm list --depth=0 $1 | grep $1 | cut -d @ -f 2)";
       echo "$s";
    ;;
    2) case "$2" in # second argument
        g) #global|#Syntax to compare bash string to literal
             s="$(npm list --depth=0 -g $1 | grep $1 | cut -d @ -f 2)";
        echo "$s";
        ;;
        l) #latest
             npm view $1 version; #npm info $1 version does same thing
       ;;
       *) echo 'Invalid arguments';
       ;;
       esac;
    ;;
    *) echo 'Invalid arguments';
    ;;
    esac;
}
export -f npmv

Now all I have to do is type:

  • npmv for the version of npm eg: NPM version is: 4.2.0
  • npmv <package-name> for the local version eg: 0.8.08
  • npmv <package-name> g for global version eg: 0.8.09
  • npmv <package-name> l for latest version eg: 0.8.10

Note -d on cut command means delimit by, followed by @, then f means field the 2 means second field since there will be one either side of the @ symbol.

Removing packages installed with go get

It's safe to just delete the source directory and compiled package file. Find the source directory under $GOPATH/src and the package file under $GOPATH/pkg/<architecture>, for example: $GOPATH/pkg/windows_amd64.

Java generics - why is "extends T" allowed but not "implements T"?

It's sort of arbitrary which of the terms to use. It could have been either way. Perhaps the language designers thought of "extends" as the most fundamental term, and "implements" as the special case for interfaces.

But I think implements would make slightly more sense. I think that communicates more that the parameter types don't have to be in an inheritance relationship, they can be in any kind of subtype relationship.

The Java Glossary expresses a similar view.

MySql Table Insert if not exist otherwise update

Try using this:

If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that would cause a duplicate value in a UNIQUE index orPRIMARY KEY, MySQL performs an [UPDATE`](http://dev.mysql.com/doc/refman/5.7/en/update.html) of the old row...

The ON DUPLICATE KEY UPDATE clause can contain multiple column assignments, separated by commas.

With ON DUPLICATE KEY UPDATE, the affected-rows value per row is 1 if the row is inserted as a new row, 2 if an existing row is updated, and 0 if an existing row is set to its current values. If you specify the CLIENT_FOUND_ROWS flag to mysql_real_connect() when connecting to mysqld, the affected-rows value is 1 (not 0) if an existing row is set to its current values...

How can I fix the Microsoft Visual Studio error: "package did not load correctly"?

  1. Find the ComponentModelCache folder
  2. Delete Microsoft.VisualStudio.Default.cache
  3. Restart Visual Studio

Enjoy using Visual Studio.

How to import Angular Material in project?

Starting from Angular version 9:

Breaking changes:

Components can no longer be imported through "@angular/material". Use the individual secondary entry-points, such as @angular/material/button.

This means that:

import { MatInputModule, MatCardModule } from "@angular/material";

becomes:

import { MatInputModule } from "@angular/material/input";
import { MatCardModule } from "@angular/material/card";

Is it possible to print a variable's type in standard C++?

As mentioned, typeid().name() may return a mangled name. In GCC (and some other compilers) you can work around it with the following code:

#include <cxxabi.h>
#include <iostream>
#include <typeinfo>
#include <cstdlib>

namespace some_namespace { namespace another_namespace {

  class my_class { };

} }

int main() {
  typedef some_namespace::another_namespace::my_class my_type;
  // mangled
  std::cout << typeid(my_type).name() << std::endl;

  // unmangled
  int status = 0;
  char* demangled = abi::__cxa_demangle(typeid(my_type).name(), 0, 0, &status);

  switch (status) {
    case -1: {
      // could not allocate memory
      std::cout << "Could not allocate memory" << std::endl;
      return -1;
    } break;
    case -2: {
      // invalid name under the C++ ABI mangling rules
      std::cout << "Invalid name" << std::endl;
      return -1;
    } break;
    case -3: {
      // invalid argument
      std::cout << "Invalid argument to demangle()" << std::endl;
      return -1;
    } break;
 }
 std::cout << demangled << std::endl;

 free(demangled);

 return 0;

}

What SOAP client libraries exist for Python, and where is the documentation for them?

We released a new library: PySimpleSOAP, that provides support for simple and functional client/server. It goals are: ease of use and flexibility (no classes, autogenerated code or xml is required), WSDL introspection and generation, WS-I standard compliance, compatibility (including Java AXIS, .NET and Jboss WS). It is included into Web2Py to enable full-stack solutions (complementing other supported protocols such as XML_RPC, JSON, AMF-RPC, etc.).

If someone is learning SOAP or want to investigate it, I think it is a good choice to start.

Getting all documents from one collection in Firestore

if you want include Id

async getMarkers() {
  const events = await firebase.firestore().collection('events')
  events.get().then((querySnapshot) => {
      const tempDoc = querySnapshot.docs.map((doc) => {
        return { id: doc.id, ...doc.data() }
      })
      console.log(tempDoc)
    })
}

Same way with array

async getMarkers() {
  const events = await firebase.firestore().collection('events')
  events.get().then((querySnapshot) => {
      const tempDoc = []
      querySnapshot.forEach((doc) => {
         tempDoc.push({ id: doc.id, ...doc.data() })
      })
      console.log(tempDoc)
   })
 }

Git Diff with Beyond Compare

Update for BC4 64bit: This works for Git for Windows v.2.16.2 and Beyond Compare 4 - v.4.2.4 (64bit Edition)

I manually edited the .gitconfig file located in my user root "C:\Users\MyUserName" and replaced the diff/difftool and merge/mergetool tags with

[diff]
  tool = bc
[difftool "bc"]
  path = 'C:/Program Files/Beyond Compare 4/BComp.exe'
[difftool "bc"]
  cmd = \"C:/Program Files/Beyond Compare 4/BComp.exe\" \"$LOCAL\" \"$REMOTE\"
[difftool]
  prompt = false
[merge]
  tool = bc
[mergetool "bc"]
  path = 'C:/Program Files/Beyond Compare 4/BComp.exe'
[mergetool "bc"]
  cmd = \"C:/Program Files/Beyond Compare 4/BComp.exe\" \"$REMOTE\" \"$LOCAL\" \"$BASE\" \"$MERGED\"

Could not determine the dependencies of task ':app:crashlyticsStoreDeobsDebug' if I enable the proguard

Full combo of build/ clean project + build/ rebuild project + file/ Invalidate caches / restart works for me!

Session unset, or session_destroy?

Something to be aware of, the $_SESSION variables are still set in the same page after calling session_destroy() where as this is not the case when using unset($_SESSION) or $_SESSION = array(). Also, unset($_SESSION) blows away the $_SESSION superglobal so only do this when you're destroying a session.

With all that said, it's best to do like the PHP docs has it in the first example for session_destroy().

Add new row to dataframe, at specific row-index, not appended?

insertRow2 <- function(existingDF, newrow, r) {
  existingDF <- rbind(existingDF,newrow)
  existingDF <- existingDF[order(c(1:(nrow(existingDF)-1),r-0.5)),]
  row.names(existingDF) <- 1:nrow(existingDF)
  return(existingDF)  
}

insertRow2(existingDF,newrow,r)

  V1 V2 V3 V4
1  1  6 11 16
2  2  7 12 17
3  1  2  3  4
4  3  8 13 18
5  4  9 14 19
6  5 10 15 20

microbenchmark(
+   rbind(existingDF[1:r,],newrow,existingDF[-(1:r),]),
+   insertRow(existingDF,newrow,r),
+   insertRow2(existingDF,newrow,r)
+ )
Unit: microseconds
                                                    expr     min       lq   median       uq      max
1                       insertRow(existingDF, newrow, r) 513.157 525.6730 531.8715 544.4575 1409.553
2                      insertRow2(existingDF, newrow, r) 430.664 443.9010 450.0570 461.3415  499.988
3 rbind(existingDF[1:r, ], newrow, existingDF[-(1:r), ]) 606.822 625.2485 633.3710 653.1500 1489.216

How to avoid precompiled headers

try to add #include "stdafx.h" before #include "iostream"

When to use RSpec let()?

let is functional as its essentially a Proc. Also its cached.

One gotcha I found right away with let... In a Spec block that is evaluating a change.

let(:object) {FactoryGirl.create :object}

expect {
  post :destroy, id: review.id
}.to change(Object, :count).by(-1)

You'll need to be sure to call let outside of your expect block. i.e. you're calling FactoryGirl.create in your let block. I usually do this by verifying the object is persisted.

object.persisted?.should eq true

Otherwise when the let block is called the first time a change in the database will actually happen due to the lazy instantiation.

Update

Just adding a note. Be careful playing code golf or in this case rspec golf with this answer.

In this case, I just have to call some method to which the object responds. So I invoke the _.persisted?_ method on the object as its truthy. All I'm trying to do is instantiate the object. You could call empty? or nil? too. The point isn't the test but bringing the object ot life by calling it.

So you can't refactor

object.persisted?.should eq true

to be

object.should be_persisted 

as the object hasn't been instantiated... its lazy. :)

Update 2

leverage the let! syntax for instant object creation, which should avoid this issue altogether. Note though it will defeat a lot of the purpose of the laziness of the non banged let.

Also in some instances you might actually want to leverage the subject syntax instead of let as it may give you additional options.

subject(:object) {FactoryGirl.create :object}

Java path..Error of jvm.cfg

Resolved

I had similar issue, I tried different things but nothing worked. Then when I checked the installed programs. I could see two versions of java installed.

What I did is, just uninstall all java versions and freshly installed the required version. But this didn't seem to work when I checked in terminal. Then I had to reopen the terminal and run the command, then only it worked.

Note : Dont forget to reopen the terminal if you are testing via terminal.

How to extract code of .apk file which is not working?

Any .apk file from market or unsigned

  1. If you apk is downloaded from market and hence signed Install Astro File Manager from market. Open Astro > Tools > Application Manager/Backup and select the application to backup on to the SD card . Mount phone as USB drive and access 'backupsapps' folder to find the apk of target app (lets call it app.apk) . Copy it to your local drive same is the case of unsigned .apk.

  2. Download Dex2Jar zip from this link: SourceForge

  3. Unzip the downloaded zip file.

  4. Open command prompt & write the following command on reaching to directory where dex2jar exe is there and also copy the apk in same directory.

    dex2jar targetapp.apk file(./dex2jar app.apk on terminal)

  5. http://jd.benow.ca/ download decompiler from this link.

  6. Open ‘targetapp.apk.dex2jar.jar’ with jd-gui File > Save All Sources to sava the class files in jar to java files.

Mapping two integers to one, in a unique and deterministic way

Is this even possible?
You are combining two integers. They both have the range -2,147,483,648 to 2,147,483,647 but you will only take the positives. That makes 2147483647^2 = 4,61169E+18 combinations. Since each combination has to be unique AND result in an integer, you'll need some kind of magical integer that can contain this amount of numbers.

Or is my logic flawed?

Hashmap with Streams in Java 8 Streams to collect value of Map

You can also do it like this

public Map<Boolean, List<Student>> getpartitionMap(List<Student> studentsList) {

    List<Predicate<Student>> allPredicates = getAllPredicates();
    Predicate<Student> compositePredicate =  allPredicates.stream()
                             .reduce(w -> true, Predicate::and)
     Map<Boolean, List<Student>> studentsMap= studentsList
                .stream()
                .collect(Collectors.partitioningBy(compositePredicate));
    return studentsMap;
}

public List<Student> getValidStudentsList(Map<Boolean, List<Student>> studentsMap) throws Exception {

    List<Student> validStudentsList =  studentsMap.entrySet()
             .stream()
             .filter(p -> p.getKey() == Boolean.TRUE)
             .flatMap(p -> p.getValue().stream())
             .collect(Collectors.toList());

    return validStudentsList;
}

public List<Student> getInValidStudentsList(Map<Boolean, List<Student>> studentsMap) throws Exception {

    List<Student> invalidStudentsList = 
             partionedByPredicate.entrySet()
             .stream()
             .filter(p -> p.getKey() == Boolean.FALSE)
             .flatMap(p -> p.getValue().stream())
             .collect(Collectors.toList());

    return invalidStudentsList;

}

With flatMap you will get just List<Student> instead of List<List<Student>>.

Thanks

How to override application.properties during production in Spring-Boot?

Update with Spring Boot 2.2.2.Release.

Full example here, https://www.surasint.com/spring-boot-override-property-example/

Assume that, in your jar file, you have the application.properties which have these two line:

server.servlet.context-path=/test
server.port=8081

Then, in production, you want to override the server.port=8888 but you don't want to override the other properties.

First you create another file, ex override.properties and have online this line:

server.port=8888

Then you can start the jar like this

java -jar spring-boot-1.0-SNAPSHOT.jar --spring.config.location=classpath:application.properties,/opt/somewhere/override.properties

How do I avoid the specification of the username and password at every git push?

If you already have your SSH keys set up and are still getting the password prompt, make sure your repo URL is in the form

git+ssh://[email protected]/username/reponame.git

as opposed to

https://github.com/username/reponame.git

To see your repo URL, run:

git remote show origin

You can change the URL with git remote set-url like so:

git remote set-url origin git+ssh://[email protected]/username/reponame.git

How can I convert JSON to CSV?

I was having trouble with Dan's proposed solution, but this worked for me:

import json
import csv 

f = open('test.json')
data = json.load(f)
f.close()

f=csv.writer(open('test.csv','wb+'))

for item in data:
  f.writerow([item['pk'], item['model']] + item['fields'].values())

Where "test.json" contained the following:

[ 
{"pk": 22, "model": "auth.permission", "fields": 
  {"codename": "add_logentry", "name": "Can add log entry", "content_type": 8 } }, 
{"pk": 23, "model": "auth.permission", "fields": 
  {"codename": "change_logentry", "name": "Can change log entry", "content_type": 8 } }, {"pk": 24, "model": "auth.permission", "fields": 
  {"codename": "delete_logentry", "name": "Can delete log entry", "content_type": 8 } }
]

Oracle SQL Where clause to find date records older than 30 days

Use:

SELECT *
  FROM YOUR_TABLE
 WHERE creation_date <= TRUNC(SYSDATE) - 30

SYSDATE returns the date & time; TRUNC resets the date to being as of midnight so you can omit it if you want the creation_date that is 30 days previous including the current time.

Depending on your needs, you could also look at using ADD_MONTHS:

SELECT *
  FROM YOUR_TABLE
 WHERE creation_date <= ADD_MONTHS(TRUNC(SYSDATE), -1)

Convert Date/Time for given Timezone - java

We can get the UTC/GMT time stamp from the given date.

/**
 * Get the time stamp in GMT/UTC by passing the valid time (dd-MM-yyyy HH:mm:ss)
 */
public static long getGMTTimeStampFromDate(String datetime) {
    long timeStamp = 0;
    Date localTime = new Date();

    String format = "dd-MM-yyyy HH:mm:ss";
    SimpleDateFormat sdfLocalFormat = new SimpleDateFormat(format);
    sdfLocalFormat.setTimeZone(TimeZone.getDefault());

    try {

        localTime = (Date) sdfLocalFormat.parse(datetime); 

        Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"),
                Locale.getDefault());
        TimeZone tz = cal.getTimeZone();

        cal.setTime(localTime);

        timeStamp = (localTime.getTime()/1000);
        Log.d("GMT TimeStamp: ", " Date TimegmtTime: " + datetime
                + ", GMT TimeStamp : " + localTime.getTime());

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return timeStamp;

}

It will return the UTC time based on passed date.

  • We can do reverse like UTC time stamp to current date and time(vice versa)

        public static String getLocalTimeFromGMT(long gmtTimeStamp) {
                 try{
                        Calendar calendar = Calendar.getInstance();
                        TimeZone tz = TimeZone.getDefault();
                        calendar.setTimeInMillis(gmtTimeStamp * 1000);
        //              calendar.add(Calendar.MILLISECOND, tz.getOffset(calendar.getTimeInMillis())); 
                        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
                        Date currenTimeZone = (Date) calendar.getTime();
                        return sdf.format(currenTimeZone);
                    }catch (Exception e) {
                    }
                    return "";  
                }
    

I hope this will help others. Thanks!!

Hiding the R code in Rmarkdown/knit and just showing the results

Just aggregating the answers and expanding on the basics. Here are three options:

1) Hide Code (individual chunk)

We can include echo=FALSE in the chunk header:

```{r echo=FALSE}
plot(cars)
```

2) Hide Chunks (globally).

We can change the default behaviour of knitr using the knitr::opts_chunk$set function. We call this at the start of the document and include include=FALSE in the chunk header to suppress any output:

---
output: html_document
---

```{r include = FALSE}
knitr::opts_chunk$set(echo=FALSE)
```

```{r}
plot(cars)
```

3) Collapsed Code Chunks

For HTML outputs, we can use code folding to hide the code in the output file. It will still include the code but can only be seen once a user clicks on this. You can read about this further here.

---
output:
  html_document:
    code_folding: "hide"
---


```{r}
plot(cars)
```

enter image description here

How to Calculate Execution Time of a Code Snippet in C++

I suggest using the standard library functions for obtaining time information from the system.

If you want finer resolution, perform more execution iterations. Instead of running the program once and obtaining samples, run it 1000 times or more.

CSS background image to fit width, height should auto-scale in proportion

There is a CSS3 property for this, namely background-size (compatibility check). While one can set length values, it's usually used with the special values contain and cover. In your specific case, you should use cover:

body {
    background-image:    url(images/background.svg);
    background-size:     cover;                      /* <------ */
    background-repeat:   no-repeat;
    background-position: center center;              /* optional, center the image */
}

Eggsplanation for contain and cover

Sorry for the bad pun, but I'm going to use the picture of the day by Biswarup Ganguly for demonstration. Lets say that this is your screen, and the gray area is outside of your visible screen. For demonstration, I'm going to assume a 16x9 ratio.

screen

We want to use the aforementioned picture of the day as a background. However, we cropped the image to 4x3 for some reason. We could set the background-size property to some fixed length, but we will focus on contain and cover. Note that I also assume that we didn't mangle the width and/or height of body.

contain

contain

Scale the image, while preserving its intrinsic aspect ratio (if any), to the largest size such that both its width and its height can fit inside the background positioning area.

This makes sure that the background image is always completely contained in the background positioning area, however, there could be some empty space filled with your background-color in this case:

contain

cover

cover

Scale the image, while preserving its intrinsic aspect ratio (if any), to the smallest size such that both its width and its height can completely cover the background positioning area.

This makes sure that the background image is covering everything. There will be no visible background-color, however depending on the screen's ratio a great part of your image could be cut off:

cover

Demonstration with actual code

_x000D_
_x000D_
div > div {_x000D_
  background-image: url(http://i.stack.imgur.com/r5CAq.jpg);_x000D_
  background-repeat: no-repeat;_x000D_
  background-position: center center;_x000D_
  background-color: #ccc;_x000D_
  border: 1px solid;_x000D_
  width: 20em;_x000D_
  height: 10em;_x000D_
}_x000D_
div.contain {_x000D_
  background-size: contain;_x000D_
}_x000D_
div.cover {_x000D_
  background-size: cover;_x000D_
}_x000D_
/********************************************_x000D_
 Additional styles for the explanation boxes _x000D_
*********************************************/_x000D_
_x000D_
div > div {_x000D_
  margin: 0 1ex 1ex 0;_x000D_
  float: left;_x000D_
}_x000D_
div + div {_x000D_
  clear: both;_x000D_
  border-top: 1px dashed silver;_x000D_
  padding-top:1ex;_x000D_
}_x000D_
div > div::after {_x000D_
  background-color: #000;_x000D_
  color: #fefefe;_x000D_
  margin: 1ex;_x000D_
  padding: 1ex;_x000D_
  opacity: 0.8;_x000D_
  display: block;_x000D_
  width: 10ex;_x000D_
  font-size: 0.7em;_x000D_
  content: attr(class);_x000D_
}
_x000D_
<div>_x000D_
  <div class="contain"></div>_x000D_
  <p>Note the grey background. The image does not cover the whole region, but it's fully <em>contained</em>._x000D_
  </p>_x000D_
</div>_x000D_
<div>_x000D_
  <div class="cover"></div>_x000D_
  <p>Note the ducks/geese at the bottom of the image. Most of the water is cut, as well as a part of the sky. You don't see the complete image anymore, but neither do you see any background color; the image <em>covers</em> all of the <code>&lt;div&gt;</code>.</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to git-svn clone the last n revisions from a Subversion repository?

I find myself using the following often to get a limited number of revisions out of our huge subversion tree (we're soon reaching svn revision 35000).

# checkout a specific revision
git svn clone -r N svn://some/repo/branch/some-branch
# enter it and get all commits since revision 'N'
cd some-branch
git svn rebase

And a good way to find out where a branch started is to do a svn log it and find the first one on the branch (the last one listed when doing):

svn log --stop-on-copy svn://some/repo/branch/some-branch

So far I have not really found the hassle worth it in tracking all branches. It takes too much time to clone and svn and git don't work together as good as I would like. I tend to create patch files and apply them on the git clone of another svn branch.

Set cookies for cross origin requests

What you need to do

To allow receiving & sending cookies by a CORS request successfully, do the following.

Back-end (server): Set the HTTP header Access-Control-Allow-Credentials value to true. Also, make sure the HTTP headers Access-Control-Allow-Origin and Access-Control-Allow-Headers are set and not with a wildcard *.

Recommended Cookie settings per Chrome and Firefox update in 2021: SameSite=None and Secure. See MDN documentation

For more info on setting CORS in express js read the docs here

Front-end (client): Set the XMLHttpRequest.withCredentials flag to true, this can be achieved in different ways depending on the request-response library used:

Or

Avoid having to use CORS in combination with cookies. You can achieve this with a proxy.

If you for whatever reason don't avoid it. The solution is above.

It turned out that Chrome won't set the cookie if the domain contains a port. Setting it for localhost (without port) is not a problem. Many thanks to Erwin for this tip!

How to get the Parent's parent directory in Powershell?

You can use

(get-item $scriptPath).Directoryname

to get the string path or if you want the Directory type use:

(get-item $scriptPath).Directory

Checking Value of Radio Button Group via JavaScript?

Try:


var selectedVal;

for( i = 0; i < document.form_name.gender.length; i++ )
{
  if(document.form_name.gender[i].checked)
    selectedVal = document.form_name.gender[i].value; //male or female
    break;
  }
}

Android Studio says "cannot resolve symbol" but project compiles

This worked for me-- (File -> Indicate Cashes) --> (Invalidate and Restart).

How to store decimal values in SQL Server?

DECIMAL(18,0) will allow 0 digits after the decimal point.

Use something like DECIMAL(18,4) instead that should do just fine!

That gives you a total of 18 digits, 4 of which after the decimal point (and 14 before the decimal point).

Using :focus to style outer div?

Some people, like me, will benefit from using the :focus-within pseudo-class.

Using it will apply the css you want to a div, for instance.

You can read more here https://developer.mozilla.org/en-US/docs/Web/CSS/:focus-within

Format date and time in a Windows batch script

For a very simple solution for numeric date for use in filenames use the following code:

set month=%date:~4,2%
set day=%date:~7,2%
set curTimestamp=%month%%day%%year%

rem then the you can add a prefix and a file extension easily like this
echo updates%curTimestamp%.txt

Jquery Ajax Loading image

Please note that: ajaxStart / ajaxStop is not working for ajax jsonp request (ajax json request is ok)

I am using jquery 1.7.2 while writing this.

here is one of the reference I found: http://bugs.jquery.com/ticket/8338

TensorFlow ValueError: Cannot feed value of shape (64, 64, 3) for Tensor u'Placeholder:0', which has shape '(?, 64, 64, 3)'

image has a shape of (64,64,3).

Your input placeholder _x have a shape of (?, 64,64,3).

The problem is that you're feeding the placeholder with a value of a different shape.

You have to feed it with a value of (1, 64, 64, 3) = a batch of 1 image.

Just reshape your image value to a batch with size one.

image = array(img).reshape(1, 64,64,3)

P.S: the fact that the input placeholder accepts a batch of images, means that you can run predicions for a batch of images in parallel. You can try to read more than 1 image (N images) and than build a batch of N image, using a tensor with shape (N, 64,64,3)

Convert UTC date time to local date time

Matt's answer is missing the fact that the daylight savings time could be different between Date() and the date time it needs to convert - here is my solution:

    function ConvertUTCTimeToLocalTime(UTCDateString)
    {
        var convertdLocalTime = new Date(UTCDateString);

        var hourOffset = convertdLocalTime.getTimezoneOffset() / 60;

        convertdLocalTime.setHours( convertdLocalTime.getHours() + hourOffset ); 

        return convertdLocalTime;
    }

And the results in the debugger:

UTCDateString: "2014-02-26T00:00:00"
convertdLocalTime: Wed Feb 26 2014 00:00:00 GMT-0800 (Pacific Standard Time)

In Git, how do I figure out what my current revision is?

What do you mean by "version number"? It is quite common to tag a commit with a version number and then use

$ git describe --tags

to identify the current HEAD w.r.t. any tags. If you mean you want to know the hash of the current HEAD, you probably want:

$ git rev-parse HEAD

or for the short revision hash:

$ git rev-parse --short HEAD

It is often sufficient to do:

$ cat .git/refs/heads/${branch-master}

but this is not reliable as the ref may be packed.

How to remove all null elements from a ArrayList or String Array?

Mainly I'm using this:

list.removeAll(Collections.singleton(null));

But after I learned Java 8, I switched to this:

List.removeIf(Objects::isNull);

Give all permissions to a user on a PostgreSQL database

All commands must be executed while connected to the right database in the right database cluster. Make sure of it.

The user needs access to the database, obviously:

GRANT CONNECT ON DATABASE my_db TO my_user;

And (at least) the USAGE privilege on the schema:

GRANT USAGE ON SCHEMA public TO my_user;

Or grant USAGE on all custom schemas:

DO
$$
BEGIN
   -- RAISE NOTICE '%', (  -- use instead of EXECUTE to see generated commands
   EXECUTE (
   SELECT string_agg(format('GRANT USAGE ON SCHEMA %I TO my_user', nspname), '; ')
   FROM   pg_namespace
   WHERE  nspname <> 'information_schema' -- exclude information schema and ...
   AND    nspname NOT LIKE 'pg\_%'        -- ... system schemas
   );
END
$$;

Then, all permissions for all tables (requires Postgres 9.0 or later).
And don't forget sequences (if any):

GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO my_user;
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO my_user;

For older versions you could use the "Grant Wizard" of pgAdmin III (the default GUI).

There are some other objects, the manual for GRANT has the complete list as of Postgres 12:

privileges on a database object (table, column, view, foreign table, sequence, database, foreign-data wrapper, foreign server, function, procedure, procedural language, schema, or tablespace)

But the rest is rarely needed. More details:

Consider upgrading to a current version.

What's the best practice for primary keys in tables?

Just an extra comment on something that is often overlooked. Sometimes not using a surrogate key has benefits in the child tables. Let's say we have a design that allows you to run multiple companies within the one database (maybe it's a hosted solution, or whatever).

Let's say we have these tables and columns:

Company:
  CompanyId   (primary key)

CostCenter:
  CompanyId   (primary key, foreign key to Company)
  CostCentre  (primary key)

CostElement
  CompanyId   (primary key, foreign key to Company)
  CostElement (primary key)

Invoice:
  InvoiceId    (primary key)
  CompanyId    (primary key, in foreign key to CostCentre, in foreign key to CostElement)
  CostCentre   (in foreign key to CostCentre)
  CostElement  (in foreign key to CostElement)

In case that last bit doesn't make sense, Invoice.CompanyId is part of two foreign keys, one to the CostCentre table and one to the CostElement table. The primary key is (InvoiceId, CompanyId).

In this model, it's not possible to screw-up and reference a CostElement from one company and a CostCentre from another company. If a surrogate key was used on the CostElement and CostCentre tables, it would be.

The fewer chances to screw up, the better.

How to view unallocated free space on a hard disk through terminal

The simplest way to show unallocated free space in a single command:

$ sudo sfdisk --list-free /dev/sdX

(Add the --quiet option if you don't need the extra info about sector size, etc.)

iterating quickly through list of tuples

Assuming a bit more memory usage is not a problem and if the first item of your tuple is hashable, you can create a dict out of your list of tuples and then looking up the value is as simple as looking up a key from the dict. Something like:

dct = dict(tuples)
val = dct.get(key) # None if item not found else the corresponding value

EDIT: To create a reverse mapping, use something like:

revDct = dict((val, key) for (key, val) in tuples)

Using both Python 2.x and Python 3.x in IPython Notebook

I looked at this excellent info and then wondered, since

  1. i have python2, python3 and IPython all installed,
  2. i have PyCharm installed,
  3. PyCharm uses IPython for its Python Console,

if PyCharm would use

  1. IPython-py2 when Menu>File>Settings>Project>Project Interpreter == py2 AND
  2. IPython-py3 when Menu>File>Settings>Project>Project Interpreter == py3

ANSWER: Yes!

P.S. i have Python Launcher for Windows installed as well.

java Compare two dates

Try using this Function.It Will help You:-

public class Main {   
public static void main(String args[]) 
 {        
  Date today=new Date();                     
  Date myDate=new Date(today.getYear(),today.getMonth()-1,today.getDay());
  System.out.println("My Date is"+myDate);    
  System.out.println("Today Date is"+today);
  if(today.compareTo(myDate)<0)
     System.out.println("Today Date is Lesser than my Date");
  else if(today.compareTo(myDate)>0)
     System.out.println("Today Date is Greater than my date"); 
  else
     System.out.println("Both Dates are equal");      
  }
}

Clear MySQL query cache without restarting server

according the documentation, this should do it...

RESET QUERY CACHE 

Turn a string into a valid filename?

>>> import string
>>> safechars = bytearray(('_-.()' + string.digits + string.ascii_letters).encode())
>>> allchars = bytearray(range(0x100))
>>> deletechars = bytearray(set(allchars) - set(safechars))
>>> filename = u'#ab\xa0c.$%.txt'
>>> safe_filename = filename.encode('ascii', 'ignore').translate(None, deletechars).decode()
>>> safe_filename
'abc..txt'

It doesn't handle empty strings, special filenames ('nul', 'con', etc).

Hibernate openSession() vs getCurrentSession()

If we talk about SessionFactory.openSession()

  • It always creates a new Session object.
  • You need to explicitly flush and close session objects.
  • In single threaded environment it is slower than getCurrentSession().
  • You do not need to configure any property to call this method.

And If we talk about SessionFactory.getCurrentSession()

  • It creates a new Session if not exists, else uses same session which is in current hibernate context.
  • You do not need to flush and close session objects, it will be automatically taken care by Hibernate internally.
  • In single threaded environment it is faster than openSession().
  • You need to configure additional property. "hibernate.current_session_context_class" to call getCurrentSession() method, otherwise it will throw an exception.

Centering a canvas

in order to center the canvas within the window +"px" should be added to el.style.top and el.style.left.

el.style.top = (viewportHeight - canvasHeight) / 2 +"px";
el.style.left = (viewportWidth - canvasWidth) / 2 +"px";

Textfield with only bottom border

Probably a duplicate of this post: A customized input text box in html/html5

_x000D_
_x000D_
input {_x000D_
  border: 0;_x000D_
  outline: 0;_x000D_
  background: transparent;_x000D_
  border-bottom: 1px solid black;_x000D_
}
_x000D_
<input></input>
_x000D_
_x000D_
_x000D_

Is SMTP based on TCP or UDP?

Seems the SMTP as internet standard uses only reliable Transport protocol. RFC821 has TCP, NCP, NITS as examples!

Turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the <serviceDebug> configuration behavior) on the server

As the error information said first please try to increase the timeout value in the both the client side and service side as following:

<basicHttpBinding>
    <binding name="basicHttpBinding_ACRMS" maxBufferSize="2147483647"
      maxReceivedMessageSize="2147483647"
      openTimeout="00:20:00" 
      receiveTimeout="00:20:00" closeTimeout="00:20:00"
      sendTimeout="00:20:00">
      <readerQuotas maxDepth="32" maxStringContentLength="2097152"
        maxArrayLength="2097152" maxBytesPerRead="4006" maxNameTableCharCount="16384" />
    </binding>

Then please do not forget to apply this binding configuration to the endpoint by doing the following:

<endpoint address="" binding="basicHttpBinding" 
      bindingConfiguration="basicHttpBinding_ACRMS"
      contract="MonitorRAM.IService1" />

If the above can not help, it will be better if you can try to upload your main project here, then I want to have a test in my side.

RHEL 6 - how to install 'GLIBC_2.14' or 'GLIBC_2.15'?

Naive question: Is it possible to somehow download GLIBC 2.15, put it in any folder (e.g. /tmp/myglibc) and then point to this path ONLY when executing something that needs this specific version of glibc?

Yes, it's possible.

Finding the position of bottom of a div with jquery

EDIT: this solution is now in the original answer too.

The accepted answer is not quite correct. You should not be using the position() function since it is relative to the parent. If you are doing global positioning(in most cases?) you should only add the offset top with the outerheight like so:

var actualBottom = $(selector).offset().top + $(selector).outerHeight(true);

The docs http://api.jquery.com/offset/

How to change the font on the TextView?

You might want to create static class which will contain all the fonts. That way, you won't create the font multiple times which might impact badly on performance. Just make sure that you create a sub-folder called "fonts" under "assets" folder.

Do something like:

public class CustomFontsLoader {

public static final int FONT_NAME_1 =   0;
public static final int FONT_NAME_2 =   1;
public static final int FONT_NAME_3 =   2;

private static final int NUM_OF_CUSTOM_FONTS = 3;

private static boolean fontsLoaded = false;

private static Typeface[] fonts = new Typeface[3];

private static String[] fontPath = {
    "fonts/FONT_NAME_1.ttf",
    "fonts/FONT_NAME_2.ttf",
    "fonts/FONT_NAME_3.ttf"
};


/**
 * Returns a loaded custom font based on it's identifier. 
 * 
 * @param context - the current context
 * @param fontIdentifier = the identifier of the requested font
 * 
 * @return Typeface object of the requested font.
 */
public static Typeface getTypeface(Context context, int fontIdentifier) {
    if (!fontsLoaded) {
        loadFonts(context);
    }
    return fonts[fontIdentifier];
}


private static void loadFonts(Context context) {
    for (int i = 0; i < NUM_OF_CUSTOM_FONTS; i++) {
        fonts[i] = Typeface.createFromAsset(context.getAssets(), fontPath[i]);
    }
    fontsLoaded = true;

}
}

This way, you can get the font from everywhere in your application.

Is there a program to decompile Delphi?

Here's a list : http://delphi.about.com/od/devutilities/a/decompiling_3.htm (and this page mentions some more : http://www.program-transformation.org/Transform/DelphiDecompilers )

I've used DeDe on occasion, but it's not really all that powerfull, and it's not up-to-date with current Delphi versions (latest version it supports is Delphi 7 I believe)

DLL load failed error when importing cv2

The issue is due to the missing python3.dll file in Anaconda3.

To fix the issue, you should simply copy the python3.dll to C:\Program Files\Anaconda3 (or wherever your Anaconda3 is installed).

You can get the python3.dll by downloading the binaries provided at the bottom of the Python's Release page and extracting the python3.dll from the ZIP file.

How do I find an element that contains specific text in Selenium WebDriver (Python)?

Use driver.find_elements_by_xpath and matches regex matching function for the case insensitive search of the element by its text.

driver.find_elements_by_xpath("//*[matches(.,'My Button', 'i')]")

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

Try using a timer:

var mnumber = document.getElementById('mobileno').value;
if (mnumber.length >=10) 
{ 
    alert("Mobile Number Should be in 10 digits only");
    document.getElementById('mobileno').value = "";
    window.setTimeout(function ()
    {
        document.getElementById('mobileno').focus();
    }, 0);
    return false;
}

A timer with a count of 0 will run when the thread becomes idle. If that doesn't help, try the code (with the timer) in the onblur event instead.

How do I configure git to ignore some files locally?

You can install some git aliases to make this process simpler. This edits the [alias] node of your .gitconfig file.

git config --global alias.ignore 'update-index --skip-worktree'
git config --global alias.unignore 'update-index --no-skip-worktree'
git config --global alias.ignored '!git ls-files -v | grep "^S"'

The shortcuts this installs for you are as follows:

  • git ignore config.xml
    • git will pretend that it doesn't see any changes upon config.xml — preventing you from accidentally committing those changes.
  • git unignore config.xml
    • git will resume acknowledging your changes to config.xml — allowing you again to commit those changes.
  • git ignored
    • git will list all the files which you are "ignoring" in the manner described above.

I built these by referring to phatmann's answer — which presents an --assume-unchanged version of the same.

The version I present uses --skip-worktree for ignoring local changes. See Borealid's answer for a full explanation of the difference, but essentially --skip-worktree's purpose is for developers to change files without the risk of committing their changes.

The git ignored command presented here uses git ls-files -v, and filters the list to show just those entries beginning with the S tag. The S tag denotes a file whose status is "skip worktree". For a full list of the file statuses shown by git ls-files: see the documentation for the -t option on git ls-files.

DateTime format to SQL format using C#

Your problem is in the Date property that truncates DateTime to date only. You could put the conversion like this:

DateTime myDateTime = DateTime.Now;

string sqlFormattedDate = myDateTime.ToString("yyyy-MM-dd HH:mm:ss");

Python how to plot graph sine wave

A simple way to plot sine wave in python using matplotlib.

import numpy as np
import matplotlib.pyplot as plt


x=np.arange(0,3*np.pi,0.1)
y=np.sin(x)
plt.plot(x,y)
plt.title("SINE WAVE")
plt.show()

How to use dashes in HTML-5 data-* attributes in ASP.NET MVC

I do not like use pure "a" tag, too much typing. So I come with solution. In view it look

<%: Html.ActionLink(node.Name, "Show", "Browse", 
                    Dic.Route("id", node.Id), Dic.New("data-nodeId", node.Id)) %>

Implementation of Dic class

public static class Dic
{
    public static Dictionary<string, object> New(params object[] attrs)
    {
        var res = new Dictionary<string, object>();
        for (var i = 0; i < attrs.Length; i = i + 2)
            res.Add(attrs[i].ToString(), attrs[i + 1]);
        return res;
    }

    public static RouteValueDictionary Route(params object[] attrs)
    {
        return new RouteValueDictionary(Dic.New(attrs));
    }
}

Inserting multiple rows in mysql

If you have your data in a text-file, you can use LOAD DATA INFILE.

When loading a table from a text file, use LOAD DATA INFILE. This is usually 20 times faster than using INSERT statements.

Optimizing INSERT Statements

You can find more tips on how to speed up your insert statements on the link above.

How can I get the MAC and the IP address of a connected client in PHP?

too late to answer but here is my approach since no one mentioned this here:
why note a client side solution ?
a javascript implementation to store the mac in a cookie (you can encrypt it before that)
then each request must include that cookie name, else it will be rejected.
to make this even more fun you can make a server side verification
from the mac address you get the manifacturer (there are plenty of free APIs for this)
then compare it with the user_agent value to see if there was some sort of manipulation:
a mac address of HP + a user agent of Safari = reject request.

how to use the Box-Cox power transformation in R

Applying the BoxCox transformation to data, without the need of any underlying model, can be done currently using the package geoR. Specifically, you can use the function boxcoxfit() for finding the best parameter and then predict the transformed variables using the function BCtransform().

Linq order by, group by and order by each group?

try this...

public class Student 
    {
        public int Grade { get; set; }
        public string Name { get; set; }
        public override string ToString()
        {
            return string.Format("Name{0} : Grade{1}", Name, Grade);
        }
    }

class Program
{
    static void Main(string[] args)
    {

      List<Student> listStudents = new List<Student>();
      listStudents.Add(new Student() { Grade = 10, Name = "Pedro" });
      listStudents.Add(new Student() { Grade = 10, Name = "Luana" });
      listStudents.Add(new Student() { Grade = 10, Name = "Maria" });
      listStudents.Add(new Student() { Grade = 11, Name = "Mario" });
      listStudents.Add(new Student() { Grade = 15, Name = "Mario" });
      listStudents.Add(new Student() { Grade = 10, Name = "Bruno" });
      listStudents.Add(new Student() { Grade = 10, Name = "Luana" });
      listStudents.Add(new Student() { Grade = 11, Name = "Luana" });
      listStudents.Add(new Student() { Grade = 22, Name = "Maria" });
      listStudents.Add(new Student() { Grade = 55, Name = "Bruno" });
      listStudents.Add(new Student() { Grade = 77, Name = "Maria" });
      listStudents.Add(new Student() { Grade = 66, Name = "Maria" });
      listStudents.Add(new Student() { Grade = 88, Name = "Bruno" });
      listStudents.Add(new Student() { Grade = 42, Name = "Pedro" });
      listStudents.Add(new Student() { Grade = 33, Name = "Bruno" });
      listStudents.Add(new Student() { Grade = 33, Name = "Luciana" });
      listStudents.Add(new Student() { Grade = 17, Name = "Maria" });
      listStudents.Add(new Student() { Grade = 25, Name = "Luana" });
      listStudents.Add(new Student() { Grade = 25, Name = "Pedro" });

      listStudents.GroupBy(g => g.Name).OrderBy(g => g.Key).SelectMany(g => g.OrderByDescending(x => x.Grade)).ToList().ForEach(x => Console.WriteLine(x.ToString()));
    }
}

Drop multiple columns in pandas

You don't need to wrap it in a list with [..], just provide the subselection of the columns index:

df.drop(df.columns[[1, 69]], axis=1, inplace=True)

as the index object is already regarded as list-like.

What's the difference between %s and %d in Python string formatting?

from python 3 doc

%d is for decimal integer

%s is for generic string or object and in case of object, it will be converted to string

Consider the following code

name ='giacomo'
number = 4.3
print('%s %s %d %f %g' % (name, number, number, number, number))

the out put will be

giacomo 4.3 4 4.300000 4.3

as you can see %d will truncate to integer, %s will maintain formatting, %f will print as float and %g is used for generic number

obviously

print('%d' % (name))

will generate an exception; you cannot convert string to number

PHP Session Destroy on Log Out Button

First give the link of logout.php page in that logout button.In that page make the code which is given below:

Here is the code:

<?php
 session_start();
 session_destroy();
?>

When the session has started, the session for the last/current user has been started, so don't need to declare the username. It will be deleted automatically by the session_destroy method.

How to pass boolean parameter value in pipeline to downstream jobs?

like Jesse Jesse Glick and abguy said you can enumerate string into Boolean type:

Boolean.valueOf(string_variable)

or the opposite Boolean into string:

String.valueOf(boolean_variable)

in my case I had to to downstream Boolean parameter to another job. So for this you will need the use the class BooleanParameterValue :

build job: 'downstream_job_name', parameters:
[
[$class: 'BooleanParameterValue', name: 'parameter_name', value: false],
], wait: true

POST request via RestTemplate in JSON

Why work harder than you have to? postForEntity accepts a simple Map object as input. The following works fine for me while writing tests for a given REST endpoint in Spring. I believe it's the simplest possible way of making a JSON POST request in Spring:

@Test
public void shouldLoginSuccessfully() {
  // 'restTemplate' below has been @Autowired prior to this
  Map map = new HashMap<String, String>();
  map.put("username", "bob123");
  map.put("password", "myP@ssw0rd");
  ResponseEntity<Void> resp = restTemplate.postForEntity(
      "http://localhost:8000/login",
      map,
      Void.class);
  assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.OK);
}

Is there a pretty print for PHP?

error_log(print_r($variable,true));

to send to syslog or eventlog for windows

Nested lists python

The question title is too wide and the author's need is more specific. In my case, I needed to extract all elements from nested list like in the example below:

Example:

input -> [1,2,[3,4]]
output -> [1,2,3,4]

The code below gives me the result, but I would like to know if anyone can create a simpler answer:

def get_elements_from_nested_list(l, new_l):
    if l is not None:
        e = l[0]
        if isinstance(e, list):
            get_elements_from_nested_list(e, new_l)
        else:
            new_l.append(e)
        if len(l) > 1:
            return get_elements_from_nested_list(l[1:], new_l)
        else:
            return new_l

Call of the method

l = [1,2,[3,4]]
new_l = []

get_elements_from_nested_list(l, new_l)

How to describe table in SQL Server 2008?

According to this documentation:

DESC MY_TABLE

is equivalent to

SELECT column_name "Name", nullable "Null?", concat(concat(concat(data_type,'('),data_length),')') "Type" FROM user_tab_columns WHERE table_name='TABLE_NAME_TO_DESCRIBE';

I've roughly translated that to the SQL Server equivalent for you - just make sure you're running it on the EX database.

SELECT column_name AS [name],
       IS_NULLABLE AS [null?],
       DATA_TYPE + COALESCE('(' + CASE WHEN CHARACTER_MAXIMUM_LENGTH = -1
                                  THEN 'Max'
                                  ELSE CAST(CHARACTER_MAXIMUM_LENGTH AS VARCHAR(5))
                                  END + ')', '') AS [type]
FROM   INFORMATION_SCHEMA.Columns
WHERE  table_name = 'EMP_MAST'

Django error - matching query does not exist

Maybe you have no Comments record with such primary key, then you should use this code:

try:
    comment = Comment.objects.get(pk=comment_id)
except Comment.DoesNotExist:
    comment = None

python pandas: apply a function with arguments to a series

Newer versions of pandas do allow you to pass extra arguments (see the new documentation). So now you can do:

my_series.apply(your_function, args=(2,3,4), extra_kw=1)

The positional arguments are added after the element of the series.


For older version of pandas:

The documentation explains this clearly. The apply method accepts a python function which should have a single parameter. If you want to pass more parameters you should use functools.partial as suggested by Joel Cornett in his comment.

An example:

>>> import functools
>>> import operator
>>> add_3 = functools.partial(operator.add,3)
>>> add_3(2)
5
>>> add_3(7)
10

You can also pass keyword arguments using partial.

Another way would be to create a lambda:

my_series.apply((lambda x: your_func(a,b,c,d,...,x)))

But I think using partial is better.

How do you extract classes' source code from a dll file?

Use dotPeek

enter image description here

Select the .dll to decompile

enter image description here

That's it

WampServer orange icon

If you are using wampserver 3 (recommended, works with no configuration usually)

  • click wampserver icon > apache > service administration > install service
  • click wampserver icon > mysql > service administration > install service
  • click wampserver icon > mariadb > service administration > install service
  • click wampserver icon > restart all services

if this doesnt fix it, try:

  • right click wampserver icon > Tools > Check httpd.conf syntax (then fix the issue it identifies and restart all services, likely it's bad syntax in your virtual hosts file)

  • right click wampserver icon > Tools > test port 80 (you likely have skype turned on or something else, turn it off and restart all services)

If this doesnt fix it, maybe have a windows conflict:

If this doesnt fix it:

  • right click wampserver icon > tools
    • check all of those for clues

Can't push to the heroku

Make sure you have package.json inside root of your project. Happy coding :)

Send email from localhost running XAMMP in PHP using GMAIL mail server

Simplest way is to use PHPMailer and Gmail SMTP. The configuration would be like the below.

require 'PHPMailer/PHPMailerAutoload.php';
$mail = new PHPMailer;

$mail->isSMTP();                            
$mail->Host = 'smtp.gmail.com';            
$mail->SMTPAuth = true;                     
$mail->Username = 'Email Address';          
$mail->Password = 'Email Account Password'; 
$mail->SMTPSecure = 'tls';               
$mail->Port = 587;                  

Example script and full source code can be found from here - How to Send Email from Localhost in PHP

How can I merge two MySQL tables?

If you need to do it manually, one time:

First, merge in a temporary table, with something like:

create table MERGED as select * from table 1 UNION select * from table 2

Then, identify the primary key constraints with something like

SELECT COUNT(*), PK from MERGED GROUP BY PK HAVING COUNT(*) > 1

Where PK is the primary key field...

Solve the duplicates.

Rename the table.

[edited - removed brackets in the UNION query, which was causing the error in the comment below]

Error in data frame undefined columns selected

Are you meaning?

data2 <- data1[good,]

With

data1[good]

you're selecting columns in a wrong way (using a logical vector of complete rows).

Consider that parameter pollutant is not used; is it a column name that you want to extract? if so it should be something like

data2 <- data1[good, pollutant]

Furthermore consider that you have to rbind the data.frames inside the for loop, otherwise you get only the last data.frame (its completed.cases)

And last but not least, i'd prefer generating filenames eg with

id <- 1:322
paste0( directory, "/", gsub(" ", "0", sprintf("%3d",id)), ".csv")

A little modified chunk of ?sprintf

The string fmt (in our case "%3d") contains normal characters, which are passed through to the output string, and also conversion specifications which operate on the arguments provided through .... The allowed conversion specifications start with a % and end with one of the letters in the set aAdifeEgGosxX%. These letters denote the following types:

  • d: integer

Eg a more general example

    sprintf("I am %10d years old", 25)
[1] "I am         25 years old"
          ^^^^^^^^^^
          |        |
          1       10

How do I do redo (i.e. "undo undo") in Vim?

Also check out :undolist, which offers multiple paths through the undo history. This is useful if you accidentally type something after undoing too much.

Center an element in Bootstrap 4 Navbar

from the docs

Navbars may contain bits of text with the help of .navbar-text. This class adjusts vertical alignment and horizontal spacing for strings of text.

i applied the .navbar-text class to my <li> element, so the result is

<li class="nav-item navbar-text">

this centers the links vertically with respect to my navbar-brand img

how to get multiple checkbox value using jquery

Try getPrameterValues() for getting values from multiple checkboxes.

How can I increment a date by one day in Java?

I prefer to use DateUtils from Apache. Check this http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/time/DateUtils.html. It is handy especially when you have to use it multiple places in your project and would not want to write your one liner method for this.

The API says:

addDays(Date date, int amount) : Adds a number of days to a date returning a new object.

Note that it returns a new Date object and does not make changes to the previous one itself.

How to Call Controller Actions using JQuery in ASP.NET MVC

the previous response is ASP.NET only

you need a reference to jquery (perhaps from a CDN): http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.js

and then a similar block of code but simpler...

$.ajax({ url: '/Controller/Action/Id',
         success: function(data) { alert(data); }, 
         statusCode : {
             404: function(content) { alert('cannot find resource'); },
             500: function(content) { alert('internal server error'); }
         }, 
         error: function(req, status, errorObj) {
               // handle status === "timeout"
               // handle other errors
         }
});

I've added some necessary handlers, 404 and 500 happen all the time if you are debugging code. Also, a lot of other errors, such as timeout, will filter out through the error handler.

ASP.NET MVC Controllers handle requests, so you just need to request the correct URL and the controller will pick it up. This code sample with work in environments other than ASP.NET

How to solve "Kernel panic - not syncing - Attempted to kill init" -- without erasing any user data

Booting from CD to rescue the installation and editing /etc/selinux/config: changed SELINUX from enforcing to permissive. Rebooted and system booted

/etc/selinux/config before change:

SELINUX=enforcing and SELINUXTYPE=permissive

/etc/selinux/config after change: SELINUX=permissive and SELINUXTYPE=permissive

Java Generics With a Class & an Interface - Together

You can't do it with "anonymous" type parameters (ie, wildcards that use ?), but you can do it with "named" type parameters. Simply declare the type parameter at method or class level.

import java.util.List;
interface A{}
interface B{}
public class Test<E extends B & A, T extends List<E>> {
    T t;
}

What does "ulimit -s unlimited" do?

When you call a function, a new "namespace" is allocated on the stack. That's how functions can have local variables. As functions call functions, which in turn call functions, we keep allocating more and more space on the stack to maintain this deep hierarchy of namespaces.

To curb programs using massive amounts of stack space, a limit is usually put in place via ulimit -s. If we remove that limit via ulimit -s unlimited, our programs will be able to keep gobbling up RAM for their evergrowing stack until eventually the system runs out of memory entirely.

int eat_stack_space(void) { return eat_stack_space(); }
// If we compile this with no optimization and run it, our computer could crash.

Usually, using a ton of stack space is accidental or a symptom of very deep recursion that probably should not be relying so much on the stack. Thus the stack limit.

Impact on performace is minor but does exist. Using the time command, I found that eliminating the stack limit increased performance by a few fractions of a second (at least on 64bit Ubuntu).

Oracle - how to remove white spaces?

Run below query replacing TABLE_NAME & COLUMN_NAME with your actual table & column names:

UPDATE TABLE_NAME SET COLUMN_NAME=TRIM(' ' from COLUMN_NAME);

Center image in table td in CSS

Another option is the use <th> instead of <td>. <th> defaults to center; <td> defaults to left.

How to set the size of button in HTML

If using the following HTML:

<button id="submit-button"></button>

Style can be applied through JS using the style object available on an HTMLElement.

To set height and width to 200px of the above example button, this would be the JS:

var myButton = document.getElementById('submit-button');
myButton.style.height = '200px';
myButton.style.width= '200px';

I believe with this method, you are not directly writing CSS (inline or external), but using JavaScript to programmatically alter CSS Declarations.

Iterating over dictionaries using 'for' loops

key is simply a variable.

For Python2.X:

d = {'x': 1, 'y': 2, 'z': 3} 
for my_var in d:
    print my_var, 'corresponds to', d[my_var]

... or better,

d = {'x': 1, 'y': 2, 'z': 3} 
for the_key, the_value in d.iteritems():
    print the_key, 'corresponds to', the_value

For Python3.X:

d = {'x': 1, 'y': 2, 'z': 3} 
for the_key, the_value in d.items():
    print(the_key, 'corresponds to', the_value)

String.equals() with multiple conditions (and one action on result)

No,its check like if string is "john" OR "mary" OR "peter" OR "etc."

you should check using ||

Like.,,if(str.equals("john") || str.equals("mary") || str.equals("peter"))

What do 1.#INF00, -1.#IND00 and -1.#IND mean?

For anyone wondering about the difference between -1.#IND00 and -1.#IND (which the question specifically asked, and none of the answers address):

-1.#IND00

This specifically means a non-zero number divided by zero, e.g. 3.14 / 0 (source)

-1.#IND (a synonym for NaN)

This means one of four things (see wiki from source):

1) sqrt or log of a negative number

2) operations where both variables are 0 or infinity, e.g. 0 / 0

3) operations where at least one variable is already NaN, e.g. NaN * 5

4) out of range trig, e.g. arcsin(2)

Django: How can I call a view function from template?

How about this:

<a class="btn btn-primary" href="{% url 'url-name'%}">Button-Text</a>

The class is including bootstrap styles for primary button.

setting request headers in selenium

With the solutions already discussed above the most reliable one is using Browsermob-Proxy

But while working with the remote grid machine, Browsermob-proxy isn't really helpful.

This is how I fixed the problem in my case. Hopefully, might be helpful for anyone with a similar setup.

  1. Add the ModHeader extension to the chrome browser

How to download the Modheader? Link

ChromeOptions options = new ChromeOptions();
options.addExtensions(new File(C://Downloads//modheader//modheader.crx));

// Set the Desired capabilities 
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(ChromeOptions.CAPABILITY, options);

// Instantiate the chrome driver with capabilities
WebDriver driver = new RemoteWebDriver(new URL(YOUR_HUB_URL), options);
  1. Go to the browser extensions and capture the Local Storage context ID of the ModHeader

Capture ID from ModHeader

  1. Navigate to the URL of the ModHeader to set the Local Storage Context

.

// set the context on the extension so the localStorage can be accessed
driver.get("chrome-extension://idgpnmonknjnojddfkpgkljpfnnfcklj/_generated_background_page.html");

Where `idgpnmonknjnojddfkpgkljpfnnfcklj` is the value captured from the Step# 2
  1. Now add the headers to the request using Javascript

.

   ((Javascript)driver).executeScript(
         "localStorage.setItem('profiles', JSON.stringify([{  title: 'Selenium', hideComment: true, appendMode: '', 
             headers: [                        
               {enabled: true, name: 'token-1', value: 'value-1', comment: ''},
               {enabled: true, name: 'token-2', value: 'value-2', comment: ''}
             ],                          
             respHeaders: [],
             filters: []
          }]));");

Where token-1, value-1, token-2, value-2 are the request headers and values that are to be added.

  1. Now navigate to the required web-application.

    driver.get("your-desired-website");

PHP Fatal error: Uncaught exception 'Exception'

Just adding a bit of extra information here in case someone has the same issue as me.

I use namespaces in my code and I had a class with a function that throws an Exception.

However my try/catch code in another class file was completely ignored and the normal PHP error for an uncatched exception was thrown.

Turned out I forgot to add "use \Exception;" at the top, adding that solved the error.

Can Mysql Split a column?

Use

substring_index(`column`,',',1) ==> first value
substring_index(substring_index(`column`,',',-2),',',1)=> second value
substring_index(substring_index(`column`,',',-1),',',1)=> third value

in your where clause.

SELECT * FROM `table`
WHERE 
substring_index(`column`,',',1)<0 
AND
substring_index(`column`,',',1)>5

Is there a simple way to convert C++ enum to string?

That's pretty much the only way it can be done (an array of string could work also).

The problem is, once a C program is compiled, the binary value of the enum is all that is used, and the name is gone.

Using NSLog for debugging

type : BOOL DATA (YES/NO) OR(1/0)

BOOL dtBool = 0; 

OR

BOOL dtBool = NO;
NSLog(dtBool ? @"Yes" : @"No");

OUTPUT : NO

type : Long

long aLong = 2015;
NSLog(@"Display Long: %ld”, aLong);

OUTPUT : Display Long: 2015

long long veryLong = 20152015;
NSLog(@"Display very Long: %lld", veryLong);

OUTPUT : Display very Long: 20152015

type : String

NSString *aString = @"A string";
NSLog(@"Display string: %@", aString);

OUTPUT : Display String: a String

type : Float

float aFloat = 5.34245;
NSLog(@"Display Float: %F", aFloat);

OUTPUT : isplay Float: 5.342450

type : Integer

int aInteger = 3;    
NSLog(@"Display Integer: %i", aInteger);

OUTPUT : Display Integer: 3

NSLog(@"\nDisplay String: %@ \n\n Display Float: %f \n\n Display Integer: %i", aString, aFloat, aInteger);

OUTPUT : String: a String

Display Float: 5.342450

Display Integer: 3

http://luterr.blogspot.sg/2015/04/example-code-nslog-console-commands-to.html

What is the maximum length of a URL in different browsers?

I wrote this test that keeps on adding 'a' to parameter until the browser fails

C# part:

[AcceptVerbs(HttpVerbs.Get)]
public ActionResult ParamTest(string x)
{
    ViewBag.TestLength = 0;
    if (!string.IsNullOrEmpty(x))
    {
        System.IO.File.WriteAllLines("c:/result.txt",
                       new[] {Request.UserAgent, x.Length.ToString()});
        ViewBag.TestLength = x.Length + 1;
    }

    return View();
}

View:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<script type="text/javascript">
    $(function() {
        var text = "a";
        for (var i = 0; i < parseInt(@ViewBag.TestLength)-1; i++) {
            text += "a";
        }

        document.location.href = "http://localhost:50766/Home/ParamTest?x=" + text;
    });
</script>

PART 1

On Chrome I got:

Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.130 Safari/537.36
2046

It then blew up with:

HTTP Error 404.15 - Not Found The request filtering module is configured to deny a request where the query string is too long.

Same on Internet Explorer 8 and Firefox

Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET4.0C; .NET4.0E)
2046

Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0
2046

PART 2

I went easy mode and added additional limits to IISExpress applicationhost.config and web.config setting maxQueryStringLength="32768".

Chrome failed with message 'Bad Request - Request Too Long

HTTP Error 400. The size of the request headers is too long.

after 7744 characters.

Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.130 Safari/537.36
7744

PART 3

Added

<headerLimits>
    <add header="Content-type" sizeLimit="32768" />
</headerLimits>

which didn't help at all. I finally decided to use fiddler to remove the referrer from header.

static function OnBeforeRequest(oSession: Session) {
    if (oSession.url.Contains("localhost:50766")) {
        oSession.RequestHeaders.Remove("Referer");
    }

Which did nicely.

Chrome: got to 15613 characters. (I guess it's a 16K limit for IIS)

And it failed again with:

<BODY><h2>Bad Request - Request Too Long</h2>
<hr><p>HTTP Error 400. The size of the request headers is too long.</p>


Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.130 Safari/537.36
15613

Firefox:

Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0
15708

Internet Explorer 8 failed with iexplore.exe crashing.

Enter image description here

After 2505

Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET4.0C; .NET4.0E)
2505

Android Emulator

Mozilla/5.0 (Linux; Android 5.1; Android SDK built for x86 Build/LKY45) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/39.0.0.0 Mobile Safari/537.36
7377

Internet Explorer 11

Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C)
4043

Internet Explorer 10

Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/6.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C)
4043

Internet Explorer 9

Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)
4043

How do I return an int from EditText? (Android)

You can do this in 2 steps:

1: Change the input type(In your EditText field) in the layout file to android:inputType="number"

2: Use int a = Integer.parseInt(yourEditTextObject.getText().toString());

Could not load file or assembly '' or one of its dependencies

I kept getting this error on my web forms project in visual studio 2015. I shutdown Visual Studio and I killed the ScriptedSandbox64.exe, Microsoft.VsHub.Server.HttpHostx64.exe, Microsoft.VsHub.Server.HttpHostx.exe *32, Microsoft.VisualStudio.Web.Host.exe *32 processes and it seemed to help fix the issue.

How can I pass an Integer class correctly by reference?

I think it is the autoboxing that is throwing you off.

This part of your code:

   public static Integer inc(Integer i) {
        i = i+1;    // I think that this must be **sneakally** creating a new integer...  
        System.out.println("Inc: "+i);
        return i;
    }

Really boils down to code that looks like:

  public static Integer inc(Integer i) {
        i = new Integer(i) + new Integer(1);      
        System.out.println("Inc: "+i);
        return i;
    }

Which of course.. will not changes the reference passed in.

You could fix it with something like this

  public static void main(String[] args) {
        Integer integer = new Integer(0);
        for (int i =0; i<10; i++){
            integer = inc(integer);
            System.out.println("main: "+integer);
        }
    }

Get startup type of Windows service using PowerShell

As far as I know there is no “native” PowerShell way of getting this information. And perhaps it is rather the .NET limitation than PowerShell.

Here is the suggestion to add this functionality to the version next:

https://connect.microsoft.com/PowerShell/feedback/details/424948/i-would-like-to-see-the-property-starttype-added-to-get-services

The WMI workaround is also there, just in case. I use this WMI solution for my tasks and it works.

Submit form without reloading page

You can't do this using forms the normal way. Instead, you want to use AJAX.

A sample function that will submit the data and alert the page response.

function submitForm() {
    var http = new XMLHttpRequest();
    http.open("POST", "<<whereverTheFormIsGoing>>", true);
    http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    var params = "search=" + <<get search value>>; // probably use document.getElementById(...).value
    http.send(params);
    http.onload = function() {
        alert(http.responseText);
    }
}

Java : How to determine the correct charset encoding of a stream

An alternative to TikaEncodingDetector is to use Tika AutoDetectReader.

Charset charset = new AutoDetectReader(new FileInputStream(file)).getCharset();

Explanation of 'String args[]' and static in 'public static void main(String[] args)'

To keep beginner attitude you can explain that all the command line is automaticaly splite in a array fo String (the String[]).

For static you have to explain, that it not a field like another : it is unique in the JVM even if you have thousand instances of the class

So main is static, because it is the only way to find it (linked in its own class) in a jar.

... after you look at coding, and your job begin ...

ASP.NET MVC Global Variables

public static class GlobalVariables
{
    // readonly variable
    public static string Foo
    {
        get
        {
            return "foo";
        }
    }

    // read-write variable
    public static string Bar
    {
        get
        {
            return HttpContext.Current.Application["Bar"] as string;
        }
        set
        {
            HttpContext.Current.Application["Bar"] = value;
        }
    }
}

Change button background color using swift language

You can set the background color of a button using the getRed function.
Let's assume you have:

  1. A UIButton called button, and
  2. You want to change button's background color to some known RBG value

Then, place the following code in the function where you want to change the background color of your UIButton

var r:CGFloat = 0
var g:CGFloat = 0
var b:CGFloat = 0
var a:CGFloat = 0

// This will be some red-ish color
let color = UIColor(red: 200.0/255.0, green: 16.0/255.0, blue: 46.0/255.0, alpha: 1.0) 

if color.getRed(&r, green: &g, blue: &b, alpha: &a){
    button.backgroundColor = UIColor(red: r, green: g, blue: b, alpha: a)
}

.NET DateTime to SqlDateTime Conversion

Also please remember resolutions [quantum of time] are different.

http://msdn.microsoft.com/en-us/library/system.data.sqltypes.sqldatetime.aspx

SQL one is 3.33 ms and .net one is 100 ns.

How to link 2 cell of excel sheet?

The simplest solution is to select the second cell, and press =. This will begin the fomula creation process. Now either type in the 1st cell reference (eg, A1) or click on the first cell and press enter. This should make the second cell reference the value of the first cell.

To read up more on different options for referencing see - This Article.

How to parse a JSON and turn its values into an Array?

for your example:

{'profiles': [{'name':'john', 'age': 44}, {'name':'Alex','age':11}]}

you will have to do something of this effect:

JSONObject myjson = new JSONObject(the_json);
JSONArray the_json_array = myjson.getJSONArray("profiles");

this returns the array object.

Then iterating will be as follows:

    int size = the_json_array.length();
    ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
    for (int i = 0; i < size; i++) {
        JSONObject another_json_object = the_json_array.getJSONObject(i);
            //Blah blah blah...
            arrays.add(another_json_object);
    }

//Finally
JSONObject[] jsons = new JSONObject[arrays.size()];
arrays.toArray(jsons);

//The end...

You will have to determine if the data is an array (simply checking that charAt(0) starts with [ character).

Hope this helps.

In Java 8 how do I transform a Map<K,V> to another Map<K,V> using a lambda?

If you don't mind using 3rd party libraries, my cyclops-react lib has extensions for all JDK Collection types, including Map. You can directly use the map or bimap methods to transform your Map. A MapX can be constructed from an existing Map eg.

  MapX<String, Column> y = MapX.fromMap(orgColumnMap)
                               .map(c->new Column(c.getValue());

If you also wish to change the key you can write

  MapX<String, Column> y = MapX.fromMap(orgColumnMap)
                               .bimap(this::newKey,c->new Column(c.getValue());

bimap can be used to transform the keys and values at the same time.

As MapX extends Map the generated map can also be defined as

  Map<String, Column> y

enum - getting value of enum on string conversion

You are printing the enum object. Use the .value attribute if you wanted just to print that:

print(D.x.value)

See the Programmatic access to enumeration members and their attributes section:

If you have an enum member and need its name or value:

>>>
>>> member = Color.red
>>> member.name
'red'
>>> member.value
1

You could add a __str__ method to your enum, if all you wanted was to provide a custom string representation:

class D(Enum):
    def __str__(self):
        return str(self.value)

    x = 1
    y = 2

Demo:

>>> from enum import Enum
>>> class D(Enum):
...     def __str__(self):
...         return str(self.value)
...     x = 1
...     y = 2
... 
>>> D.x
<D.x: 1>
>>> print(D.x)
1

jQuery if statement to check visibility

 $('#column-left form').hide();
 $('.show-search').click(function() {
    $('#column-left form').stop(true, true).slideToggle(300); //this will slide but not hide that's why
    $('#column-left form').hide(); 
    if(!($('#column-left form').is(":visible"))) {
        $("#offers").show();
    } else {
        $('#offers').hide();
    }
  });

Check if a given key already exists in a dictionary

Sharing one more way of checking if a key exists using boolean operators.

d = {'a': 1, 'b':2}
keys = 'abcd'

for k in keys:
    x = (k in d and 'blah') or 'boo'
    print(x) 

This returns

>>> blah
>>> blah
>>> boo
>>> boo

Explanation

First you should know that in Python, 0, None, or objects with zero length evaluate to False. Everything else evaluates to True. Boolean operations are evaluated left to right and return the operand not True or False.

Let's see an example:

>>> 'Some string' or 1/0 
'Some string'
>>>

Since 'Some string' evaluates to True, the rest of the or is not evaluated and there is no division by zero error raised.

But if we switch the order 1/0 is evaluated first and raises an exception:

>>> 1/0 or 'Some string'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>> 

We can use this for pattern for checking if a key exists.

(k in d and 'blah')

does the same as

if k in d:
    'blah'
else:
    False

This already returns the correct result if the key exists, but we want it to print 'boo' when it doesn't. So, we take the result and or it with 'boo'

>>> False or 'boo'
'boo'
>>> 'blah' or 'boo'
'blah'
>>> 

Adding a collaborator to my free GitHub account?

In the repository, click Admin, then go to the Collaborators tab.

Mismatched anonymous define() module

The existing answers explain the problem well but if including your script files using or before requireJS is not an easy option due to legacy code a slightly hacky workaround is to remove require from the window scope before your script tag and then reinstate it afterwords. In our project this is wrapped behind a server-side function call but effectively the browser sees the following:

    <script>
        window.__define = window.define;
        window.__require = window.require;
        window.define = undefined;
        window.require = undefined;
    </script>
    <script src="your-script-file.js"></script>        
    <script>
        window.define = window.__define;
        window.require = window.__require;
        window.__define = undefined;
        window.__require = undefined;
    </script>

Not the neatest but seems to work and has saved a lot of refractoring.

How to insert new row to database with AUTO_INCREMENT column without specifying column names?

Just add the column names, yes you can use Null instead but is is a very bad idea to not use column names in any insert, ever.

'negative' pattern matching in python

 if not (line.startswith("OK ") or line.strip() == "."):
     print line

Prevent row names to be written to file when using write.csv

For completeness, write_csv() from the readr package is faster and never writes row names

# install.packages('readr', dependencies = TRUE)
library(readr)
write_csv(t, "t.csv")

If you need to write big data out, use fwrite() from the data.table package. It's much faster than both write.csv and write_csv

# install.packages('data.table')
library(data.table)
fwrite(t, "t.csv")

Below is a benchmark that Edouard published on his site

microbenchmark(write.csv(data, "baseR_file.csv", row.names = F),
               write_csv(data, "readr_file.csv"),
               fwrite(data, "datatable_file.csv"),
               times = 10, unit = "s")

## Unit: seconds
##                                              expr        min         lq       mean     median         uq        max neval
##  write.csv(data, "baseR_file.csv", row.names = F) 13.8066424 13.8248250 13.9118324 13.8776993 13.9269675 14.3241311    10
##                 write_csv(data, "readr_file.csv")  3.6742610  3.7999409  3.8572456  3.8690681  3.8991995  4.0637453    10
##                fwrite(data, "datatable_file.csv")  0.3976728  0.4014872  0.4097876  0.4061506  0.4159007  0.4355469    10

Running EXE with parameters

ProcessStartInfo startInfo = new ProcessStartInfo(string.Concat(cPath, "\\", "HHTCtrlp.exe"));
startInfo.Arguments =cParams;
startInfo.UseShellExecute = false; 
System.Diagnostics.Process.Start(startInfo);

Calling a JavaScript function returned from an Ajax response

That seems a rather weird design for your code - it generally makes more sense to have your functions called directly from a .js file, and then only retrieve data with the Ajax call.

However, I believe it should work by calling eval() on the response - provided it is syntactically correct JavaScript code.

Using CSS td width absolute, position

Use table-layout property and the "fixed" value on your table.

table {
   table-layout: fixed;
   width: 300px; /* your desired width */
}

After setting up the entire width of the table, you can now setup the width in % of the td's.

td:nth-child(1), td:nth-child(2) {
   width: 15%;  
}

You can learn more about in on this link: http://www.w3schools.com/cssref/pr_tab_table-layout.asp

Run script with rc.local: script works, but not at boot

first make the script executable using sudo chmod 755 /path/of/the/file.sh now add the script in the rc.local sh /path/of/the/file.sh before exit 0 in the rc.local, next make the rc.local to executable with sudo chmod 755 /etc/rc.local next to initialize the rc.local use sudo /etc/init.d/rc.local start this will initiate the rc.local now reboot the system. Done..

python pandas remove duplicate columns

First step:- Read first row i.e all columns the remove all duplicate columns.

Second step:- Finally read only that columns.

cols = pd.read_csv("file.csv", header=None, nrows=1).iloc[0].drop_duplicates()
df = pd.read_csv("file.csv", usecols=cols)

What is the default stack size, can it grow, how does it work with garbage collection?

As you say, local variables and references are stored on the stack. When a method returns, the stack pointer is simply moved back to where it was before the method started, that is, all local data is "removed from the stack". Therefore, there is no garbage collection needed on the stack, that only happens in the heap.

To answer your specific questions:

  • See this question on how to increase the stack size.
  • You can limit the stack growth by:
    • grouping many local variables in an object: that object will be stored in the heap and only the reference is stored on the stack
    • limit the number of nested function calls (typically by not using recursion)
  • For windows, the default stack size is 320k for 32bit and 1024k for 64bit, see this link.

AngularJS ng-if with multiple conditions

Sure you can. Something like:

HTML

<div ng-controller="fessCntrl">    
     <label ng-repeat="(key,val) in list">
       <input type="radio" name="localityTypeRadio" ng-model="$parent.localityTypeRadio" ng-value="key" />{{key}}
         <div ng-if="key == 'City' || key == 'County'">
             <pre>City or County !!! {{$parent.localityTypeRadio}}</pre>
         </div>
         <div ng-if="key == 'Town'">
             <pre>Town!!! {{$parent.localityTypeRadio}}</pre>
         </div>        
      </label>
</div>

JS

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

fessmodule.controller('fessCntrl', function ($scope) {

    $scope.list = {
        City: [{name: "cityA"}, {name: "cityB"}],
        County: [{ name: "countyA"}, {name: "countyB"}],
        Town: [{ name: "townA"}, {name: "townB"}]
      };

    $scope.localityTypeRadio = 'City';
});

fessmodule.$inject = ['$scope'];

Demo Fiddle

How can I fix "Design editor is unavailable until a successful build" error?

Go online before starting android studio. Then go file->New project Follow onscreen steps. Then wait It will download the necessary files over internet. And that should fix it.

How to get the root dir of the Symfony2 application?

Since Symfony 3.3 you can use binding, like

services:
_defaults:
    autowire: true      
    autoconfigure: true
    bind:
        $kernelProjectDir: '%kernel.project_dir%'

After that you can use parameter $kernelProjectDir in any controller OR service. Just like

class SomeControllerOrService
{
    public function someAction(...., $kernelProjectDir)
    {
          .....

Highlight a word with jQuery

Why using a selfmade highlighting function is a bad idea

The reason why it's probably a bad idea to start building your own highlighting function from scratch is because you will certainly run into issues that others have already solved. Challenges:

  • You would need to remove text nodes with HTML elements to highlight your matches without destroying DOM events and triggering DOM regeneration over and over again (which would be the case with e.g. innerHTML)
  • If you want to remove highlighted elements you would have to remove HTML elements with their content and also have to combine the splitted text-nodes for further searches. This is necessary because every highlighter plugin searches inside text nodes for matches and if your keywords will be splitted into several text nodes they will not being found.
  • You would also need to build tests to make sure your plugin works in situations which you have not thought about. And I'm talking about cross-browser tests!

Sounds complicated? If you want some features like ignoring some elements from highlighting, diacritics mapping, synonyms mapping, search inside iframes, separated word search, etc. this becomes more and more complicated.

Use an existing plugin

When using an existing, well implemented plugin, you don't have to worry about above named things. The article 10 jQuery text highlighter plugins on Sitepoint compares popular highlighter plugins. This includes plugins of answers from this question.

Have a look at mark.js

mark.js is such a plugin that is written in pure JavaScript, but is also available as jQuery plugin. It was developed to offer more opportunities than the other plugins with options to:

  • search for keywords separately instead of the complete term
  • map diacritics (For example if "justo" should also match "justò")
  • ignore matches inside custom elements
  • use custom highlighting element
  • use custom highlighting class
  • map custom synonyms
  • search also inside iframes
  • receive not found terms

DEMO

Alternatively you can see this fiddle.

Usage example:

// Highlight "keyword" in the specified context
$(".context").mark("keyword");

// Highlight the custom regular expression in the specified context
$(".context").markRegExp(/Lorem/gmi);

It's free and developed open-source on GitHub (project reference).

How to view changes made to files on a certain revision in Subversion

With this command you will see all changes in the repository path/to/repo that were committed in revision <revision>:

svn diff -c <revision> path/to/repo

The -c indicates that you would like to look at a changeset, but there are many other ways you can look at diffs and changesets. For example, if you would like to know which files were changed (but not how), you can issue

svn log -v -r <revision>

Or, if you would like to show at the changes between two revisions (and not just for one commit):

svn diff -r <revA>:<revB> path/to/repo

Convert Rows to columns using 'Pivot' in SQL Server

I've achieved the same thing before by using subqueries. So if your original table was called StoreCountsByWeek, and you had a separate table that listed the Store IDs, then it would look like this:

SELECT StoreID, 
    Week1=(SELECT ISNULL(SUM(xCount),0) FROM StoreCountsByWeek WHERE StoreCountsByWeek.StoreID=Store.StoreID AND Week=1),
    Week2=(SELECT ISNULL(SUM(xCount),0) FROM StoreCountsByWeek WHERE StoreCountsByWeek.StoreID=Store.StoreID AND Week=2),
    Week3=(SELECT ISNULL(SUM(xCount),0) FROM StoreCountsByWeek WHERE StoreCountsByWeek.StoreID=Store.StoreID AND Week=3)
FROM Store
ORDER BY StoreID

One advantage to this method is that the syntax is more clear and it makes it easier to join to other tables to pull other fields into the results too.

My anecdotal results are that running this query over a couple of thousand rows completed in less than one second, and I actually had 7 subqueries. But as noted in the comments, it is more computationally expensive to do it this way, so be careful about using this method if you expect it to run on large amounts of data .

How to remove Firefox's dotted outline on BUTTONS as well as links?

Yep don't miss !important

button::-moz-focus-inner {
 border: 0 !important;
}

Error 80040154 (Class not registered exception) when initializing VCProjectEngineObject (Microsoft.VisualStudio.VCProjectEngine.dll)

There are not many good reasons this would fail, especially the regsvr32 step. Run dumpbin /exports on that dll. If you don't see DllRegisterServer then you've got a corrupt install. It should have more side-effects, you wouldn't be able to build C/C++ projects anymore.

One standard failure mode is running this on a 64-bit operating system. This is 32-bit unmanaged code, you would indeed get the 'class not registered' exception. Project + Properties, Build tab, change Platform Target to x86.

SVN repository backup strategies

You could use something like (Linux):

svnadmin dump repositorypath | gzip > backupname.svn.gz

Since Windows does not support GZip it is just:

svnadmin dump repositorypath > backupname.svn

Where does R store packages?

You do not want the '='

Use .libPaths("C:/R/library") in you Rprofile.site file

And make sure you have correct " symbol (Shift-2)

Pandas KeyError: value not in index

please try this to clean and format your column names:

df.columns = (df.columns.str.strip().str.upper()
              .str.replace(' ', '_')
              .str.replace('(', '')
              .str.replace(')', ''))

[Ljava.lang.Object; cannot be cast to

You need to add query.addEntity(SwitcherServiceSource.class) before calling the .list() on query.

Selecting one row from MySQL using mysql_* API

Ultimately, I want to be able to echo out a signle field like so:

   $row['option_value']

So why don't you? It should work.

Where to place JavaScript in an HTML file?

Putting the javascript at the top would seem neater, but functionally, its better to go after the HTML. That way, your javascript won't run and try to reference HTML elements before they are loaded. This sort of problem often only becomes apparent when you load the page over an actual internet connection, especially a slow one.

You could also try to dynamically load the javascript by adding a header element from other javascript code, although that only makes sense if you aren't using all of the code all the time.

Jquery UI tooltip does not support html content

another solution will be to grab the text inside the title tag & then use .html() method of jQuery to construct the content of the tooltip.

$(function() {
  $(document).tooltip({
    position: {
      using: function(position, feedback) {
        $(this).css(position);
        var txt = $(this).text();
        $(this).html(txt);
        $("<div>")
          .addClass("arrow")
          .addClass(feedback.vertical)
          .addClass(feedback.horizontal)
          .appendTo(this);
      }
    }
  });
});

Example: http://jsfiddle.net/hamzeen/0qwxfgjo/

Converting a PDF to PNG

Out of all the available alternatives I found Inkscape to produce the most accurate results when converting PDFs to PNG. Especially when the source file had transparent layers, Inkscape succeeded where Imagemagick and other tools failed.

This is the command I use:

inkscape "$pdf" -z --export-dpi=600 --export-area-drawing --export-png="$pngfile"

And here it is implemented in a script:

#!/bin/bash

while [ $# -gt 0 ]; do

pdf=$1
echo "Converting "$pdf" ..."
pngfile=`echo "$pdf" | sed 's/\.\w*$/.png/'`
inkscape "$pdf" -z --export-dpi=600 --export-area-drawing --export-png="$pngfile"
echo "Converted to "$pngfile""
shift

done

echo "All jobs done. Exiting."

Run a script in Dockerfile

It's best practice to use COPY instead of ADD when you're copying from the local file system to the image. Also, I'd recommend creating a sub-folder to place your content into. If nothing else, it keeps things tidy. Make sure you mark the script as executable using chmod.

Here, I am creating a scripts sub-folder to place my script into and run it from:

RUN mkdir -p /scripts
COPY script.sh /scripts
WORKDIR /scripts
RUN chmod +x script.sh
RUN script.sh

app-release-unsigned.apk is not signed

If anyone wants to debug and release separate build variant using Android Studio 3.5, follow the below steps: 1. Set build variant to release mode.

Build Variant

  1. Go to File >> Project Structure
  2. Select Modules, then Signing Config
  3. Click in the Plus icon under Signing Config

Signing Config

  1. Select release section and Provide your release App Information then Apply and OK.

signin

  1. Go to your app level build.gradle and change your buildTypes > "release" section like below Screenshot.

final

Then Run your Project. Happy Coding.

Get the date (a day before current time) in Bash

If you have BSD (OSX) date you can do it like this:

date -j -v-1d
Wed Dec 14 15:34:14 CET 2011

Or if you want to do date calculations on an arbitrary date:

date -j -v-1d -f "%Y-%m-%d" "2011-09-01" "+%Y-%m-%d"
2011-08-31

Call a VBA Function into a Sub Procedure

Calling a Sub Procedure – 3 Way technique

Once you have a procedure, whether you created it or it is part of the Visual Basic language, you can use it. Using a procedure is also referred to as calling it.

Before calling a procedure, you should first locate the section of code in which you want to use it. To call a simple procedure, type its name. Here is an example:

Sub CreateCustomer()
    Dim strFullName As String

    strFullName = "Paul Bertrand Yamaguchi"

msgbox strFullName
End Sub

Sub Exercise()
    CreateCustomer
End Sub

Besides using the name of a procedure to call it, you can also precede it with the Call keyword. Here is an example:

Sub CreateCustomer()
    Dim strFullName As String

    strFullName = "Paul Bertrand Yamaguchi"
End Sub

Sub Exercise()
    Call CreateCustomer
End Sub

When calling a procedure, without or without the Call keyword, you can optionally type an opening and a closing parentheses on the right side of its name. Here is an example:

Sub CreateCustomer()
    Dim strFullName As String

    strFullName = "Paul Bertrand Yamaguchi"
End Sub

Sub Exercise()
    CreateCustomer()
End Sub

Procedures and Access Levels

Like a variable access, the access to a procedure can be controlled by an access level. A procedure can be made private or public. To specify the access level of a procedure, precede it with the Private or the Public keyword. Here is an example:

Private Sub CreateCustomer()
    Dim strFullName As String

    strFullName = "Paul Bertrand Yamaguchi"
End Sub

The rules that were applied to global variables are the same:

Private: If a procedure is made private, it can be called by other procedures of the same module. Procedures of outside modules cannot access such a procedure.

Also, when a procedure is private, its name does not appear in the Macros dialog box

Public: A procedure created as public can be called by procedures of the same module and by procedures of other modules.

Also, if a procedure was created as public, when you access the Macros dialog box, its name appears and you can run it from there

Linq to Entities join vs groupjoin

According to eduLINQ:

The best way to get to grips with what GroupJoin does is to think of Join. There, the overall idea was that we looked through the "outer" input sequence, found all the matching items from the "inner" sequence (based on a key projection on each sequence) and then yielded pairs of matching elements. GroupJoin is similar, except that instead of yielding pairs of elements, it yields a single result for each "outer" item based on that item and the sequence of matching "inner" items.

The only difference is in return statement:

Join:

var lookup = inner.ToLookup(innerKeySelector, comparer); 
foreach (var outerElement in outer) 
{ 
    var key = outerKeySelector(outerElement); 
    foreach (var innerElement in lookup[key]) 
    { 
        yield return resultSelector(outerElement, innerElement); 
    } 
} 

GroupJoin:

var lookup = inner.ToLookup(innerKeySelector, comparer); 
foreach (var outerElement in outer) 
{ 
    var key = outerKeySelector(outerElement); 
    yield return resultSelector(outerElement, lookup[key]); 
} 

Read more here:

How to "EXPIRE" the "HSET" child key in redis?

This is not possible, for the sake of keeping Redis simple.

Quoth Antirez, creator of Redis:

Hi, it is not possible, either use a different top-level key for that specific field, or store along with the filed another field with an expire time, fetch both, and let the application understand if it is still valid or not based on current time.

Escape a string for a sed replace pattern

These are the escape codes that I've found:

* = \x2a
( = \x28
) = \x29

" = \x22
/ = \x2f
\ = \x5c

' = \x27
? = \x3f
% = \x25
^ = \x5e

Where do I find some good examples for DDD?

.NET DDD Sample from Domain-Driven Design Book by Eric Evans can be found here: http://dddsamplenet.codeplex.com

Cheers,

Jakub G

How to print from Flask @app.route to python console

We can also use logging to print data on the console.

Example:

import logging
from flask import Flask

app = Flask(__name__)

@app.route('/print')
def printMsg():
    app.logger.warning('testing warning log')
    app.logger.error('testing error log')
    app.logger.info('testing info log')
    return "Check your console"

if __name__ == '__main__':
    app.run(debug=True)

Output first 100 characters in a string

String formatting using % is a great way to handle this. Here are some examples.

The formatting code '%s' converts '12345' to a string, but it's already a string.

>>> '%s' % '12345'

'12345'

'%.3s' specifies to use only the first three characters.

>>> '%.3s' % '12345'

'123'

'%.7s' says to use the first seven characters, but there are only five. No problem.

>>> '%.7s' % '12345'

'12345'

'%7s' uses up to seven characters, filling missing characters with spaces on the left.

>>> '%7s' % '12345'

'  12345'

'%-7s' is the same thing, except filling missing characters on the right.

>>> '%-7s' % '12345'

'12345  '

'%5.3' says use the first three characters, but fill it with spaces on the left to total five characters.

>>> '%5.3s' % '12345'

'  123'

Same thing except filling on the right.

>>> '%-5.3s' % '12345'

'123  '

Can handle multiple arguments too!

>>> 'do u no %-4.3sda%3.2s wae' % ('12345', 6789)

'do u no 123 da 67 wae'

If you require even more flexibility, str.format() is available too. Here is documentation for both.

How do I verify that a string only contains letters, numbers, underscores and dashes?

You could always use a list comprehension and check the results with all, it would be a little less resource intensive than using a regex: all([c in string.letters + string.digits + ["_", "-"] for c in mystring])

How do I filter an array with AngularJS and use a property of the filtered object as the ng-model attribute?

if you wanted to create a separate list of results in the controller you could apply a filter

function MyCtrl($scope, filterFilter) {
  $scope.results = {
    year:2013,
    subjects:[
      {title:'English',grade:'A'},
      {title:'Maths',grade:'A'},
      {title:'Science',grade:'B'},
      {title:'Geography',grade:'C'}
    ]
  };
  //create a filtered array of results 
  //with grade 'C' or subjects that have been failed
  $scope.failedSubjects = filterFilter($scope.results.subjects, {'grade':'C'});
}

Then you can reference failedSubjects the same way you would reference the results object

you can read more about it here https://docs.angularjs.org/guide/filter

since this answer angular have updated the documentation they now recommend calling the filter

// update 
// eg: $filter('filter')(array, expression, comparator, anyPropertyKey);
// becomes
$scope.failedSubjects = $filter('filter')($scope.results.subjects, {'grade':'C'});

How to only find files in a given directory, and ignore subdirectories using bash

Is there any particular reason that you need to use find? You can just use ls to find files that match a pattern in a directory.

ls /dev/abc-*

If you do need to use find, you can use the -maxdepth 1 switch to only apply to the specified directory.

Remove characters from a string

You can use replace function.

str.replace(regexp|substr, newSubstr|function)

C# how to wait for a webpage to finish loading before continuing

This code was very helpful for me. Maybe it could be for you also

wb.Navigate(url);
while(wb.ReadyState != WebBrowserReadyState.Complete)
{
     Application.DoEvents();
}
MessageBox.Show("Loaded");

Export Postgresql table data using pgAdmin

In the pgAdmin4, Right click on table select backup like this

enter image description here

After that into the backup dialog there is Dump options tab into that there is section queries you can select Use Insert Commands which include all insert queries as well in the backup.

enter image description here

Jquery check if element is visible in viewport

var visible = $(".media").visible();

Laravel 4 with Sentry 2 add user to a group on Registration

Somehow, where you are using Sentry, you're not using its Facade, but the class itself. When you call a class through a Facade you're not really using statics, it's just looks like you are.

Do you have this:

use Cartalyst\Sentry\Sentry; 

In your code?

Ok, but if this line is working for you:

$user = $this->sentry->register(array(     'username' => e($data['username']),     'email' => e($data['email']),      'password' => e($data['password'])     )); 

So you already have it instantiated and you can surely do:

$adminGroup = $this->sentry->findGroupById(5); 

How to clear/delete the contents of a Tkinter Text widget?

from Tkinter import *

app = Tk()

# Text Widget + Font Size
txt = Text(app, font=('Verdana',8))
txt.pack()

# Delete Button
btn = Button(app, text='Delete', command=lambda: txt.delete(1.0,END))
btn.pack()

app.mainloop()

Here's an example of txt.delete(1.0,END) as mentioned.

The use of lambda makes us able to delete the contents without defining an actual function.

Are members of a C++ struct initialized to 0 by default?

In C++, use no-argument constructors. In C you can't have constructors, so use either memset or - the interesting solution - designated initializers:

struct Snapshot s = { .x = 0.0, .y = 0.0 };

how to get file path from sd card in android

As some people indicated, the officially accepted answer does not quite return the external removable SD card. And i ran upon the following thread that proposes a method I've tested on some Android devices and seems to work reliably, so i thought of re-sharing here as i don't see it in the other responses:

http://forums.androidcentral.com/samsung-galaxy-s7/668364-whats-external-sdcard-path.html

Kudos to paresh996 for coming up with the answer itself, and i can attest I've tried on Samsung S7 and S7edge and seems to work.

Now, i needed a method that returned a valid path where to read files, and that considered the fact that there might not be an external SD, in which case the internal storage should be returned, so i modified the code from paresh996 to this :

File getStoragePath() {
    String removableStoragePath;
    File fileList[] = new File("/storage/").listFiles();
    for (File file : fileList) {
       if(!file.getAbsolutePath().equalsIgnoreCase(Environment.getExternalStorageDirectory().getAbsolutePath()) && file.isDirectory() && file.canRead()) {
            return file;
        }
    }
    return Environment.getExternalStorageDirectory();
}

How to create checkbox inside dropdown?

Here is a simple dropdown checklist:

_x000D_
_x000D_
var checkList = document.getElementById('list1');
checkList.getElementsByClassName('anchor')[0].onclick = function(evt) {
  if (checkList.classList.contains('visible'))
    checkList.classList.remove('visible');
  else
    checkList.classList.add('visible');
}
_x000D_
.dropdown-check-list {
  display: inline-block;
}

.dropdown-check-list .anchor {
  position: relative;
  cursor: pointer;
  display: inline-block;
  padding: 5px 50px 5px 10px;
  border: 1px solid #ccc;
}

.dropdown-check-list .anchor:after {
  position: absolute;
  content: "";
  border-left: 2px solid black;
  border-top: 2px solid black;
  padding: 5px;
  right: 10px;
  top: 20%;
  -moz-transform: rotate(-135deg);
  -ms-transform: rotate(-135deg);
  -o-transform: rotate(-135deg);
  -webkit-transform: rotate(-135deg);
  transform: rotate(-135deg);
}

.dropdown-check-list .anchor:active:after {
  right: 8px;
  top: 21%;
}

.dropdown-check-list ul.items {
  padding: 2px;
  display: none;
  margin: 0;
  border: 1px solid #ccc;
  border-top: none;
}

.dropdown-check-list ul.items li {
  list-style: none;
}

.dropdown-check-list.visible .anchor {
  color: #0094ff;
}

.dropdown-check-list.visible .items {
  display: block;
}
_x000D_
<div id="list1" class="dropdown-check-list" tabindex="100">
  <span class="anchor">Select Fruits</span>
  <ul class="items">
    <li><input type="checkbox" />Apple </li>
    <li><input type="checkbox" />Orange</li>
    <li><input type="checkbox" />Grapes </li>
    <li><input type="checkbox" />Berry </li>
    <li><input type="checkbox" />Mango </li>
    <li><input type="checkbox" />Banana </li>
    <li><input type="checkbox" />Tomato</li>
  </ul>
</div>
_x000D_
_x000D_
_x000D_

How to make a radio button unchecked by clicking it?

I came here because I had the same issue. I wanted to present the options to the user while leaving the option of remaining empty. Although this is possible to explicitly code using checkboxes that would complicate the back end.

Having the user Control+click is almost as good as having them uncheck it through the console. Catching the mousedown is to early and onclick is too late.

Well, at last here is a solution! Just put these few lines once on the page and you have it made for all radio buttons on the page. You can even fiddle with the selector to customize it.

_x000D_
_x000D_
window.onload = function() {_x000D_
  document.querySelectorAll("INPUT[type='radio']").forEach(function(rd) {_x000D_
    rd.addEventListener("mousedown", function() {_x000D_
      if(this.checked) {_x000D_
        this.onclick=function() {_x000D_
          this.checked=false_x000D_
        }_x000D_
      } else {_x000D_
        this.onclick=null_x000D_
      }_x000D_
    })_x000D_
  })_x000D_
}
_x000D_
<input type=radio name=unchecksample> Number One<br>_x000D_
<input type=radio name=unchecksample> Number Two<br>_x000D_
<input type=radio name=unchecksample> Number Three<br>_x000D_
<input type=radio name=unchecksample> Number Four<br>_x000D_
<input type=radio name=unchecksample> Number Five<br>
_x000D_
_x000D_
_x000D_

Failed to install Python Cryptography package with PIP and setup.py

I encountered a similar issue recently. In my case the versions of cffi and cryptography written in requirements.txt weren't compatible (cffi==1.8.9 and cryptography==1.9). I solved updating cffi with the last available version.

How to write character & in android strings.xml

It should be like this :

<string name="game_settings_dragNDropMove_checkBox">Move by Drag&amp;Drop</string>

How do I execute a command and get the output of the command within C++ using POSIX?

For Windows, popen also works, but it opens up a console window - which quickly flashes over your UI application. If you want to be a professional, it's better to disable this "flashing" (especially if the end-user can cancel it).

So here is my own version for Windows:

(This code is partially recombined from ideas written in The Code Project and MSDN samples.)

#include <windows.h>
#include <atlstr.h>
//
// Execute a command and get the results. (Only standard output)
//
CStringA ExecCmd(
    const wchar_t* cmd              // [in] command to execute
)
{
    CStringA strResult;
    HANDLE hPipeRead, hPipeWrite;

    SECURITY_ATTRIBUTES saAttr = {sizeof(SECURITY_ATTRIBUTES)};
    saAttr.bInheritHandle = TRUE; // Pipe handles are inherited by child process.
    saAttr.lpSecurityDescriptor = NULL;

    // Create a pipe to get results from child's stdout.
    if (!CreatePipe(&hPipeRead, &hPipeWrite, &saAttr, 0))
        return strResult;

    STARTUPINFOW si = {sizeof(STARTUPINFOW)};
    si.dwFlags     = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
    si.hStdOutput  = hPipeWrite;
    si.hStdError   = hPipeWrite;
    si.wShowWindow = SW_HIDE; // Prevents cmd window from flashing.
                              // Requires STARTF_USESHOWWINDOW in dwFlags.

    PROCESS_INFORMATION pi = { 0 };

    BOOL fSuccess = CreateProcessW(NULL, (LPWSTR)cmd, NULL, NULL, TRUE, CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi);
    if (! fSuccess)
    {
        CloseHandle(hPipeWrite);
        CloseHandle(hPipeRead);
        return strResult;
    }

    bool bProcessEnded = false;
    for (; !bProcessEnded ;)
    {
        // Give some timeslice (50 ms), so we won't waste 100% CPU.
        bProcessEnded = WaitForSingleObject( pi.hProcess, 50) == WAIT_OBJECT_0;

        // Even if process exited - we continue reading, if
        // there is some data available over pipe.
        for (;;)
        {
            char buf[1024];
            DWORD dwRead = 0;
            DWORD dwAvail = 0;

            if (!::PeekNamedPipe(hPipeRead, NULL, 0, NULL, &dwAvail, NULL))
                break;

            if (!dwAvail) // No data available, return
                break;

            if (!::ReadFile(hPipeRead, buf, min(sizeof(buf) - 1, dwAvail), &dwRead, NULL) || !dwRead)
                // Error, the child process might ended
                break;

            buf[dwRead] = 0;
            strResult += buf;
        }
    } //for

    CloseHandle(hPipeWrite);
    CloseHandle(hPipeRead);
    CloseHandle(pi.hProcess);
    CloseHandle(pi.hThread);
    return strResult;
} //ExecCmd

Get month and year from date cells Excel

Try this formula (it will return value from A1 as is if it's not a date):

=TEXT(A1,"mm-yyyy")

Or this formula (it's more strict, it will return #VALUE error if A1 is not date):

=TEXT(MONTH(A1),"00")&"-"&YEAR(A1)

org.json.simple cannot be resolved

try this

<!-- https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple -->
<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <version>1.1.1</version>
</dependency>

How can I set the default timezone in node.js?

The solution env TZ='Europe/Amsterdam' node server.js from @uhef works in cases where your app doesn't work with forked process, but when you are working with forked process, specially when you launch your app with a building tool like gulp , the command gulp will take the env values, but the process created by gulp not (your app).

To solve this, you have to do:

$ export TZ="Europe/Amsterdam"; gulp myTask

This will set the TZ environment variable for all the process started in the console you are working on, included all the subsequents process executed after the gulp command in the same console without the need to execute them with the prefix export TZ="Europe/Amsterdam"; again.

Change color of Label in C#

You can try this with Color.FromArgb:

Random rnd = new Random();
lbl.ForeColor = Color.FromArgb(rnd.Next(255), rnd.Next(255), rnd.Next(255));

Convert a String representation of a Dictionary to a dictionary?

https://docs.python.org/3.8/library/json.html

JSON can solve this problem though its decoder wants double quotes around keys and values. If you don't mind a replace hack...

import json
s = "{'muffin' : 'lolz', 'foo' : 'kitty'}"
json_acceptable_string = s.replace("'", "\"")
d = json.loads(json_acceptable_string)
# d = {u'muffin': u'lolz', u'foo': u'kitty'}

NOTE that if you have single quotes as a part of your keys or values this will fail due to improper character replacement. This solution is only recommended if you have a strong aversion to the eval solution.

More about json single quote: jQuery.parseJSON throws “Invalid JSON” error due to escaped single quote in JSON

Multi-dimensional associative arrays in JavaScript

Javascript is flexible:

var arr = {
  "fred": {"apple": 2, "orange": 4},
  "mary": {}
  //etc, etc
};

alert(arr.fred.orange);
alert(arr["fred"]["orange"]);
for (key in arr.fred)
    alert(key + ": " + arr.fred[key]);

Android set height and width of Custom view programmatically

On Kotlin you can set width and height of any view directly using their virtual properties:

someView.layoutParams.width = 100
someView.layoutParams.height = 200

How do I calculate the percentage of a number?

Divide $percentage by 100 and multiply to $totalWidth. Simple maths.

Mongoose.js: Find user by username LIKE value

For those that were looking for a solution here it is:

var name = 'Peter';
model.findOne({name: new RegExp('^'+name+'$', "i")}, function(err, doc) {
  //Do your action here..
});

Get webpage contents with Python?

Suppose you want to GET a webpage's content. The following code does it:

# -*- coding: utf-8 -*-
# python

# example of getting a web page

from urllib import urlopen
print urlopen("http://xahlee.info/python/python_index.html").read()

Explaining Apache ZooKeeper

Zookeeper is a centralized open-source server for maintaining and managing configuration information, naming conventions and synchronization for distributed cluster environment. Zookeeper helps the distributed systems to reduce their management complexity by providing low latency and high availability. Zookeeper was initially a sub-project for Hadoop but now it's a top level independent project of Apache Software Foundation.

More Information

Set scroll position

You can use window.scrollTo(), like this:

window.scrollTo(0, 0); // values are x,y-offset