Programs & Examples On #Axum

Axum is a domain specific concurrent programming language, based on the Actor model, being developed by Microsoft.

JavaScript - Get Portion of URL Path

window.location.href.split('/');

Will give you an array containing all the URL parts, which you can access like a normal array.

Or an ever more elegant solution suggested by @Dylan, with only the path parts:

window.location.pathname.split('/');

No value accessor for form control with name: 'recipient'

Make sure you import MaterialModule as well since you are using md-input which does not belong to FormsModule

How to use ternary operator in razor (specifically on HTML attributes)?

I have a field named IsActive in table rows that's True when an item has been deleted. This code applies a CSS class named strikethrough only to deleted items. You can see how it uses the C# Ternary Operator:

<tr class="@(@businesstypes.IsActive ? "" : "strikethrough")">

How to erase the file contents of text file in Python?

You cannot "erase" from a file in-place unless you need to erase the end. Either be content with an overwrite of an "empty" value, or read the parts of the file you care about and write it to another file.

What is the difference between 0.0.0.0, 127.0.0.1 and localhost?

In current version of Jekyll, it defaults to http://127.0.0.1:4000/.
This is good, if you are connected to a network but do not want anyone else to access your application.

However it may happen that you want to see how your application runs on a mobile or from some other laptop/computer.

In that case, you can use

jekyll serve --host 0.0.0.0

This binds your application to the host & next use following to connect to it from some other host

http://host's IP adress/4000 

Why is php not running?

One big gotcha is that PHP is disabled in user home directories by default, so if you are testing from ~/public_html it doesn't work. Check /etc/apache2/mods-enabled/php5.conf

# Running PHP scripts in user directories is disabled by default
# 
# To re-enable PHP in user directories comment the following lines
# (from <IfModule ...> to </IfModule>.) Do NOT set it to On as it
# prevents .htaccess files from disabling it.
#<IfModule mod_userdir.c>
#    <Directory /home/*/public_html>
#        php_admin_flag engine Off
#    </Directory>
#</IfModule>

Other than that installing in Ubuntu is real easy, as all the stuff you used to have to put in httpd.conf is done automatically.

How do I fix the error "Only one usage of each socket address (protocol/network address/port) is normally permitted"?

I faced similar problem on windows server 2012 STD 64 bit , my problem is resolved after updating windows with all available windows updates.

What's the difference between Perl's backticks, system, and exec?

In general I use system, open, IPC::Open2, or IPC::Open3 depending on what I want to do. The qx// operator, while simple, is too constraining in its functionality to be very useful outside of quick hacks. I find open to much handier.

system: run a command and wait for it to return

Use system when you want to run a command, don't care about its output, and don't want the Perl script to do anything until the command finishes.

#doesn't spawn a shell, arguments are passed as they are
system("command", "arg1", "arg2", "arg3");

or

#spawns a shell, arguments are interpreted by the shell, use only if you
#want the shell to do globbing (e.g. *.txt) for you or you want to redirect
#output
system("command arg1 arg2 arg3");

qx// or ``: run a command and capture its STDOUT

Use qx// when you want to run a command, capture what it writes to STDOUT, and don't want the Perl script to do anything until the command finishes.

#arguments are always processed by the shell

#in list context it returns the output as a list of lines
my @lines = qx/command arg1 arg2 arg3/;

#in scalar context it returns the output as one string
my $output = qx/command arg1 arg2 arg3/;

exec: replace the current process with another process.

Use exec along with fork when you want to run a command, don't care about its output, and don't want to wait for it to return. system is really just

sub my_system {
    die "could not fork\n" unless defined(my $pid = fork);
    return waitpid $pid, 0 if $pid; #parent waits for child
    exec @_; #replace child with new process
}

You may also want to read the waitpid and perlipc manuals.

open: run a process and create a pipe to its STDIN or STDERR

Use open when you want to write data to a process's STDIN or read data from a process's STDOUT (but not both at the same time).

#read from a gzip file as if it were a normal file
open my $read_fh, "-|", "gzip", "-d", $filename
    or die "could not open $filename: $!";

#write to a gzip compressed file as if were a normal file
open my $write_fh, "|-", "gzip", $filename
    or die "could not open $filename: $!";

IPC::Open2: run a process and create a pipe to both STDIN and STDOUT

Use IPC::Open2 when you need to read from and write to a process's STDIN and STDOUT.

use IPC::Open2;

open2 my $out, my $in, "/usr/bin/bc"
    or die "could not run bc";

print $in "5+6\n";

my $answer = <$out>;

IPC::Open3: run a process and create a pipe to STDIN, STDOUT, and STDERR

use IPC::Open3 when you need to capture all three standard file handles of the process. I would write an example, but it works mostly the same way IPC::Open2 does, but with a slightly different order to the arguments and a third file handle.

writing integer values to a file using out.write()

Also you can use f-string formatting to write integer to file

For appending use following code, for writing once replace 'a' with 'w'.

for i in s_list:
    with open('path_to_file','a') as file:
        file.write(f'{i}\n')

file.close()

How can I properly handle 404 in ASP.NET MVC?

1) Make abstract Controller class.

public abstract class MyController:Controller
{
    public ActionResult NotFound()
    {
        Response.StatusCode = 404;
        return View("NotFound");
    }

    protected override void HandleUnknownAction(string actionName)
    {
        this.ActionInvoker.InvokeAction(this.ControllerContext, "NotFound");
    }
    protected override void OnAuthorization(AuthorizationContext filterContext) { }
}  

2) Make inheritence from this abstract class in your all controllers

public class HomeController : MyController
{}  

3) And add a view named "NotFound" in you View-Shared folder.

Android BroadcastReceiver within Activity

You forget to write .show() at the end, which is used to show the toast message.

Toast.makeText(getApplicationContext(), "received", Toast.LENGTH_SHORT).show();

It is a common mistake that programmer does, but i am sure after this you won't repeat the mistake again... :D

Laravel 5 - artisan seed [ReflectionException] Class SongsTableSeeder does not exist

I have used only SINGLE FILE with TWO classes in it following :

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
use App\Lesson;

use Faker\Factory as Faker;

class DatabaseSeeder extends Seeder {

/**
 * Run the database seeds.
 *
 * @return void
 */
public function run()
{
    //Lesson::truncate();

    Model::unguard();

    $this->call("LessonsTableSeeder");


}

}

class LessonsTableSeeder extends Seeder {

/**
 * Run the database seeds.
 *
 * @return void
 */
public function run()
{

    $faker = Faker::create();

    foreach(range(1,30) as $index) {

        Lesson::create(['title' => $faker->sentence(5), 'body' => $faker->paragraph(4)]);

    }

}

}

Why can't Python find shared objects that are in directories in sys.path?

Had the exact same issue. I installed curl 7.19 to /opt/curl/ to make sure that I would not affect current curl on our production servers. Once I linked libcurl.so.4 to /usr/lib:

sudo ln -s /opt/curl/lib/libcurl.so /usr/lib/libcurl.so.4

I still got the same error! Durf.

But running ldconfig make the linkage for me and that worked. No need to set the LD_RUN_PATH or LD_LIBRARY_PATH at all. Just needed to run ldconfig.

Break string into list of characters in Python

In python many things are iterable including files and strings. Iterating over a filehandler gives you a list of all the lines in that file. Iterating over a string gives you a list of all the characters in that string.

charsFromFile = []
filePath = r'path\to\your\file.txt' #the r before the string lets us use backslashes

for line in open(filePath):
    for char in line:
        charsFromFile.append(char) 
        #apply code on each character here

or if you want a one liner

#the [0] at the end is the line you want to grab.
#the [0] can be removed to grab all lines
[list(a) for a in list(open('test.py'))][0]  

.

.

Edit: as agf mentions you can use itertools.chain.from_iterable

His method is better, unless you want the ability to specify which lines to grab list(itertools.chain.from_iterable(open(filename, 'rU)))

This does however require one to be familiar with itertools, and as a result looses some readablity

If you only want to iterate over the chars, and don't care about storing a list, then I would use the nested for loops. This method is also the most readable.

What is the runtime performance cost of a Docker container?

An excellent 2014 IBM research paper “An Updated Performance Comparison of Virtual Machines and Linux Containers” by Felter et al. provides a comparison between bare metal, KVM, and Docker containers. The general result is: Docker is nearly identical to native performance and faster than KVM in every category.

The exception to this is Docker’s NAT — if you use port mapping (e.g., docker run -p 8080:8080), then you can expect a minor hit in latency, as shown below. However, you can now use the host network stack (e.g., docker run --net=host) when launching a Docker container, which will perform identically to the Native column (as shown in the Redis latency results lower down).

Docker NAT overhead

They also ran latency tests on a few specific services, such as Redis. You can see that above 20 client threads, highest latency overhead goes Docker NAT, then KVM, then a rough tie between Docker host/native.

Docker Redis Latency Overhead

Just because it’s a really useful paper, here are some other figures. Please download it for full access.

Taking a look at Disk I/O:

Docker vs. KVM vs. Native I/O Performance

Now looking at CPU overhead:

Docker CPU Overhead

Now some examples of memory (read the paper for details, memory can be extra tricky):

Docker Memory Comparison

adb shell command to make Android package uninstall dialog appear

Running the @neverever415 answer I got:

Failure [DELETE_FAILED_INTERNAL_ERROR]

In this case check that you wrote a right package name, maybe it is a debug version like com.package_name.debug:

adb shell pm uninstall com.package_name.debug

Or see https://android.stackexchange.com/questions/179575/how-to-uninstall-a-system-app-using-adb-uninstall-command-not-remove-via-rm-or.

Is CSS Turing complete?

CSS is not a programming language, so the question of turing-completeness is a meaningless one. If programming extensions are added to CSS such as was the case in IE6 then that new synthesis is a whole different thing.

CSS is merely a description of styles; it does not have any logic, and its structure is flat.

Nginx subdomain configuration

Another type of solution would be to autogenerate the nginx conf files via Jinja2 templates from ansible. The advantage of this is easy deployment to a cloud environment, and easy to replicate on multiple dev machines

Download history stock prices automatically from yahoo finance in python

You can check out the yahoo_fin package. It was initially created after Yahoo Finance changed their API (documentation is here: http://theautomatic.net/yahoo_fin-documentation).

from yahoo_fin import stock_info as si

aapl_data = si.get_data("aapl")

nflx_data = si.get_data("nflx")

aapl_data.head()

nflx_data.head()

aapl.to_csv("aapl_data.csv")

nflx_data.to_csv("nflx_data.csv")

How to create file object from URL object (image)

You can convert the URL to a String and use it to create a new File. e.g.

URL url = new URL("http://google.com/pathtoaimage.jpg");
File f = new File(url.getFile());

Printing string variable in Java

You're getting the toString() value returned by the Scanner object itself which is not what you want and not how you use a Scanner object. What you want instead is the data obtained by the Scanner object. For example,

Scanner input = new Scanner(System.in);
String data = input.nextLine();
System.out.println(data);

Please read the tutorial on how to use it as it will explain all.

Edit
Please look here: Scanner tutorial

Also have a look at the Scanner API which will explain some of the finer points of Scanner's methods and properties.

Write string to output stream

OutputStream writes bytes, String provides chars. You need to define Charset to encode string to byte[]:

outputStream.write(string.getBytes(Charset.forName("UTF-8")));

Change UTF-8 to a charset of your choice.

How would you implement an LRU cache in Java?

There are two open source implementations.

Apache Solr has ConcurrentLRUCache: https://lucene.apache.org/solr/3_6_1/org/apache/solr/util/ConcurrentLRUCache.html

There's an open source project for a ConcurrentLinkedHashMap: http://code.google.com/p/concurrentlinkedhashmap/

Spring Boot default H2 jdbc connection (and H2 console)

As of Spring Boot 1.3.0.M3, the H2 console can be auto-configured.

The prerequisites are:

  • You are developing a web app
  • Spring Boot Dev Tools are enabled
  • H2 is on the classpath

Even if you don't use Spring Boot Dev Tools, you can still auto-configure the console by setting spring.h2.console.enabled to true

Check out this part of the documentation for all the details.

Note that when configuring in this way the console is accessible at: http://localhost:8080/h2-console/

jQuery removing '-' character from string

$mylabel.text( $mylabel.text().replace('-', '') );

Since text() gets the value, and text( "someValue" ) sets the value, you just place one inside the other.

Would be the equivalent of doing:

var newValue = $mylabel.text().replace('-', '');
$mylabel.text( newValue );

EDIT:

I hope I understood the question correctly. I'm assuming $mylabel is referencing a DOM element in a jQuery object, and the string is in the content of the element.

If the string is in some other variable not part of the DOM, then you would likely want to call the .replace() function against that variable before you insert it into the DOM.

Like this:

var someVariable = "-123456";
$mylabel.text( someVariable.replace('-', '') );

or a more verbose version:

var someVariable = "-123456";
someVariable = someVariable.replace('-', '');
$mylabel.text( someVariable );

grabbing first row in a mysql query only

You didn't specify how the order is determined, but this will give you a rank value in MySQL:

SELECT t.*,
       @rownum := @rownum +1 AS rank
  FROM TBL_FOO t
  JOIN (SELECT @rownum := 0) r
 WHERE t.name = 'sarmen'

Then you can pick out what rows you want, based on the rank value.

PHP: Calling another class' method

You would need to have an instance of ClassA within ClassB or have ClassB inherit ClassA

class ClassA {
    public function getName() {
      echo $this->name;
    }
}

class ClassB extends ClassA {
    public function getName() {
      parent::getName();
    }
}

Without inheritance or an instance method, you'd need ClassA to have a static method

class ClassA {
  public static function getName() {
    echo "Rawkode";
  }
}

--- other file ---

echo ClassA::getName();

If you're just looking to call the method from an instance of the class:

class ClassA {
  public function getName() {
    echo "Rawkode";
  }
}

--- other file ---

$a = new ClassA();
echo $a->getName();

Regardless of the solution you choose, require 'ClassA.php is needed.

Get max and min value from array in JavaScript

Instead of .each, another (perhaps more concise) approach to getting all those prices might be:

var prices = $(products).children("li").map(function() {
    return $(this).prop("data-price");
}).get();

additionally you may want to consider filtering the array to get rid of empty or non-numeric array values in case they should exist:

prices = prices.filter(function(n){ return(!isNaN(parseFloat(n))) });

then use Sergey's solution above:

var max = Math.max.apply(Math,prices);
var min = Math.min.apply(Math,prices);

Destroy or remove a view in Backbone.js

This is what I've been using. Haven't seen any issues.

destroy: function(){
  this.remove();
  this.unbind();
}

Singleton design pattern vs Singleton beans in Spring container

"singleton" in spring is using bean factory get instance, then cache it; which singleton design pattern is strictly, the instance can only be retrieved from static get method, and the object can never be publicly instantiated.

How to prevent a double-click using jQuery?

Just one more solution:

$('a').on('click', function(e){
    var $link = $(e.target);
    e.preventDefault();
    if(!$link.data('lockedAt') || +new Date() - $link.data('lockedAt') > 300) {
        doSomething();
    }
    $link.data('lockedAt', +new Date());
});

Here we save the time of last click as data attribute and then check if previous click was more than 0.3 seconds ago. If it is false (less than 0.3 sec ago), just update last click time, if true, do something.

jsbin

Save internal file in my own internal folder in Android

Save:

public boolean saveFile(Context context, String mytext){
    Log.i("TESTE", "SAVE");
    try {
        FileOutputStream fos = context.openFileOutput("file_name"+".txt",Context.MODE_PRIVATE);
        Writer out = new OutputStreamWriter(fos);
        out.write(mytext);
        out.close();
        return true;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}

Load:

public String load(Context context){
    Log.i("TESTE", "FILE");
    try {
        FileInputStream fis = context.openFileInput("file_name"+".txt");
        BufferedReader r = new BufferedReader(new InputStreamReader(fis));
        String line= r.readLine();
        r.close();
        return line;
    } catch (IOException e) {
        e.printStackTrace();
        Log.i("TESTE", "FILE - false");
        return null;
    }
}

How to move Jenkins from one PC to another

Following the Jenkins wiki, you'll have to:

  • Install a fresh Jenkins instance on the new server
  • Be sure the old and the new Jenkins instances are stopped
  • Archive all the content of the JENKINS_HOME of the old Jenkins instance
  • Extract the archive into the new JENKINS_HOME directory
  • Launch the new Jenkins instance
  • Do not forget to change documentation/links to your new instance of Jenkins :)
  • Do not forget to change the owner of the new Jenkins files : chown -R jenkins:jenkins $JENKINS_HOME

JENKINS_HOME is by default located in ~/.jenkins on a Linux installation, yet to exactly find where it is located, go on the http://your_jenkins_url/configure page and check the value of the first parameter: Home directory; this is the JENKINS_HOME.

Git Pull is Not Possible, Unmerged Files

There is a solution even if you don't want to remove your local changes. Just fix the unmerged files (by git add or git remove). Then do git pull.

Add a UIView above all, even the navigation bar

You can do that by adding your view directly to the keyWindow:

UIView *myView = /* <- Your custom view */;
UIWindow *currentWindow = [UIApplication sharedApplication].keyWindow;
[currentWindow addSubview:myView];

UPDATE -- For Swift 4.1 and above

let currentWindow: UIWindow? = UIApplication.shared.keyWindow
currentWindow?.addSubview(myView)

UPDATE for iOS13 and above

keyWindow is deprecated. You should use the following:

UIApplication.shared.windows.first(where: { $0.isKeyWindow })?.addSubview(myView)

How to get file name from file path in android

We can find file name below code:

File file =new File(Path);
String filename=file.getName();

GIT vs. Perforce- Two VCS will enter... one will leave

I have been using Perforce for a long time and recently I also started to use GIT. Here is my "objective" opinion:

Perforce features:

  1. GUI tools seem to be more feature rich (e.g. Time lapse view, Revision graph)
  2. Speed when syncing to head revision (no overhead of transferring whole history)
  3. Eclipse/Visual Studio Integration is really nice
  4. You can develop multiple features in one branch per Changelist (I am still not 100% sure if this is an advantage over GIT)
  5. You can "spy" what other developers are doing - what kind of files they have checked out.

GIT features:

  1. I got impressions that GIT command line is much simpler than Perforce (init/clone, add, commit. No configuration of complex Workspaces)
  2. Speed when accessing project history after a checkout (comes at a cost of copying whole history when syncing)
  3. Offline mode (developers will not complain that unreachable P4 server will prohibit them from coding)
  4. Creating a new branches is much faster
  5. The "main" GIT server does not need plenty of TBytes of storage, because each developer can have it's own local sandbox
  6. GIT is OpenSource - no Licensing fees
  7. If your Company is contributing also to OpenSource projects then sharing patches is way much easier with GIT

Overall for OpenSource/Distributed projects I would always recommend GIT, because it is more like a P2P application and everyone can participate in development. For example, I remember that when I was doing remote development with Perforce I was syncing 4GB Projects over 1Mbps link once in a week. Alot of time was simply wasted because of that. Also we needed set up VPN to do that.

If you have a small company and P4 server will be always up then I would say that Perforce is also a very good option.

How do I convert uint to int in C#?

I would say using tryParse, it'll return 'false' if the uint is to big for an int.
Don't forget that a uint can go much bigger than a int, as long as you going > 0

Text size and different android screen sizes

I think its too late to reply on this thread. But I would like to share my idea or way to resolve text size problem over difference resolution devices. Many android developer sites suggest that we have to use sp unit for text size which will handle text size for difference resolution devices. But I am always unable to get the desired result. So I have found one solution which I am using from my last 4-5 projects and its working fine. As per my suggestion, you have to place the text size for each resolution devices, which is bit tedious work, but it will fulfill your requirement. Each developer has must listen about the ratio like 4:6:8:12 (h:xh:xxh:xxxh respectively). Now inside your project res folder you have to create 4 folder with dimens file e.g.

  1. res/values-hdpi/dimens.xml
  2. res/values-xhdpi/dimens.xml
  3. res/values-xxhdpi/dimens.xml
  4. res/values-xxxhdpi/dimens.xml

Now inside dimens.xml file you have to place text sizes. I am showing you code for values-hdpi, similarly you have to place code for other resolution values/dimens.xml file.

<?xml version="1.0" encoding="utf-8"?>
<resources>
   <dimen name="text_size">4px</dimen>
</resources>

For other resolutions it is like xhdpi : 6px, xxhdpi : 8px, xxxhdpi : 12px. This is calculated with the ratio (3:4:6:8:12) I have written above. Lets discuss other text size example with above ratio. If you want to take text size of 12px in hdpi, then in other resolution it would be

  1. hdpi : 12px
  2. xhdpi : 18px
  3. xxhdpi : 24px
  4. xxxhdpi : 36px

This is the simple solution to implement required text size for all resolutions. I am not considering values-mdpi resolution devices here. If any one want to include text size for this resolution then ration is like 3:4:6:8:12. In any query please let me know. Hope it will help you people out.

Getting an element from a Set

What about using the Arrays class ?

import java.util.Arrays;
import java.util.List;
import java.util.HashSet;
import java.util.Arrays;

public class MyClass {
    public static void main(String args[]) {
        Set mySet = new HashSet();
        mySet.add("one");
        mySet.add("two");
        List list = Arrays.asList(mySet.toArray());
        Object o0 = list.get(0);
        Object o1 = list.get(1);
        System.out.println("items " + o0+","+o1);
    }
}

output:
items one,two

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

from sklearn import metrics
import bumpy as np
print(no.sqrt(metrics.mean_squared_error(actual,predicted)))

How to Pass data from child to parent component Angular

In order to send data from child component create property decorated with output() in child component and in the parent listen to the created event. Emit this event with new values in the payload when ever it needed.

@Output() public eventName:EventEmitter = new EventEmitter();

to emit this event:

this.eventName.emit(payloadDataObject);

What is "android:allowBackup"?

It is privacy concern. It is recommended to disallow users to backup an app if it contains sensitive data. Having access to backup files (i.e. when android:allowBackup="true"), it is possible to modify/read the content of an app even on a non-rooted device.

Solution - use android:allowBackup="false" in the manifest file.

You can read this post to have more information: Hacking Android Apps Using Backup Techniques

Convert HTML5 into standalone Android App

Create an Android app using Eclipse.

Create a layout that has a <WebView> control.

Move your HTML code to /assets folder.

Load webview with your file:///android_asset/ file.

And you have an android app!

Error checking for NULL in VBScript

From your code, it looks like provider is a variant or some other variable, and not an object.

Is Nothing is for objects only, yet later you say it's a value that should either be NULL or NOT NULL, which would be handled by IsNull.

Try using:

If Not IsNull(provider) Then 
    url = url & "&provider=" & provider 
End if

Alternately, if that doesn't work, try:

If provider <> "" Then 
    url = url & "&provider=" & provider 
End if

JPA getSingleResult() or null

Spring has a utility method for this:

TypedQuery<Profile> query = em.createNamedQuery(namedQuery, Profile.class);
...
return org.springframework.dao.support.DataAccessUtils.singleResult(query.getResultList());

Waiting on a list of Future

maybe this would help (nothing would replaced with raw thread, yeah!) I suggest run each Future guy with a separated thread (they goes parallel), then when ever one of the got error, it just signal the manager(Handler class).

class Handler{
//...
private Thread thisThread;
private boolean failed=false;
private Thread[] trds;
public void waitFor(){
  thisThread=Thread.currentThread();
  List<Future<Object>> futures = getFutures();
  trds=new Thread[futures.size()];
  for (int i = 0; i < trds.length; i++) {
    RunTask rt=new RunTask(futures.get(i), this);
    trds[i]=new Thread(rt);
  }
  synchronized (this) {
    for(Thread tx:trds){
      tx.start();
    }  
  }
  for(Thread tx:trds){
    try {tx.join();
    } catch (InterruptedException e) {
      System.out.println("Job failed!");break;
    }
  }if(!failed){System.out.println("Job Done");}
}

private List<Future<Object>> getFutures() {
  return null;
}

public synchronized void cancelOther(){if(failed){return;}
  failed=true;
  for(Thread tx:trds){
    tx.stop();//Deprecated but works here like a boss
  }thisThread.interrupt();
}
//...
}
class RunTask implements Runnable{
private Future f;private Handler h;
public RunTask(Future f,Handler h){this.f=f;this.h=h;}
public void run(){
try{
f.get();//beware about state of working, the stop() method throws ThreadDeath Error at any thread state (unless it blocked by some operation)
}catch(Exception e){System.out.println("Error, stopping other guys...");h.cancelOther();}
catch(Throwable t){System.out.println("Oops, some other guy has stopped working...");}
}
}

I have to say the above code would error(didn't check), but I hope I could explain the solution. please have a try.

Using print statements only to debug

First off, I will second the nomination of python's logging framework. Be a little careful about how you use it, however. Specifically: let the logging framework expand your variables, don't do it yourself. For instance, instead of:

logging.debug("datastructure: %r" % complex_dict_structure)

make sure you do:

logging.debug("datastructure: %r", complex_dict_structure)

because while they look similar, the first version incurs the repr() cost even if it's disabled. The second version avoid this. Similarly, if you roll your own, I'd suggest something like:

def debug_stdout(sfunc):
    print(sfunc())

debug = debug_stdout

called via:

debug(lambda: "datastructure: %r" % complex_dict_structure)

which will, again, avoid the overhead if you disable it by doing:

def debug_noop(*args, **kwargs):
    pass

debug = debug_noop

The overhead of computing those strings probably doesn't matter unless they're either 1) expensive to compute or 2) the debug statement is in the middle of, say, an n^3 loop or something. Not that I would know anything about that.

How to install php-curl in Ubuntu 16.04

Do:

apt-get update

And then:

apt-get install php5-curl

T-SQL: Looping through an array of known values

You can try as below :

declare @list varchar(MAX), @i int
select @i=0, @list ='4,7,12,22,19,'

while( @i < LEN(@list))
begin
    declare @item varchar(MAX)
    SELECT  @item = SUBSTRING(@list,  @i,CHARINDEX(',',@list,@i)-@i)
    select @item

     --do your stuff here with @item 
     exec p_MyInnerProcedure @item 

    set @i = CHARINDEX(',',@list,@i)+1
    if(@i = 0) set @i = LEN(@list) 
end

Stop Excel from automatically converting certain text values to dates

(Assuming Excel 2003...)

When using the Text-to-Columns Wizard has, in Step 3 you can dictate the data type for each of the columns. Click on the column in the preview and change the misbehaving column from "General" to "Text."

When restoring a backup, how do I disconnect all active connections?

I ran across this problem while automating a restore proccess in SQL Server 2008. My (successfull) approach was a mix of two of the answers provided.

First, I run across all the connections of said database, and kill them.

DECLARE @SPID int = (SELECT TOP 1 SPID FROM sys.sysprocess WHERE dbid = db_id('dbName'))
While @spid Is Not Null
Begin
        Execute ('Kill ' + @spid)
        Select @spid = top 1 spid from master.dbo.sysprocesses
        where dbid = db_id('dbName')
End

Then, I set the database to a single_user mode

ALTER DATABASE dbName SET SINGLE_USER

Then, I run the restore...

RESTORE DATABASE and whatnot

Kill the connections again

(same query as above)

And set the database back to multi_user.

ALTER DATABASE dbName SET MULTI_USER

This way, I ensure that there are no connections holding up the database before setting to single mode, since the former will freeze if there are.

DECODE( ) function in SQL Server

when I use the function

select dbo.decode(10>1 ,'yes' ,'no')

then say syntax error near '>'

Unfortunately, that does not get you around having the CASE clause in the SQL, since you would need it to convert the logical expression to a bit parameter to match the type of the first function argument:

create function decode(@var1 as bit, @var2 as nvarchar(100), @var3 as nvarchar(100))
returns nvarchar(100)
begin
return case when @var1 = 1 then @var2 else @var3 end;
end;

select dbo.decode(case when 10 > 1 then 1 else 0 end, 'Yes', 'No');

Open File Dialog, One Filter for Multiple Excel Extensions?

If you want to merge the filters (eg. CSV and Excel files), use this formula:

OpenFileDialog of = new OpenFileDialog();
of.Filter = "CSV files (*.csv)|*.csv|Excel Files|*.xls;*.xlsx";

Or if you want to see XML or PDF files in one time use this:

of.Filter = @" XML or PDF |*.xml;*.pdf";

How to read data from excel file using c#

Convert the excel file to .csv file (comma separated value file) and now you can easily be able to read it.

How to overlay images

You might want to check out this tutorial: http://www.webdesignerwall.com/tutorials/css-decorative-gallery/

In it the writer uses an empty span element to add an overlaying image. You can use jQuery to inject said span elements, if you'd like to keep your code as clean as possible. An example is also given in the aforementioned article.

Hope this helps!

-Dave

Text-decoration: none not working

Use CSS Pseudo-classes and give your tag a class, for example:

<a class="noDecoration" href="#">

and add this to your stylesheet:

.noDecoration, a:link, a:visited {
    text-decoration: none;
}

Change color of Back button in navigation bar

Swift 4.2

Change complete app theme

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

        UINavigationBar.appearance().tintColor = .white

        return true
    }

Change specific controller

let navController = UINavigationController.init(rootViewController: yourViewController) 
navController.navigationBar.tintColor = .red

present(navController, animated: true, completion: nil)

Make anchor link go some pixels above where it's linked to

<a href="#anchor">Click me!</a>

<div style="margin-top: -100px; padding-top: 100px;" id="anchor"></div>
<p>I should be 100px below where I currently am!</p>

Git diff between current branch and master but not including unmerged master commits

Here's what worked for me:

git diff origin/master...

This shows only the changes between my currently selected local branch and the remote master branch, and ignores all changes in my local branch that came from merge commits.

The system cannot find the file specified in java

You need to give the absolute pathname to where the file exists.

        File file = new File("C:\\Users\\User\\Documents\\Workspace\\FileRead\\hello.txt");

SQL: how to select a single id ("row") that meets multiple criteria from a single column

Users who have one of the 3 countries

SELECT DISTINCT user_id
FROM table
WHERE ancestry IN('England','France','Germany')

Users who have all 3 countries

SELECT DISTINCT A.userID
FROM table A
   INNER JOIN table B on A.user_id = B.user_id
   INNER JOIN table C on A.user_id = C.user_id
WHERE A.ancestry = 'England'
   AND B.ancestry = 'Germany'
   AND C.ancestry = 'France'

Twitter Bootstrap and ASP.NET GridView

Just for the record, I got borders in the table and to get rid of it I needed to set following properties in the GridView:

GridLines="None"
CellSpacing="-1"

Html/PHP - Form - Input as array

HTML: Use names as

<input name="levels[level][]">
<input name="levels[build_time][]">

PHP:

$array = filter_input_array(INPUT_POST);
$newArray = array();
foreach (array_keys($array) as $fieldKey) {
    foreach ($array[$fieldKey] as $key=>$value) {
        $newArray[$key][$fieldKey] = $value;
    }
}  

$newArray will hold data as you want

Array ( 
  [0] => Array ( [level] => 1 [build_time] => 123 ) 
  [1] => Array ( [level] => 2 [build_time] => 456 )
)

The tilde operator in Python

One should note that in the case of array indexing, array[~i] amounts to reversed_array[i]. It can be seen as indexing starting from the end of the array:

[0, 1, 2, 3, 4, 5, 6, 7, 8]
    ^                 ^
    i                ~i

How to divide flask app into multiple py files?

Dividing the app into blueprints is a great idea. However, if this isn't enough, and if you want to then divide the Blueprint itself into multiple py files, this is also possible using the regular Python module import system, and then looping through all the routes that get imported from the other files.

I created a Gist with the code for doing this:

https://gist.github.com/Jaza/61f879f577bc9d06029e

As far as I'm aware, this is the only feasible way to divide up a Blueprint at the moment. It's not possible to create "sub-blueprints" in Flask, although there's an issue open with a lot of discussion about this:

https://github.com/mitsuhiko/flask/issues/593

Also, even if it were possible (and it's probably do-able using some of the snippets from that issue thread), sub-blueprints may be too restrictive for your use case anyway - e.g. if you don't want all the routes in a sub-module to have the same URL sub-prefix.

How do I 'svn add' all unversioned files to SVN?

svn add --force .

This will add any unversioned file in the current directory and all versioned child directories.

Finding an item in a List<> using C#

For .NET 2.0:

list.Find(delegate(Item i) { return i.Property == someValue; });

How to allow http content within an iframe on a https site

Try to use protocol relative links.

Your link is http://example.com/script.js, use:

<script src="//example.com/script.js" type="text/javascript"></script>

In this way, you can leave the scheme free (do not indicate the protocol in the links) and trust that the browser uses the protocol of the embedded Web page. If your users visit the HTTP version of your Web page, the script will be loaded over http:// and if your users visit the HTTPS version of your Web site, the script will be loaded over https://.

Seen in: https://developer.mozilla.org/es/docs/Seguridad/MixedContent/arreglar_web_con_contenido_mixto

What is the difference between Set and List?

TOPIC Name: List VS Set

I have just gone through Java's most important topic called Collections Framework. I thought to share my little knowledge about Collections with you. List, Set, Map are the most important topic of it. So let's start with List and Set.

Difference between List and Set:

  1. List is a collection class which extends AbstractList class where as Set is a collection class which extends AbstractSet class but both implements Collection interface.

  2. List interface allows duplicate values (elements) whereas Set interface does not allow duplicate values. In case of duplicate elements in Set, it replaces older values.

  3. List interface allows NULL values where as Set interface does not allow Null values. In case of using Null values in Set it gives NullPointerException.

  4. List interface maintains insertion order. That means the way we add the elements in the List in the same way we obtain it using iterator or for-each style. Whereas Set implementations do not necessarily maintain insertion order. (Although SortedSet does using TreeSet, and LinkedHashSet maintains insertion order).

  5. List interface has its own methods defined whereas Set interface does not have its own method so Set uses Collection interface methods only.

  6. List interface has one legacy class called Vector whereas Set interface does not have any legacy class

  7. Last but not the least... The listIterator() method can only be used to cycle through the elements within List Classes whereas we can use iterator() method to access Set class elements

Anything else can we add? Please let me know.

Thanks.

how to stop a for loop

To stop your loop you can use break with label. It will stop your loop for sure. Code is written in Java but aproach is the same for the all languages.

public void exitFromTheLoop() {
    boolean value = true;
            loop_label:for (int i = 0; i < 10; i++) {
              if(!value) { 
                 System.out.println("iteration: " + i);
              break loop_label;
        }
    }
}   

}

Get width/height of SVG element

FireFox have problemes for getBBox(), i need to do this in vanillaJS.

I've a better Way and is the same result as real svg.getBBox() function !

With this good post : Get the real size of a SVG/G element

var el   = document.getElementById("yourElement"); // or other selector like querySelector()
var rect = el.getBoundingClientRect(); // get the bounding rectangle

console.log( rect.width );
console.log( rect.height);

JAXB: how to marshall map into <key>value</key>

I found easiest solution.

@XmlElement(name="attribute")
    public String[] getAttributes(){
        return attributes.keySet().toArray(new String[1]);
    }
}

Now it will generate in you xml output like this:

<attribute>key1<attribute>
...
<attribute>keyN<attribute>

adding noise to a signal in python

... And for those who - like me - are very early in their numpy learning curve,

import numpy as np
pure = np.linspace(-1, 1, 100)
noise = np.random.normal(0, 1, 100)
signal = pure + noise

Displaying a message in iOS which has the same functionality as Toast in Android

I thought off a simple way to do the toast! using UIAlertController without button! We use the button text as our message! get it? see below code:

func alert(title: String?, message: String?, bdy:String) {
    let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
    let okAction = UIAlertAction(title: bdy, style: .Cancel, handler: nil)
    alertController.addAction(okAction)
        self.presentViewController(alertController, animated: true, completion: nil)


    let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(2 * Double(NSEC_PER_SEC)))
    dispatch_after(delayTime, dispatch_get_main_queue()) {
        //print("Bye. Lovvy")
        alertController.dismissViewControllerAnimated(true, completion: nil) 
    }    
}

use it like this:

self.alert(nil,message:nil,bdy:"Simple Toast!") // toast
self.alert(nil,message:nil,bdy:"Alert") // alert with "Alert" button

When should I use a trailing slash in my URL?

I'm always surprised by the extensive use of trailing slashes on non-directory URLs (WordPress among others). This really shouldn't be an either-or debate because putting a slash after a resource is semantically wrong. The web was designed to deliver addressable resources, and those addresses - URLs - were designed to emulate a *nix-style file-system hierarchy. In that context:

  • Slashes always denote directories, never files.
  • Files may be named anything (with or without extensions), but cannot contain or end with slashes.

Using these guidelines, it's wrong to put a slash after a non-directory resource.

How to add subject alernative name to ssl certs?

Although this question was more specifically about IP addresses in Subject Alt. Names, the commands are similar (using DNS entries for a host name and IP entries for IP addresses).

To quote myself:

If you're using keytool, as of Java 7, keytool has an option to include a Subject Alternative Name (see the table in the documentation for -ext): you could use -ext san=dns:www.example.com or -ext san=ip:10.0.0.1

Note that you only need Java 7's keytool to use this command. Once you've prepared your keystore, it should work with previous versions of Java.

(The rest of this answer also mentions how to do this with OpenSSL, but it doesn't seem to be what you're using.)

Anaconda Navigator won't launch (windows 10)

Update to the latest conda and latest navigator will resolve this issue.

Open the Anaconda Prompt and type

  • conda update conda

and

  • conda update anaconda-navigator

JavaScript closure inside loops – simple practical example

Use closure structure, this would reduce your extra for loop. You can do it in a single for loop:

var funcs = [];
for (var i = 0; i < 3; i++) {     
  (funcs[i] = function() {         
    console.log("My value: " + i); 
  })(i);
}

I have created a table in hive, I would like to know which directory my table is created in?

in hive 0.1 you can use SHOW CREATE TABLE to find the path where hive store data.

in other versions, there is no good way to do this.

upadted:

thanks Joe K

use DESCRIBE FORMATTED <table> to show table information.

ps: database.tablename is not supported here.

Excel formula to get ranking position

Try this in your forth column

=COUNTIF(B:B; ">" & B2) + 1

Replace B2 with B3 for next row and so on.

What this does is it counts how many records have more points then current one and then this adds current record position (+1 part).

Javascript format date / time

Yes, you can use the native javascript Date() object and its methods.

For instance you can create a function like:

function formatDate(date) {
  var hours = date.getHours();
  var minutes = date.getMinutes();
  var ampm = hours >= 12 ? 'pm' : 'am';
  hours = hours % 12;
  hours = hours ? hours : 12; // the hour '0' should be '12'
  minutes = minutes < 10 ? '0'+minutes : minutes;
  var strTime = hours + ':' + minutes + ' ' + ampm;
  return (date.getMonth()+1) + "/" + date.getDate() + "/" + date.getFullYear() + "  " + strTime;
}

var d = new Date();
var e = formatDate(d);

alert(e);

And display also the am / pm and the correct time.

Remember to use getFullYear() method and not getYear() because it has been deprecated.

DEMO http://jsfiddle.net/a_incarnati/kqo10jLb/4/

Add text to textarea - Jquery

Just append() the text nodes:

$('#replyBox').append(quote); 

http://jsfiddle.net/nQErc/

How to pass object with NSNotificationCenter

You'll have to use the "userInfo" variant and pass a NSDictionary object that contains the messageTotal integer:

NSDictionary* userInfo = @{@"total": @(messageTotal)};

NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];
[nc postNotificationName:@"eRXReceived" object:self userInfo:userInfo];

On the receiving end you can access the userInfo dictionary as follows:

-(void) receiveTestNotification:(NSNotification*)notification
{
    if ([notification.name isEqualToString:@"TestNotification"])
    {
        NSDictionary* userInfo = notification.userInfo;
        NSNumber* total = (NSNumber*)userInfo[@"total"];
        NSLog (@"Successfully received test notification! %i", total.intValue);
    }
}

What is use of c_str function In c++

c_str() converts a C++ string into a C-style string which is essentially a null terminated array of bytes. You use it when you want to pass a C++ string into a function that expects a C-style string (e.g. a lot of the Win32 API, POSIX style functions, etc).

How to sort alphabetically while ignoring case sensitive?

did you tried converting the first char of the string to lowercase on if(fruits[i].charAt(0) == currChar) and char currChar = fruits[0].charAt(0) statements?

Assign command output to variable in batch file

You can't assign a process output directly into a var, you need to parse the output with a For /F loop:

@Echo OFF

FOR /F "Tokens=2,*" %%A IN (
    'Reg Query "HKEY_CURRENT_USER\Software\Macromedia\FlashPlayer" /v "CurrentVersion"'
) DO (
    REM Set "Version=%%B"
    Echo Version: %%B
)

Pause&Exit

http://ss64.com/nt/for_f.html

PS: Change the reg key used if needed.

How to call a stored procedure (with parameters) from another stored procedure without temp table

 Create PROCEDURE  Stored_Procedure_Name_2
  (
  @param1 int = 5  ,
  @param2 varchar(max),
  @param3 varchar(max)

 )
AS


DECLARE @Table TABLE
(
   /*TABLE DEFINITION*/
   id int,
   name varchar(max),
   address varchar(max)
)

INSERT INTO @Table 
EXEC Stored_Procedure_Name_1 @param1 , @param2 = 'Raju' ,@param3 =@param3

SELECT id ,name ,address  FROM @Table  

Use the auto keyword in C++ STL

If you want a code that is readable by all programmers (c++, java, and others) use the original old form instead of cryptographic new features

atp::ta::DataDrawArrayInfo* ddai;
for(size_t i = 0; i < m_dataDraw->m_dataDrawArrayInfoList.size(); i++) {
    ddai = m_dataDraw->m_dataDrawArrayInfoList[i];
    //...
}

Print number of keys in Redis

You can issue the INFO command, which returns information and statistics about the server. See here for an example output.

As mentioned in the comments by mVChr, you can use info keyspace directly on the redis-cli.

redis> INFO
# Server
redis_version:6.0.6
redis_git_sha1:00000000
redis_git_dirty:0
redis_build_id:b63575307aaffe0a
redis_mode:standalone
os:Linux 5.4.0-1017-aws x86_64
arch_bits:64
multiplexing_api:epoll
atomicvar_api:atomic-builtin
gcc_version:9.3.0
process_id:2854672
run_id:90a5246f10e0aeb6b02cc2765b485d841ffc924e
tcp_port:6379
uptime_in_seconds:2593097
uptime_in_days:30
hz:10
configured_hz:10
lru_clock:4030200
executable:/usr/local/bin/redis-server

How to override the [] operator in Python?

You need to use the __getitem__ method.

class MyClass:
    def __getitem__(self, key):
        return key * 2

myobj = MyClass()
myobj[3] #Output: 6

And if you're going to be setting values you'll need to implement the __setitem__ method too, otherwise this will happen:

>>> myobj[5] = 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: MyClass instance has no attribute '__setitem__'

How do I obtain a list of all schemas in a Sql Server database

You can also use the following query to get Schemas for a specific Database user:

select s.schema_id, s.name as schema_name
from sys.schemas s
inner join sys.sysusers u on u.uid = s.principal_id
where u.name='DataBaseUserUserName'
order by s.name

Singleton in Android

You are copying singleton's customVar into a singletonVar variable and changing that variable does not affect the original value in singleton.

// This does not update singleton variable
// It just assigns value of your local variable
Log.d("Test",singletonVar);
singletonVar="World";
Log.d("Test",singletonVar);

// This actually assigns value of variable in singleton
Singleton.customVar = singletonVar;

jQuery or JavaScript auto click

In jQuery you can trigger a click like this:

$('#foo').trigger('click');

More here:

http://api.jquery.com/trigger/

If you want to do the same using prototype, it looks like this:

$('foo').simulate('click');

How to change the background-color of jumbrotron?

I think another way to do it is to use in-line css, just add your background-color in the html code

<div class="jumbotron" style="background-color:blue;">
    <h3>Piece of text</h3>
</div>

Image inside div has extra space below the image

I found it works great using display:block; on the image and vertical-align:top; on the text.

_x000D_
_x000D_
.imagebox {_x000D_
    width:200px;_x000D_
    float:left;_x000D_
    height:88px;_x000D_
    position:relative;_x000D_
    background-color: #999;_x000D_
}_x000D_
.container {_x000D_
    width:600px;_x000D_
    height:176px;_x000D_
    background-color: #666;_x000D_
    position:relative;_x000D_
    overflow:hidden;_x000D_
}_x000D_
.text {_x000D_
    color: #000;_x000D_
    font-size: 11px;_x000D_
    font-family: robotomeduim, sans-serif;_x000D_
    vertical-align:top;_x000D_
    _x000D_
}_x000D_
_x000D_
.imagebox img{ display:block;}
_x000D_
<div class="container">_x000D_
    <div class="imagebox">_x000D_
        <img src="http://machdiamonds.com/n69xvs.jpg" /> <span class="text">Image title</span>_x000D_
    </div>_x000D_
    <div class="imagebox">_x000D_
        <img src="http://machdiamonds.com/n69xvs.jpg" /> <span class="text">Image title</span>_x000D_
    </div>_x000D_
    <div class="imagebox">_x000D_
        <img src="http://machdiamonds.com/n69xvs.jpg" /> <span class="text">Image title</span>_x000D_
    </div>_x000D_
    <div class="imagebox">_x000D_
        <img src="http://machdiamonds.com/n69xvs.jpg" /> <span class="text">Image title</span>_x000D_
    </div>_x000D_
    <div class="imagebox">_x000D_
        <img src="http://machdiamonds.com/n69xvs.jpg" /> <span class="text">Image title</span>_x000D_
    </div>_x000D_
    <div class="imagebox">_x000D_
        <img src="http://machdiamonds.com/n69xvs.jpg" /> <span class="text">Image title</span>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

or you can edit the code a JS FIDDLE

Getting request payload from POST request in Java servlet

With Apache Commons IO you can do this in one line.

IOUtils.toString(request.getReader())

Change SQLite database mode to read-write

In the project path Terminal django_project#

sudo chown django:django *

Proper way to declare custom exceptions in modern Python?

Maybe I missed the question, but why not:

class MyException(Exception):
    pass

Edit: to override something (or pass extra args), do this:

class ValidationError(Exception):
    def __init__(self, message, errors):

        # Call the base class constructor with the parameters it needs
        super(ValidationError, self).__init__(message)

        # Now for your custom code...
        self.errors = errors

That way you could pass dict of error messages to the second param, and get to it later with e.errors


Python 3 Update: In Python 3+, you can use this slightly more compact use of super():

class ValidationError(Exception):
    def __init__(self, message, errors):

        # Call the base class constructor with the parameters it needs
        super().__init__(message)

        # Now for your custom code...
        self.errors = errors

What's the best way to iterate an Android Cursor?

import java.util.Iterator;
import android.database.Cursor;

public class IterableCursor implements Iterable<Cursor>, Iterator<Cursor> {
    Cursor cursor;
    int toVisit;
    public IterableCursor(Cursor cursor) {
        this.cursor = cursor;
        toVisit = cursor.getCount();
    }
    public Iterator<Cursor> iterator() {
        cursor.moveToPosition(-1);
        return this;
    }
    public boolean hasNext() {
        return toVisit>0;
    }
    public Cursor next() {
    //  if (!hasNext()) {
    //      throw new NoSuchElementException();
    //  }
        cursor.moveToNext();
        toVisit--;
        return cursor;
    }
    public void remove() {
        throw new UnsupportedOperationException();
    }
}

Example code:

static void listAllPhones(Context context) {
    Cursor phones = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
    for (Cursor phone : new IterableCursor(phones)) {
        String name = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
        String phoneNumber = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
        Log.d("name=" + name + " phoneNumber=" + phoneNumber);
    }
    phones.close();
}

Python wildcard search in string

Why don't you just use the join function? In a regex findall() or group() you will need a string so:

import re
regex = re.compile('th.s')
l = ['this', 'is', 'just', 'a', 'test']
matches = re.findall(regex, ' '.join(l)) #Syntax option 1
matches = regex.findall(' '.join(l)) #Syntax option 2

The join() function allows you to transform a list in a string. The single quote before join is what you will put in the middle of each string on list. When you execute this code part (' '.join(l)) you'll receive this:

'this is just a test'

So you can use the findal() function.

I know i am 7 years late, but i recently create an account because I'm studying and other people could have the same question. I hope this help you and others.


Update After @FélixBrunet comments:

import re
regex = re.compile(r'th.s')
l = ['this', 'is', 'just', 'a', 'test','th','s', 'this is']

matches2=[] #declare a list
for i in range(len(l)): #loop with the iterations = list l lenght. This avoid the first item commented by @Felix
if regex.findall(l[i]) != []: #if the position i is not an empty list do the next line. PS: remember regex.findall() command return a list.
    if l[i]== ''.join(regex.findall(l[i])): # If the string of i position of l list = command findall() i position so it'll allow the program do the next line - this avoid the second item commented by @Félix
        matches2.append(''.join(regex.findall(l[i]))) #adds in the list just the string in the matches2 list

print(matches2)

How to install JSON.NET using NuGet?

I have Had the same issue and the only Solution i found was open Package manager> Select Microsoft and .Net as Package Source and You will install it..

enter image description here

Remove specific rows from a data frame

 X <- data.frame(Variable1=c(11,14,12,15),Variable2=c(2,3,1,4))
> X
  Variable1 Variable2
1        11         2
2        14         3
3        12         1
4        15         4
> X[X$Variable1!=11 & X$Variable1!=12, ]
  Variable1 Variable2
2        14         3
4        15         4
> X[ ! X$Variable1 %in% c(11,12), ]
  Variable1 Variable2
2        14         3
4        15         4

You can functionalize this however you like.

CSS selector (id contains part of text)

The only selector I see is a[id$="name"] (all links with id finishing by "name") but it's not as restrictive as it should.

What's the valid way to include an image with no src?

I found that simply setting the src to an empty string and adding a rule to your CSS to hide the broken image icon works just fine.

[src=''] {
    visibility: hidden;
}

Splitting on last delimiter in Python string?

Use .rsplit() or .rpartition() instead:

s.rsplit(',', 1)
s.rpartition(',')

str.rsplit() lets you specify how many times to split, while str.rpartition() only splits once but always returns a fixed number of elements (prefix, delimiter & postfix) and is faster for the single split case.

Demo:

>>> s = "a,b,c,d"
>>> s.rsplit(',', 1)
['a,b,c', 'd']
>>> s.rsplit(',', 2)
['a,b', 'c', 'd']
>>> s.rpartition(',')
('a,b,c', ',', 'd')

Both methods start splitting from the right-hand-side of the string; by giving str.rsplit() a maximum as the second argument, you get to split just the right-hand-most occurrences.

matrix multiplication algorithm time complexity

The naive algorithm, which is what you've got once you correct it as noted in comments, is O(n^3).

There do exist algorithms that reduce this somewhat, but you're not likely to find an O(n^2) implementation. I believe the question of the most efficient implementation is still open.

See this wikipedia article on Matrix Multiplication for more information.

C++ Returning reference to local variable

A local variable is memory on the stack, that memory is not automatically invalidated when you go out of scope. From a Function deeper nested (higher on the stack in memory), its perfectly safe to access this memory.

Once the Function returns and ends though, things get dangerous. Usually the memory is not deleted or overwritten when you return, meaning the memory at that adresss is still containing your data - the pointer seems valid.

Until another function builds up the stack and overwrites it. This is why this can work for a while - and then suddenly cease to function after one particularly deeply nested set of functions, or a function with really huge sized or many local objects, reaches that stack-memory again.

It even can happen that you reach the same program part again, and overwrite your old local function variable with the new function variable. All this is very dangerous and should be heavily discouraged. Do not use pointers to local objects!

ggplot legends - change labels, order and title

You need to do two things:

  1. Rename and re-order the factor levels before the plot
  2. Rename the title of each legend to the same title

The code:

dtt$model <- factor(dtt$model, levels=c("mb", "ma", "mc"), labels=c("MBB", "MAA", "MCC"))

library(ggplot2)
ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
  geom_ribbon(alpha = 0.35, linetype=0)+ 
  geom_line(aes(linetype=model), size = 1) +       
  geom_point(aes(shape=model), size=4)  +      
  theme(legend.position=c(.6,0.8)) +
  theme(legend.background = element_rect(colour = 'black', fill = 'grey90', size = 1, linetype='solid')) +
  scale_linetype_discrete("Model 1") +
  scale_shape_discrete("Model 1") +
  scale_colour_discrete("Model 1")

enter image description here

However, I think this is really ugly as well as difficult to interpret. It's far better to use facets:

ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
  geom_ribbon(alpha=0.2, colour=NA)+ 
  geom_line() +       
  geom_point()  +      
  facet_wrap(~model)

enter image description here

Multiple conditions in if statement shell script

if using /bin/sh you can use:

if [ <condition> ] && [ <condition> ]; then
    ...
fi

if using /bin/bash you can use:

if [[ <condition> && <condition> ]]; then
    ...
fi

Setting session variable using javascript

It is very important to understand both sessionStorage and localStorage as they both have different uses:

From MDN:

All of your web storage data is contained within two object-like structures inside the browser: sessionStorage and localStorage. The first one persists data for as long as the browser is open (the data is lost when the browser is closed) and the second one persists data even after the browser is closed and then opened again.

sessionStorage - Saves data until the browser is closed, the data is deleted when the tab/browser is closed.

localStorage - Saves data "forever" even after the browser is closed BUT you shouldn't count on the data you store to be there later, the data might get deleted by the browser at any time because of pretty much anything, or deleted by the user, best practice would be to validate that the data is there first, and continue the rest if it is there. (or set it up again if its not there)

To understand more, read here: localStorage | sessionStorage

iPhone app signing: A valid signing identity matching this profile could not be found in your keychain

Everyone here is very wrong. All you need is to follow the steps that Apple provides in Managing Your Digital Identities.

It instructs you to export your certificates through Xcode and reimport through Xcode. It works great, but make sure your username is the same on both computers or it will fail.

Hide all warnings in ipython

I hide the warnings in the pink boxes by running the following code in a cell:

from IPython.display import HTML
HTML('''<script>
code_show_err=false; 
function code_toggle_err() {
 if (code_show_err){
 $('div.output_stderr').hide();
 } else {
 $('div.output_stderr').show();
 }
 code_show_err = !code_show_err
} 
$( document ).ready(code_toggle_err);
</script>
To toggle on/off output_stderr, click <a href="javascript:code_toggle_err()">here</a>.''')

How do I clone a Django model instance object and save it to the database?

To clone a model with multiple inheritance levels, i.e. >= 2, or ModelC below

class ModelA(models.Model):
    info1 = models.CharField(max_length=64)

class ModelB(ModelA):
    info2 = models.CharField(max_length=64)

class ModelC(ModelB):
    info3 = models.CharField(max_length=64)

Please refer the question here.

Eliminate space before \begin{itemize}

Use \vspace{-\topsep} before \begin{itemize}.

Use \setlength{\parskip}{0pt} \setlength{\itemsep}{0pt plus 1pt} after \begin{itemize}.

And for the space after the list, use \vspace{-\topsep} after \end{itemize}.

\vspace{-\topsep}
\begin{itemize}
  \setlength{\parskip}{0pt}
  \setlength{\itemsep}{0pt plus 1pt}
  \item ...
  \item ...
\end{itemize}
\vspace{-\topsep}

Convert pandas.Series from dtype object to float, and errors to nans

Use pd.to_numeric with errors='coerce'

# Setup
s = pd.Series(['1', '2', '3', '4', '.'])
s

0    1
1    2
2    3
3    4
4    .
dtype: object

pd.to_numeric(s, errors='coerce')

0    1.0
1    2.0
2    3.0
3    4.0
4    NaN
dtype: float64

If you need the NaNs filled in, use Series.fillna.

pd.to_numeric(s, errors='coerce').fillna(0, downcast='infer')

0    1
1    2
2    3
3    4
4    0
dtype: float64

Note, downcast='infer' will attempt to downcast floats to integers where possible. Remove the argument if you don't want that.

From v0.24+, pandas introduces a Nullable Integer type, which allows integers to coexist with NaNs. If you have integers in your column, you can use

pd.__version__
# '0.24.1'

pd.to_numeric(s, errors='coerce').astype('Int32')

0      1
1      2
2      3
3      4
4    NaN
dtype: Int32

There are other options to choose from as well, read the docs for more.


Extension for DataFrames

If you need to extend this to DataFrames, you will need to apply it to each row. You can do this using DataFrame.apply.

# Setup.
np.random.seed(0)
df = pd.DataFrame({
    'A' : np.random.choice(10, 5), 
    'C' : np.random.choice(10, 5), 
    'B' : ['1', '###', '...', 50, '234'], 
    'D' : ['23', '1', '...', '268', '$$']}
)[list('ABCD')]
df

   A    B  C    D
0  5    1  9   23
1  0  ###  3    1
2  3  ...  5  ...
3  3   50  2  268
4  7  234  4   $$

df.dtypes

A     int64
B    object
C     int64
D    object
dtype: object

df2 = df.apply(pd.to_numeric, errors='coerce')
df2

   A      B  C      D
0  5    1.0  9   23.0
1  0    NaN  3    1.0
2  3    NaN  5    NaN
3  3   50.0  2  268.0
4  7  234.0  4    NaN

df2.dtypes

A      int64
B    float64
C      int64
D    float64
dtype: object

You can also do this with DataFrame.transform; although my tests indicate this is marginally slower:

df.transform(pd.to_numeric, errors='coerce')

   A      B  C      D
0  5    1.0  9   23.0
1  0    NaN  3    1.0
2  3    NaN  5    NaN
3  3   50.0  2  268.0
4  7  234.0  4    NaN

If you have many columns (numeric; non-numeric), you can make this a little more performant by applying pd.to_numeric on the non-numeric columns only.

df.dtypes.eq(object)

A    False
B     True
C    False
D     True
dtype: bool

cols = df.columns[df.dtypes.eq(object)]
# Actually, `cols` can be any list of columns you need to convert.
cols
# Index(['B', 'D'], dtype='object')

df[cols] = df[cols].apply(pd.to_numeric, errors='coerce')
# Alternatively,
# for c in cols:
#     df[c] = pd.to_numeric(df[c], errors='coerce')

df

   A      B  C      D
0  5    1.0  9   23.0
1  0    NaN  3    1.0
2  3    NaN  5    NaN
3  3   50.0  2  268.0
4  7  234.0  4    NaN

Applying pd.to_numeric along the columns (i.e., axis=0, the default) should be slightly faster for long DataFrames.

Compare two columns using pandas

You can use .equals for columns or entire dataframes.

df['col1'].equals(df['col2'])

If they're equal, that statement will return True, else False.

Slack clean all messages (~8K) in a channel

I wrote a simple node script for deleting messages from public/private channels and chats. You can modify and use it.

https://gist.github.com/firatkucuk/ee898bc919021da621689f5e47e7abac

First, modify your token in the scripts configuration section then run the script:

node ./delete-slack-messages CHANNEL_ID

Get an OAuth token:

  1. Go to https://api.slack.com/apps
  2. Click 'Create New App', and name your (temporary) app.
  3. In the side nav, go to 'Oauth & Permissions'
  4. On that page, find the 'Scopes' section. Click 'Add an OAuth Scope' and add 'channels:history' and 'chat:write'. (see scopes)
  5. At the top of the page, Click 'Install App to Workspace'. Confirm, and on page reload, copy the OAuth Access Token.

Find the channel ID

Also, the channel ID can be seen in the browser URL when you open slack in the browser. e.g.

https://mycompany.slack.com/messages/MY_CHANNEL_ID/

or

https://app.slack.com/client/WORKSPACE_ID/MY_CHANNEL_ID

Do you (really) write exception safe code?

I try my darned best to write exception-safe code, yes.

That means I take care to keep an eye on which lines can throw. Not everyone can, and it is critically important to keep that in mind. The key is really to think about, and design your code to satisfy, the exception guarantees defined in the standard.

Can this operation be written to provide the strong exception guarantee? Do I have to settle for the basic one? Which lines may throw exceptions, and how can I ensure that if they do, they don't corrupt the object?

Format ints into string of hex

Just for completeness, using the modern .format() syntax:

>>> numbers = [1, 15, 255]
>>> ''.join('{:02X}'.format(a) for a in numbers)
'010FFF'

Environment variable substitution in sed

Another easy alternative:

Since $PWD will usually contain a slash /, use | instead of / for the sed statement:

sed -e "s|xxx|$PWD|"

Error 6 (net::ERR_FILE_NOT_FOUND): The files c or directory could not be found

The below are the typical situation where we shall get ERR_FILE_NOT_FOUND even file avail in respective folder.

Code:
@font-face {
    font-family: Eau_Sans_Bold;
    src: url("/fonts/eau_sans_bold.otf") format("opentype");
}
Error:
 GET file:///C:/fonts/eau_sans_bold.otf net::ERR_FILE_NOT_FOUND

Answer or Solution.:
@font-face {
    font-family: Eau_Sans_Book;
    src: url("../fonts/eau_sans_book.otf") format("opentype");  
}

Basically browser not able to pick if we metion just /font/. We should to mention ../fonts/ This will work. So, we wont get ERR_FILE_NOT_FOUND.

Input mask for numeric and decimal

Try imaskjs. It has Number, RegExp and other masks. Very simple to extend.

How do you receive a url parameter with a spring controller mapping

You should be using @RequestParam instead of @ModelAttribute, e.g.

@RequestMapping("/{someID}")
public @ResponseBody int getAttr(@PathVariable(value="someID") String id, 
                                 @RequestParam String someAttr) {
}

You can even omit @RequestParam altogether if you choose, and Spring will assume that's what it is:

@RequestMapping("/{someID}")
public @ResponseBody int getAttr(@PathVariable(value="someID") String id, 
                                 String someAttr) {
}

C# Macro definitions in Preprocessor

While you can't write macros, when it comes to simplifying things like your example, C# 6.0 now offers static usings. Here's the example Martin Pernica gave on his Medium article:

using static System.Console; // Note the static keyword

namespace CoolCSharp6Features
{
  public class Program
  {
    public static int Main(string[] args)
    {
      WriteLine("Hellow World without Console class name prefix!");

      return 0;
    }
  }
}

Could not reserve enough space for object heap to start JVM

It looks like the machine you're trying to run this on has only 256 MB memory.

Maybe the JVM tries to allocate a large, contiguous block of 64 MB memory. The 192 MB that you have free might be fragmented into smaller pieces, so that there is no contiguous block of 64 MB free to allocate.

Try starting your Java program with a smaller heap size, for example:

java -Xms16m ...

jQuery : select all element with custom attribute

Use the "has attribute" selector:

$('p[MyTag]')

Or to select one where that attribute has a specific value:

$('p[MyTag="Sara"]')

There are other selectors for "attribute value starts with", "attribute value contains", etc.

Normalize data in pandas

Slightly modified from: Python Pandas Dataframe: Normalize data between 0.01 and 0.99? but from some of the comments thought it was relevant (sorry if considered a repost though...)

I wanted customized normalization in that regular percentile of datum or z-score was not adequate. Sometimes I knew what the feasible max and min of the population were, and therefore wanted to define it other than my sample, or a different midpoint, or whatever! This can often be useful for rescaling and normalizing data for neural nets where you may want all inputs between 0 and 1, but some of your data may need to be scaled in a more customized way... because percentiles and stdevs assumes your sample covers the population, but sometimes we know this isn't true. It was also very useful for me when visualizing data in heatmaps. So i built a custom function (used extra steps in the code here to make it as readable as possible):

def NormData(s,low='min',center='mid',hi='max',insideout=False,shrinkfactor=0.):    
    if low=='min':
        low=min(s)
    elif low=='abs':
        low=max(abs(min(s)),abs(max(s)))*-1.#sign(min(s))
    if hi=='max':
        hi=max(s)
    elif hi=='abs':
        hi=max(abs(min(s)),abs(max(s)))*1.#sign(max(s))

    if center=='mid':
        center=(max(s)+min(s))/2
    elif center=='avg':
        center=mean(s)
    elif center=='median':
        center=median(s)

    s2=[x-center for x in s]
    hi=hi-center
    low=low-center
    center=0.

    r=[]

    for x in s2:
        if x<low:
            r.append(0.)
        elif x>hi:
            r.append(1.)
        else:
            if x>=center:
                r.append((x-center)/(hi-center)*0.5+0.5)
            else:
                r.append((x-low)/(center-low)*0.5+0.)

    if insideout==True:
        ir=[(1.-abs(z-0.5)*2.) for z in r]
        r=ir

    rr =[x-(x-0.5)*shrinkfactor for x in r]    
    return rr

This will take in a pandas series, or even just a list and normalize it to your specified low, center, and high points. also there is a shrink factor! to allow you to scale down the data away from endpoints 0 and 1 (I had to do this when combining colormaps in matplotlib:Single pcolormesh with more than one colormap using Matplotlib) So you can likely see how the code works, but basically say you have values [-5,1,10] in a sample, but want to normalize based on a range of -7 to 7 (so anything above 7, our "10" is treated as a 7 effectively) with a midpoint of 2, but shrink it to fit a 256 RGB colormap:

#In[1]
NormData([-5,2,10],low=-7,center=1,hi=7,shrinkfactor=2./256)
#Out[1]
[0.1279296875, 0.5826822916666667, 0.99609375]

It can also turn your data inside out... this may seem odd, but I found it useful for heatmapping. Say you want a darker color for values closer to 0 rather than hi/low. You could heatmap based on normalized data where insideout=True:

#In[2]
NormData([-5,2,10],low=-7,center=1,hi=7,insideout=True,shrinkfactor=2./256)
#Out[2]
[0.251953125, 0.8307291666666666, 0.00390625]

So now "2" which is closest to the center, defined as "1" is the highest value.

Anyways, I thought my application was relevant if you're looking to rescale data in other ways that could have useful applications to you.

Java Equivalent of C# async/await?

Java doesn't have direct equivalent of C# language feature called async/await, however there's a different approach to the problem that async/await tries to solve. It's called project Loom, which will provide virtual threads for high-throughput concurrency. It will be available in some future version of OpenJDK.

This approach also solves "colored function problem" that async/await has.

Similar feature can be also found in Golang (goroutines).

How can I create directories recursively?

Try using os.makedirs:

import os
import errno

try:
    os.makedirs(<path>)
except OSError as e:
    if errno.EEXIST != e.errno:
        raise

Tips for debugging .htaccess rewrite rules

Set environment variables and use headers to receive them:

You can create new environment variables with RewriteRule lines, as mentioned by OP:

RewriteRule ^(.*) - [E=TEST0:%{DOCUMENT_ROOT}/blog/html_cache/$1.html]

But if you can't get a server-side script to work, how can you then read this environment variable? One solution is to set a header:

Header set TEST_FOOBAR "%{REDIRECT_TEST0}e"

The value accepts format specifiers, including the %{NAME}e specifier for environment variables (don't forget the lowercase e). Sometimes, you'll need to add the REDIRECT_ prefix, but I haven't worked out when the prefix gets added and when it doesn't.

How to change onClick handler dynamically?

Here is the YUI counterpart to the jQuery posts above.

<script>
  YAHOO.util.Event.onDOMReady(function() {   
    document.getElementById("foo").onclick =  function (){alert('foo');};
  });
</script>

How to declare a global variable in React?

The best way I have found so far is to use React Context but to isolate it inside a high order provider component.

PHP combine two associative arrays into one array

There is also array_replace, where an original array is modified by other arrays preserving the key => value association without creating duplicate keys.

  • Same keys on other arrays will cause values to overwrite the original array
  • New keys on other arrays will be created on the original array

Trim characters in Java

My solution:

private static String trim(String string, String charSequence) {
        var str = string;
        str = str.replace(" ", "$SAVE_SPACE$").
                  replace(charSequence, " ").
                  trim().
                  replace(" ", charSequence).
                  replace("$SAVE_SPACE$", " ");
        return str;
    }

Encode String to UTF-8

I have use below code to encode the special character by specifying encode format.

String text = "This is an example é";
byte[] byteText = text.getBytes(Charset.forName("UTF-8"));
//To get original string from byte.
String originalString= new String(byteText , "UTF-8");

CSS Cell Margin

margin does not work unfortunately on individual cells, however you could add extra columns between the two cells you want to put a space between... another option is to use a border with the same colour as the background...

Given URL is not allowed by the Application configuration Facebook application error

1.Make Sure Website Url and platform added, if not then visit https://developers.facebook.com/quickstarts/ then Select Platform -> Setup SDK -> Website Url And so on..

Note: website url can't be like this : https://www.example.com just remove www and make it simple and working ;)

2.Goto App Dashboard -> Setting -> Click on Advanced Tab then go to bottom of the page and enable Embedded Browser OAuth Login and leave Valid OAuth redirect URIs blank and Save it

How to use protractor to check if an element is visible?

This answer will be robust enough to work for elements that aren't on the page, therefore failing gracefully (not throwing an exception) if the selector failed to find the element.

const nameSelector = '[data-automation="name-input"]';
const nameInputIsDisplayed = () => {
    return $$(nameSelector).count()
        .then(count => count !== 0)
}
it('should be displayed', () => {
    nameInputIsDisplayed().then(isDisplayed => {
        expect(isDisplayed).toBeTruthy()
    })
})

Is there any difference between GROUP BY and DISTINCT

I know it's an old post. But it happens that I had a query that used group by just to return distinct values when using that query in toad and oracle reports everything worked fine, I mean a good response time. When we migrated from Oracle 9i to 11g the response time in Toad was excellent but in the reporte it took about 35 minutes to finish the report when using previous version it took about 5 minutes.

The solution was to change the group by and use DISTINCT and now the report runs in about 30 secs.

I hope this is useful for someone with the same situation.

Oracle 10g: Extract data (select) from XML (CLOB Type)

In case the XML store in the CLOB field in the database table. E.g for this XML:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Awmds>
    <General_segment>
        <General_segment_id>
        <Customs_office_code>000</Customs_office_code>
    </General_segment_id>
</General_segment>
</Awmds>

This is the Extract Query:

SELECT EXTRACTVALUE (
    xmltype (T.CLOB_COLUMN_NAME),
    '/Awmds/General_segment/General_segment_id/Customs_office_code')
    AS Customs_office_code
FROM TABLE_NAME t;

How to extend a class in python?

class MyParent:

    def sayHi():
        print('Mamma says hi')
from path.to.MyParent import MyParent

class ChildClass(MyParent):
    pass

An instance of ChildClass will then inherit the sayHi() method.

Do sessions really violate RESTfulness?

HTTP transaction, basic access authentication, is not suitable for RBAC, because basic access authentication uses the encrypted username:password every time to identify, while what is needed in RBAC is the Role the user wants to use for a specific call. RBAC does not validate permissions on username, but on roles.

You could tric around to concatenate like this: usernameRole:password, but this is bad practice, and it is also inefficient because when a user has more roles, the authentication engine would need to test all roles in concatenation, and that every call again. This would destroy one of the biggest technical advantages of RBAC, namely a very quick authorization-test.

So that problem cannot be solved using basic access authentication.

To solve this problem, session-maintaining is necessary, and that seems, according to some answers, in contradiction with REST.

That is what I like about the answer that REST should not be treated as a religion. In complex business cases, in healthcare, for example, RBAC is absolutely common and necessary. And it would be a pity if they would not be allowed to use REST because all REST-tools designers would treat REST as a religion.

For me there are not many ways to maintain a session over HTTP. One can use cookies, with a sessionId, or a header with a sessionId.

If someone has another idea I will be glad to hear it.

View not attached to window manager crash

May be you initialize pDialog globally, Then remove it and intialize your view or dialog locally.I have same issue, I have done this and my issue is resolved. Hope it will work for u.

How could I use requests in asyncio?

Requests does not currently support asyncio and there are no plans to provide such support. It's likely that you could implement a custom "Transport Adapter" (as discussed here) that knows how to use asyncio.

If I find myself with some time it's something I might actually look into, but I can't promise anything.

OS X cp command in Terminal - No such file or directory

In my case, I had accidentally named a folder 'samples '. I couldn't see the space when I did 'ls -la'.

Eventually I realized this when I tried tabbing to autocomplete and saw 'samples\ /'.

To fix this I ran

mv samples\  samples

How to compile and run C in sublime text 3?

The code that worked for me on a Windows 10 machine using Sublime Text 3

 {
 "cmd" : "gcc $file_name -o ${file_base_name}",
 "selector" : "source.c",
 "shell" : true,
 "working_dir" : "$file_path",
 "variants":
    [
     {
      "name": "Run",
      "cmd": "${file_base_name}"
     }
   ]
}

Why is this program erroneously rejected by three C++ compilers?

Is your compiler set in expert mode?! If yes, it shouldn't compile. Modern compilers are tired of "Hello World!"

How to get the CPU Usage in C#?

CMS has it right, but also if you use the server explorer in visual studio and play around with the performance counter tab then you can figure out how to get lots of useful metrics.

How to read user input into a variable in Bash?

Use read -p:

# fullname="USER INPUT"
read -p "Enter fullname: " fullname
# user="USER INPUT"
read -p "Enter user: " user

If you like to confirm:

read -p "Continue? (Y/N): " confirm && [[ $confirm == [yY] || $confirm == [yY][eE][sS] ]] || exit 1

You should also quote your variables to prevent pathname expansion and word splitting with spaces:

# passwd "$user"
# mkdir "$home"
# chown "$user:$group" "$home"

HTML Input - already filled in text

You seem to look for the input attribute value, "the initial value of the control"?

<input type="text" value="Morlodenhof 7" />

https://developer.mozilla.org/de/docs/Web/HTML/Element/Input#attr-value

How to break out from foreach loop in javascript

Use a for loop instead of .forEach()

var myObj = [{"a": "1","b": null},{"a": "2","b": 5}]
var result = false

for(var call of myObj) {
    console.log(call)
    
    var a = call['a'], b = call['b']
     
    if(a == null || b == null) {
        result = false
        break
    }
}

Django Reverse with arguments '()' and keyword arguments '{}' not found

You have to specify project_id:

reverse('edit_project', kwargs={'project_id':4})

Doc here

How can I read numeric strings in Excel cells as string (not numbers)?

The below code worked for me for any type of cell.

InputStream inp =getClass().getResourceAsStream("filename.xls"));
Workbook wb = WorkbookFactory.create(inp);
DataFormatter objDefaultFormat = new DataFormatter();
FormulaEvaluator objFormulaEvaluator = new HSSFFormulaEvaluator((HSSFWorkbook) wb);

Sheet sheet= wb.getSheetAt(0);
Iterator<Row> objIterator = sheet.rowIterator();

while(objIterator.hasNext()){

    Row row = objIterator.next();
    Cell cellValue = row.getCell(0);
    objFormulaEvaluator.evaluate(cellValue); // This will evaluate the cell, And any type of cell will return string value
    String cellValueStr = objDefaultFormat.formatCellValue(cellValue,objFormulaEvaluator);

}

How to specify a multi-line shell variable?

I would like to give one additional answer, while the other ones will suffice in most cases.

I wanted to write a string over multiple lines, but its contents needed to be single-line.

sql="                       \
SELECT c1, c2               \
from Table1, ${TABLE2}      \
where ...                   \
"

I am sorry if this if a bit off-topic (I did not need this for SQL). However, this post comes up among the first results when searching for multi-line shell variables and an additional answer seemed appropriate.

Sorting an ArrayList of objects using a custom sorting order

You shoud use the Arrays.sort function. The containing classes should implement Comparable.

Why am I getting "Thread was being aborted" in ASP.NET?

I got this error when I did a Response.Redirect after a successful login of the user.

I fixed it by doing a FormsAuthentication.RedirectFromLoginPage instead.

Relative imports in Python 3

I had a similar problem and solved it by creating a symbolic link to the package in the working directory:

ln -s ../../../my_package my_package

and then import it as usual:

import my_package

I know this is more like a "Linux" solution rather than a "Python" solution. but it's a valid approach nonetheless.

How to check how many letters are in a string in java?

If you are counting letters, the above solution will fail for some unicode symbols. For example for these 5 characters sample.length() will return 6 instead of 5:

String sample = "\u760c\u0444\u03b3\u03b5\ud800\udf45"; // ???e

The codePointCount function was introduced in Java 1.5 and I understand gives better results for glyphs etc

sample.codePointCount(0, sample.length()) // returns 5

http://globalizer.wordpress.com/2007/01/16/utf-8-and-string-length-limitations/

Android SQLite SELECT Query

Try trimming the string to make sure there is no extra white space:

Cursor c = db.rawQuery("SELECT * FROM tbl1 WHERE TRIM(name) = '"+name.trim()+"'", null);

Also use c.moveToFirst() like @thinksteep mentioned.


This is a complete code for select statements.

SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("SELECT column1,column2,column3 FROM table ", null);
if (c.moveToFirst()){
    do {
        // Passing values 
        String column1 = c.getString(0);
        String column2 = c.getString(1);
        String column3 = c.getString(2); 
        // Do something Here with values
    } while(c.moveToNext());
}
c.close();
db.close();

How to install maven on redhat linux

Go to mirror.olnevhost.net/pub/apache/maven/binaries/ and check what is the latest tar.gz file

Supposing it is e.g. apache-maven-3.2.1-bin.tar.gz, from the command line; you should be able to simply do:

wget http://mirror.olnevhost.net/pub/apache/maven/binaries/apache-maven-3.2.1-bin.tar.gz

And then proceed to install it.

UPDATE: Adding complete instructions (copied from the comment below)

  1. Run command above from the dir you want to extract maven to (e.g. /usr/local/apache-maven)
  2. run the following to extract the tar:

    tar xvf apache-maven-3.2.1-bin.tar.gz
    
  3. Next add the env varibles such as

    export M2_HOME=/usr/local/apache-maven/apache-maven-3.2.1

    export M2=$M2_HOME/bin

    export PATH=$M2:$PATH

  4. Verify

    mvn -version
    

Compiling problems: cannot find crt1.o

If you're using Debian's Testing version, called 'wheezy', then you may have been bitten by the move to multiarch. More about Debian's multiarch here: http://wiki.debian.org/Multiarch

Basically, what is happening is various architecture specific libraries are being moved from traditional places in the file system to new architecture specific places. This is why /usr/bin/ld is confused.

You will find crt1.o in both /usr/lib64/ and /usr/lib/i386-linux-gnu/ now and you'll need to tell your toolchain about that. Here is some documentation on how to do that; http://wiki.debian.org/Multiarch/LibraryPathOverview

Note that merely creating a symlink will only give you one architecture and you'd be essentially disabling multiarch. While this may be what you want it might not be the optimal solution.

How to solve npm error "npm ERR! code ELIFECYCLE"

Usually killall node command fixes mine.

Removing NA observations with dplyr::filter()

From @Ben Bolker:

[T]his has nothing specifically to do with dplyr::filter()

From @Marat Talipov:

[A]ny comparison with NA, including NA==NA, will return NA

From a related answer by @farnsy:

The == operator does not treat NA's as you would expect it to.

Think of NA as meaning "I don't know what's there". The correct answer to 3 > NA is obviously NA because we don't know if the missing value is larger than 3 or not. Well, it's the same for NA == NA. They are both missing values but the true values could be quite different, so the correct answer is "I don't know."

R doesn't know what you are doing in your analysis, so instead of potentially introducing bugs that would later end up being published an embarrassing you, it doesn't allow comparison operators to think NA is a value.

psql: FATAL: Ident authentication failed for user "postgres"

I've spent more time solving this error that I care to admit.

The order of authentication configuration in pg_hba.conf is relevant in your case I think. The default configuration file includes several lines in a vanilla install. These defaults can match the conditions of your authentication attempts resulting in a failure to authenticate. It fails regardless of additional configuration added at the end of the .conf file.

To check which line of configuration is use make sure to look at the default log file for messages. You might see something like this

LOG:  could not connect to Ident server at address "127.0.0.1", port 113: Connection refused
FATAL:  Ident authentication failed for user "acme" 
DETAIL:  Connection matched pg_hba.conf line 82: "host     all             all             127.0.0.1/32            ident"

It turns out this default line is causing the rejection.

host    all             all             127.0.0.1/32            ident

try commenting it out.

How to draw a standard normal distribution in R

Something like this perhaps?

x<-rnorm(100000,mean=10, sd=2)
hist(x,breaks=150,xlim=c(0,20),freq=FALSE)
abline(v=10, lwd=5)
abline(v=c(4,6,8,12,14,16), lwd=3,lty=3)

How to comment lines in rails html.erb files?

Note that if you want to comment out a single line of printing erb you should do like this

<%#= ["Buck", "Papandreou"].join(" you ") %>

How to iterate through table in Lua?

All the answers here suggest to use ipairs but beware, it does not work all the time.

t = {[2] = 44, [4]=77, [6]=88}

--This for loop prints the table
for key,value in next,t,nil do 
  print(key,value) 
end

--This one does not print the table
for key,value in ipairs(t) do 
  print(key,value) 
end

initialize a vector to zeros C++/C++11

Initializing a vector having struct, class or Union can be done this way

std::vector<SomeStruct> someStructVect(length);
memset(someStructVect.data(), 0, sizeof(SomeStruct)*length);

How to make MySQL handle UTF-8 properly

To make this 'permanent', in my.cnf:

[client]
default-character-set=utf8
[mysqld]
character-set-server = utf8

To check, go to the client and show some variables:

SHOW VARIABLES LIKE 'character_set%';

Verify that they're all utf8, except ..._filesystem, which should be binary and ..._dir, that points somewhere in the MySQL installation.

maven compilation failure

You could try running the "mvn site" command and see what transitive dependencies you have, and then resolve potential conflicts (by ommitting an implicit dependency somewhere). Just a guess (it's a bit difficult to know what the problem could be without seeing your pom info)...

Default username password for Tomcat Application Manager

First navigate to below location and open it in a text editor

<TOMCAT_HOME>/conf/tomcat-users.xml

For tomcat 7, Add the following xml code somewhere between <tomcat-users> I find the following solution.

  <role rolename="manager-gui"/>
  <user username="username" password="password" roles="manager-gui"/>

Now restart the tomcat server.

How to make an input type=button act like a hyperlink and redirect using a get request?

You can make <button> tag to do action like this:

<a href="http://www.google.com/">
   <button>Visit Google</button>
</a>

or:

<a href="http://www.google.com/">
   <input type="button" value="Visit Google" />
</a>

It's simple and no javascript required!


NOTE:

This approach is not valid from HTML structure. But, it works on many modern browser. See following reference :

Javascript sleep/delay/wait function

You cannot just put in a function to pause Javascript unfortunately.

You have to use setTimeout()

Example:

function startTimer () {
    timer.start();
    setTimeout(stopTimer,5000);
}

function stopTimer () {
    timer.stop();
}

EDIT:

For your user generated countdown, it is just as simple.

HTML:

<input type="number" id="delay" min="1" max="5">

JS:

var delayInSeconds = parseInt(delay.value);
var delayInMilliseconds = delayInSeconds*1000;

function startTimer () {
    timer.start();
    setTimeout(stopTimer,delayInMilliseconds);
}

function stopTimer () {
    timer.stop;
}

Now you simply need to add a trigger for startTimer(), such as onchange.

Perform commands over ssh with Python

You can use any of these commands, this will help you to give a password also.

cmd = subprocess.run(["sshpass -p 'password' ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null [email protected] ps | grep minicom"], shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
print(cmd.stdout)
OR
cmd = subprocess.getoutput("sshpass -p 'password' ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null [email protected] ps | grep minicom")
print(cmd)

Base table or view not found: 1146 Table Laravel 5

Check your migration file, maybe you are using Schema::table, like this:

Schema::table('table_name', function ($table)  {
    // ...
});

If you want to create a new table you must use Schema::create:

Schema::create('table_name', function ($table)  {
    // ...
});

How do I escape a single quote ( ' ) in JavaScript?

The answer here is very simple:

You're already containing it in double quotes, so there's no need to escape it with \.

If you want to escape single quotes in a single quote string:

var string = 'this isn\'t a double quoted string';
var string = "this isn\"t a single quoted string";
//           ^         ^ same types, hence we need to escape it with a backslash

or if you want to escape \', you can escape the bashslash to \\ and the quote to \' like so:

var string = 'this isn\\\'t a double quoted string';
//                    vvvv
//                     \ ' (the escaped characters)

However, if you contain the string with a different quote type, you don't need to escape:

var string = 'this isn"t a double quoted string';
var string = "this isn't a single quoted string";
//           ^        ^ different types, hence we don't need escaping

Why does calling sumr on a stream with 50 tuples not complete

sumr is implemented in terms of foldRight:

 final def sumr(implicit A: Monoid[A]): A = F.foldRight(self, A.zero)(A.append) 

foldRight is not always tail recursive, so you can overflow the stack if the collection is too long. See Why foldRight and reduceRight are NOT tail recursive? for some more discussion of when this is or isn't true.

Split array into chunks of N length

Maybe this code helps:

_x000D_
_x000D_
var chunk_size = 10;_x000D_
var arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17];_x000D_
var groups = arr.map( function(e,i){ _x000D_
     return i%chunk_size===0 ? arr.slice(i,i+chunk_size) : null; _x000D_
}).filter(function(e){ return e; });_x000D_
console.log({arr, groups})
_x000D_
_x000D_
_x000D_

java.lang.IllegalStateException: Error processing condition on org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration

This error is because of multiple project having the offending resources.

Try out adding the dependencies projects other way around. (like in pom.xml or external depandancies)

enter image description here

Unable to install gem - Failed to build gem native extension - cannot load such file -- mkmf (LoadError)

After some search for a solution, it turns out the -dev package is needed, not just ruby1.8. So if you have ruby1.9.1 doing

sudo apt-get install ruby1.9.1-dev

or to install generic ruby version, use (as per @lamplightdev comment):

sudo apt-get install ruby-dev

should fix it.

Try to locate mkmf to see if the file is actually there.

Why is there no String.Empty in Java?

If you want to compare with empty string without worrying about null values you can do the following.

if ("".equals(text))

Ultimately you should do what what you believe is clearest. Most programmers assume "" means empty string, not a string someone forgot to put anything into.

If you think there is a performance advantage, you should test it. If you don't think its worth testing for yourself, its a good indication it really isn't worth it.

It sounds like to you try to solve a problem which was solved when the language was designed more than 15 years ago.

Why doesn't os.path.join() work in this case?

do it like this, without too the extra slashes

root="/home"
os.path.join(root,"build","test","sandboxes",todaystr,"new_sandbox")

Cannot make a static reference to the non-static method

There are some good answers already with explanations of why the mixture of the non-static Context method getText() can't be used with your static final String.

A good question to ask is: why do you want to do this? You are attempting to load a String from your strings resource, and populate its value into a public static field. I assume that this is so that some of your other classes can access it? If so, there is no need to do this. Instead pass a Context into your other classes and call context.getText(R.string.TTT) from within them.

public class NonActivity {

    public static void doStuff(Context context) {
        String TTT = context.getText(R.string.TTT);
        ...
    }
}

And to call this from your Activity:

NonActivity.doStuff(this);

This will allow you to access your String resource without needing to use a public static field.

Combine two arrays

This works:

$a = array(1 => 1, 2 => 2, 3 => 3);
$b = array(4 => 4, 5 => 5, 6 => 6);
$c = $a + $b;
print_r($c);

Setting the number of map tasks and reduce tasks

From your log I understood that you have 12 input files as there are 12 local maps generated. Rack Local maps are spawned for the same file if some of the blocks of that file are in some other data node. How many data nodes you have?

How do I center an SVG in a div?

Above answers did not work for me. Adding the attribute preserveAspectRatio="xMidYMin" to the <svg> tag did the trick though. The viewBox attribute needs to be specified for this to work as well. Source: Mozilla developer network

How to refer to relative paths of resources when working with a code repository

I got stumped here a bit. Wanted to package some resource files into a wheel file and access them. Did the packaging using manifest file, but pip install was not installing it unless it was a sub directory. Hoping these sceen shots will help

+-- cnn_client
¦   +-- image_preprocessor.py
¦   +-- __init__.py
¦   +-- resources
¦   ¦   +-- mscoco_complete_label_map.pbtxt
¦   ¦   +-- retinanet_complete_label_map.pbtxt
¦   ¦   +-- retinanet_label_map.py
¦   +-- tf_client.py

MANIFEST.in

recursive-include cnn_client/resources *

Created a weel using standard setup.py . pip installed the wheel file. After installation checked if resources are installed. They are

ls /usr/local/lib/python2.7/dist-packages/cnn_client/resources

mscoco_complete_label_map.pbtxt
retinanet_complete_label_map.pbtxt 
 retinanet_label_map.py  

In tfclient.py to access these files. from

templates_dir = os.path.join(os.path.dirname(__file__), 'resources')
 file_path = os.path.join(templates_dir, \
            'mscoco_complete_label_map.pbtxt')
        s = open(file_path, 'r').read()

And it works.

Creating a Custom Event

Yes you can create events on objects, here is an example;

public class Foo
{
    public delegate void MyEvent(object sender, object param);
    event MyEvent OnMyEvent;

    public Foo()
    {
        this.OnMyEvent += new MyEvent(Foo_OnMyEvent);
    }

    void Foo_OnMyEvent(object sender, object param)
    {
        if (this.OnMyEvent != null)
        {
            //do something
        }
    }



    void RaiseEvent()
    {
        object param = new object();
        this.OnMyEvent(this,param);
    }
}

How to make a vertical SeekBar in Android?

You can do it by yourself - it's now so difficult. Here is an example from my project: https://github.com/AlShevelev/WizardCamera

Let start from settings (attrs.xml).

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="ExpositionBar">
        <attr name="button_icon" format="reference" />
        <attr name="button_icon_size" format="dimension" />

        <attr name="stroke_width" format="dimension" />

        <attr name="stroke_color" format="color" />
        <attr name="button_color" format="color" />
        <attr name="button_color_pressed" format="color" />

        <attr name="min_value" format="float" />
        <attr name="max_value" format="float" />
    </declare-styleable>
</resources>

Here is a couple of utility functions:

fun <T: Comparable<T>>T.fitInRange(range: Range<T>): T =
    when {
        this < range.lower -> range.lower
        this > range.upper -> range.upper
        else -> this
    }

fun Float.reduceToRange(rangeFrom: Range<Float>, rangeTo: Range<Float>): Float =
    when {
        this == rangeFrom.lower -> rangeTo.lower
        this == rangeFrom.upper -> rangeTo.upper
        else -> {
            val placeInRange = (this - rangeFrom.lower) / (rangeFrom.upper - rangeFrom.lower)
            ((rangeTo.upper - rangeTo.lower) * placeInRange) + rangeTo.lower
        }
    }

And at last, but not least - a class for vertical seek bar:

class ExpositionBar
@JvmOverloads
constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    private val drawingRect = RectF(0f, 0f, 0f, 0f)
    private val drawingPaint = Paint(Paint.ANTI_ALIAS_FLAG)

    private val strokeWidth: Float

    @ColorInt
    private val strokeColor: Int
    @ColorInt
    private val buttonFillColor: Int
    @ColorInt
    private val buttonFillColorPressed: Int

    private val icon: VectorDrawable

    private val valuesRange: Range<Float>

    private var centerX = 0f
    private var minY = 0f
    private var maxY = 0f

    private var buttonCenterY = 0f
    private var buttonRadiusExt = 0f
    private var buttonRadiusInt = 0f
    private var buttonMinY = 0f
    private var buttonMaxY = 0f
    private var buttonCenterBoundsRange = Range(0f, 0f)

    private var iconTranslationX = 0f
    private var iconTranslationY = 0f

    private var isInDragMode = false

    private var onValueChangeListener: ((Float) -> Unit)? = null

    private var oldOutputValue = Float.MIN_VALUE

    init {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.ExpositionBar)

        icon =  typedArray.getDrawable(R.styleable.ExpositionBar_button_icon) as VectorDrawable
        val iconSize = typedArray.getDimensionPixelSize(R.styleable.ExpositionBar_button_icon_size, 0)
        icon.setBounds(0, 0, iconSize, iconSize)

        strokeWidth = typedArray.getDimensionPixelSize(R.styleable.ExpositionBar_stroke_width, 0).toFloat()
        drawingPaint.strokeWidth = strokeWidth

        strokeColor = typedArray.getColor(R.styleable.ExpositionBar_stroke_color, Color.WHITE)
        buttonFillColor = typedArray.getColor(R.styleable.ExpositionBar_button_color, Color.BLACK)
        buttonFillColorPressed = typedArray.getColor(R.styleable.ExpositionBar_button_color_pressed, Color.BLUE)

        val minValue = typedArray.getFloat(R.styleable.ExpositionBar_min_value, 0f)
        val maxValue = typedArray.getFloat(R.styleable.ExpositionBar_max_value, 0f)
        valuesRange = Range(minValue, maxValue)

        typedArray.recycle()
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)

        drawingRect.right = width.toFloat()
        drawingRect.bottom = height.toFloat()

        buttonCenterY = drawingRect.centerY()

        recalculateDrawingValues()
    }

    override fun onDraw(canvas: Canvas) {
        drawingPaint.color = strokeColor
        drawingPaint.style = Paint.Style.STROKE

        // Draw the center line
        canvas.drawLine(centerX, minY, centerX, buttonMinY, drawingPaint)
        canvas.drawLine(centerX, buttonMaxY, centerX, maxY, drawingPaint)

        // Draw the button
        canvas.drawCircle(centerX, buttonCenterY, buttonRadiusExt, drawingPaint)
        drawingPaint.style = Paint.Style.FILL
        drawingPaint.color = if(isInDragMode) buttonFillColorPressed else buttonFillColor
        canvas.drawCircle(centerX, buttonCenterY, buttonRadiusInt, drawingPaint)

        // Draw button icon
        canvas.translate(iconTranslationX, iconTranslationY)
        icon.draw(canvas)
        canvas.translate(-iconTranslationX, -iconTranslationY)
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun onTouchEvent(event: MotionEvent): Boolean {
        if(!isEnabled) {
            return false
        }

        when(event.actionMasked) {
            MotionEvent.ACTION_DOWN -> {
                if(isButtonHit(event.y)){
                    isInDragMode = true
                    invalidate()
                }
            }
            MotionEvent.ACTION_MOVE -> {
                if(isInDragMode) {
                    buttonCenterY = event.y.fitInRange(buttonCenterBoundsRange)
                    recalculateDrawingValues()
                    invalidate()

                    val outputValue = buttonCenterY.reduceToRange(buttonCenterBoundsRange, valuesRange)
                    if (outputValue != oldOutputValue) {
                        onValueChangeListener?.invoke(outputValue)
                        oldOutputValue = outputValue
                    }
                }
            }
            MotionEvent.ACTION_UP,
            MotionEvent.ACTION_CANCEL -> {
                isInDragMode = false
                invalidate()
            }
        }
        return true
    }

    fun setOnValueChangeListener(listener: ((Float) -> Unit)?) {
        onValueChangeListener = listener
    }

    private fun recalculateDrawingValues() {
        centerX = drawingRect.left + drawingRect.width()/2
        minY = drawingRect.top
        maxY = drawingRect.bottom

        buttonRadiusExt = drawingRect.width() / 2 - strokeWidth / 2
        buttonRadiusInt = buttonRadiusExt - strokeWidth / 2
        buttonMinY = buttonCenterY - buttonRadiusExt
        buttonMaxY = buttonCenterY + buttonRadiusExt

        val buttonCenterMinY = minY + buttonRadiusExt + strokeWidth / 2
        val buttonCenterMaxY = maxY - buttonRadiusExt - strokeWidth / 2
        buttonCenterBoundsRange = Range(buttonCenterMinY, buttonCenterMaxY)

        iconTranslationX = centerX - icon.bounds.width() / 2
        iconTranslationY = buttonCenterY - icon.bounds.height() / 2
    }

    private fun isButtonHit(y: Float): Boolean {
        return y >= buttonMinY && y <= buttonMaxY
    }
}

You can use it as shown here:

<com.shevelev.wizard_camera.main_activity.view.widgets.ExpositionBar
    android:id="@+id/expositionBar"
    android:layout_width="@dimen/mainButtonSize"
    android:layout_height="300dp"
    android:layout_gravity="end|center_vertical"

    android:layout_marginEnd="@dimen/marginNormal"
    android:layout_marginBottom="26dp"

    app:button_icon = "@drawable/ic_brightness"
    app:button_icon_size = "@dimen/toolButtonIconSize"
    app:stroke_width = "@dimen/strokeWidthNormal"
    app:stroke_color = "@color/mainButtonsForeground"
    app:button_color = "@color/mainButtonsBackground"
    app:button_color_pressed = "@color/mainButtonsBackgroundPressed"
    app:min_value="-100"
    app:max_value="100"
/>

Voila!

XSLT getting last element

You need to put the last() indexing on the nodelist result, rather than as part of the selection criteria. Try:

(//element[@name='D'])[last()]

Why is the Visual Studio 2015/2017/2019 Test Runner not discovering my xUnit v2 tests

I have test project A and B. Tests in Project A where discovered but the Discovery never stopped for B. I had to manually kill TestHost to make stop.

I did a lot of things this page describes even to the point that I'm unsure as to wheter this was the solution.

Now it worked and the thing I did was to open the Solution and NOT have the Test Explorer up. Instead I just checked the Output window for Tests and I could see the discovery process end and the number of test where equal to A+B. After this, I opened the Test Explorer and then both A and B where present. So:

Uninstall and Install the latest xUnit stuff correctly. Delete the %temp% as mentioned above, Add NuGet Package "Microsoft.TestPlatform.TestHost" Add NuGet Package "Microsoft.NET.Test.Sdk", restart but only check the Tests Output. If it works u'll see

How to set default values for Angular 2 component properties?

Here is the best solution for this. (ANGULAR All Version)

Addressing solution: To set a default value for @Input variable. If no value passed to that input variable then It will take the default value.

I have provided solution for this kind of similar question. You can find the full solution from here

export class CarComponent implements OnInit {
  private _defaultCar: car = {
    // default isCar is true
    isCar: true,
    // default wheels  will be 4
    wheels: 4
  };

  @Input() newCar: car = {};

  constructor() {}

  ngOnInit(): void {

   // this will concate both the objects and the object declared later (ie.. ...this.newCar )
   // will overwrite the default value. ONLY AND ONLY IF DEFAULT VALUE IS PRESENT

    this.newCar = { ...this._defaultCar, ...this.newCar };
   //  console.log(this.newCar);
  }
}

What is the purpose of the vshost.exe file?

Adding on, you can turn off the creation of vshost files for your Release build configuration and have it enabled for Debug.

Steps

  • Project Properties > Debug > Configuration (Release) > Disable the Visual Studio hosting process
  • Project Properties > Debug > Configuration (Debug) > Enable the Visual Studio hosting process

Screenshot from VS2010

Reference

  1. MSDN How to: Disable the Hosting Process
  2. MSDN Hosting Process (vshost.exe)

Excerpt from MSDN How to: Disable the Hosting Process

Calls to certain APIs can be affected when the hosting process is enabled. In these cases, it is necessary to disable the hosting process to return the correct results.

To disable the hosting process

  1. Open an executable project in Visual Studio. Projects that do not produce executables (for example, class library or service projects) do not have this option.
  2. On the Project menu, click Properties.
  3. Click the Debug tab.
  4. Clear the Enable the Visual Studio hosting process check box.

When the hosting process is disabled, several debugging features are unavailable or experience decreased performance. For more information, see Debugging and the Hosting Process.

In general, when the hosting process is disabled:

  • The time needed to begin debugging .NET Framework applications increases.
  • Design-time expression evaluation is unavailable.
  • Partial trust debugging is unavailable.

phpMyAdmin - can't connect - invalid setings - ever since I added a root password - locked out

I'm one of the noob too when I encountered something like this. So... I set the passwords using the command security page gave me: /opt/lampp/lampp security Then I used password xyz for all the passwords... Then when I go to site/, it ask for a basic authentication. But when I tried root//xyz, it does not allow me login. So, after some digging, it turns out the xyz password was set for a default user named 'lampp'. When I tried to login using lampp//xyz, it worked like a charm.

The issue is that they made an assumption that everyone knows to use lampp//rootpw as their login o.O And... that is a basic auth for the directory! not pw for phpmyadmin or pw for mysql...

How to Get JSON Array Within JSON Object?

JSONObject jsonObject =new JSONObject(jsonStr);
JSONArray jsonArray = jsonObject.getJSONArray("data");
for(int i=0;i<jsonArray.length;i++){
    JSONObject json = jsonArray.getJSONObject(i);
    String id = json.getString("id");
    String name=json.getString("name");
    JSONArray ingArray = json.getJSONArray("Ingredients") // here you are going   to get ingredients
    for(int j=0;j<ingArray.length;j++){
        JSONObject ingredObject= ingArray.getJSONObject(j);
        String ingName = ingredObject.getString("name");//so you are going to get   ingredient name
        Log.e("name",ingName); // you will get 
   }
}

connect local repo with remote repo

git remote add origin <remote_repo_url>
git push --all origin

If you want to set all of your branches to automatically use this remote repo when you use git pull, add --set-upstream to the push:

git push --all --set-upstream origin

Cross-browser custom styling for file upload button

The best example is this one, No hiding, No jQuery, It's completely pure CSS

http://css-tricks.com/snippets/css/custom-file-input-styling-webkitblink/

_x000D_
_x000D_
.custom-file-input::-webkit-file-upload-button {_x000D_
    visibility: hidden;_x000D_
}_x000D_
_x000D_
.custom-file-input::before {_x000D_
    content: 'Select some files';_x000D_
    display: inline-block;_x000D_
    background: -webkit-linear-gradient(top, #f9f9f9, #e3e3e3);_x000D_
    border: 1px solid #999;_x000D_
    border-radius: 3px;_x000D_
    padding: 5px 8px;_x000D_
    outline: none;_x000D_
    white-space: nowrap;_x000D_
    -webkit-user-select: none;_x000D_
    cursor: pointer;_x000D_
    text-shadow: 1px 1px #fff;_x000D_
    font-weight: 700;_x000D_
    font-size: 10pt;_x000D_
}_x000D_
_x000D_
.custom-file-input:hover::before {_x000D_
    border-color: black;_x000D_
}_x000D_
_x000D_
.custom-file-input:active::before {_x000D_
    background: -webkit-linear-gradient(top, #e3e3e3, #f9f9f9);_x000D_
}
_x000D_
<input type="file" class="custom-file-input">
_x000D_
_x000D_
_x000D_

remove None value from a list without removing the 0 value

Say the list is like below

iterator = [None, 1, 2, 0, '', None, False, {}, (), []]

This will return only those items whose bool(item) is True

print filter(lambda item: item, iterator)
# [1, 2]

This is equivalent to

print [item for item in iterator if item]

To just filter None:

print filter(lambda item: item is not None, iterator)
# [1, 2, 0, '', False, {}, (), []]

Equivalent to:

print [item for item in iterator if item is not None]

To get all the items that evaluate to False

print filter(lambda item: not item, iterator)
# Will print [None, '', 0, None, False, {}, (), []]