Programs & Examples On #Powerset

A powerset is the set of all subsets for a given set.

How to get all subsets of a set? (powerset)

This can be done very naturally with itertools.product:

import itertools

def powerset(l):
    for sl in itertools.product(*[[[], [i]] for i in l]):
        yield {j for i in sl for j in i}

How to enable assembly bind failure logging (Fusion) in .NET

In my case helped type disk name in lower case

Wrong - C:\someFolder

Correct - c:\someFolder

How to capitalize the first letter of word in a string using Java?

String s=t.getText().trim();
int l=s.length();
char c=Character.toUpperCase(s.charAt(0));
s=c+s.substring(1);
for(int i=1; i<l; i++)
    {
        if(s.charAt(i)==' ')
        {
            c=Character.toUpperCase(s.charAt(i+1));
            s=s.substring(0, i) + c + s.substring(i+2);
        }
    }
    t.setText(s);

Change background color of iframe issue

You can do it using javascript

  • Change iframe background color
  • Change background color of the loaded page (same domain)

Plain javascript

var iframe = document.getElementsByTagName('iframe')[0];
iframe.style.background = 'white';
iframe.contentWindow.document.body.style.backgroundColor = 'white';

jQuery

$('iframe').css('background', 'white');
$('iframe').contents().find('body').css('backgroundColor', 'white');

How to create local notifications?

Creating local notifications are pretty easy. Just follow these steps.

  1. On viewDidLoad() function ask user for permission that your apps want to display notifications. For this we can use the following code.

    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: {didAllow, error in
    })
    
  2. Then you can create a button, and then in the action function you can write the following code to display a notification.

    //creating the notification content
    let content = UNMutableNotificationContent()
    
    //adding title, subtitle, body and badge
    content.title = "Hey this is Simplified iOS"
    content.subtitle = "iOS Development is fun"
    content.body = "We are learning about iOS Local Notification"
    content.badge = 1
    
    //getting the notification trigger
    //it will be called after 5 seconds
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
    
    //getting the notification request
    let request = UNNotificationRequest(identifier: "SimplifiedIOSNotification", content: content, trigger: trigger)
    
    //adding the notification to notification center
    UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
    
  3. Notification will be displayed, just click on home button after tapping the notification button. As when the application is in foreground the notification is not displayed. But if you are using iPhone X. You can display notification even when the app is in foreground. For this you just need to add a delegate called UNUserNotificationCenterDelegate

For more details visit this blog post: iOS Local Notification Tutorial

Iterate through 2 dimensional array

 //This is The easiest I can Imagine . 
 // You need to just change the order of Columns and rows , Yours is printing columns X rows and the solution is printing them rows X columns 
for(int rows=0;rows<array.length;rows++){
    for(int columns=0;columns <array[rows].length;columns++){
        System.out.print(array[rows][columns] + "\t" );}
    System.out.println();}

Add border-bottom to table row <tr>

I tried adding

    table {
      border-collapse: collapse;
    }   

alongside the

    tr {
      bottom-border: 2pt solid #color;
    }

and then commented out border-collapse to see what worked. Just having the tr selector with bottom-border property worked for me!

No Border CSS ex.

No Border CSS ex.

No Border Photo live

No Border Photo live

CSS Border ex.

CSS Border ex.

Table with Border photo live

Table with Border photo live

How do I get my C# program to sleep for 50 msec?

For readability:

using System.Threading;
Thread.Sleep(TimeSpan.FromMilliseconds(50));

jQuery DataTables: control table width

Check this solution too. this solved my DataTable column width issue easily

JQuery DataTables 1.10.20 introduces columns.adjust() method which fix Bootstrap toggle tab issue

 $('a[data-toggle="tab"]').on( 'shown.bs.tab', function (e) {
    $.fn.dataTable.tables( {visible: true, api: true} ).columns.adjust();
} );

Please refer the documentation : Scrolling and Bootstrap tabs

Install IPA with iTunes 12

For iTunes 12.7.0 and above, you just need to Cmd+c your app and Cmd+v into your device on iTunes. Any tab works, including Summary, Music, Movies.

Converting UTF-8 to ISO-8859-1 in Java - how to keep it as single byte

Starting with a set of bytes which encode a string using UTF-8, creates a string from that data, then get some bytes encoding the string in a different encoding:

    byte[] utf8bytes = { (byte)0xc3, (byte)0xa2, 0x61, 0x62, 0x63, 0x64 };
    Charset utf8charset = Charset.forName("UTF-8");
    Charset iso88591charset = Charset.forName("ISO-8859-1");

    String string = new String ( utf8bytes, utf8charset );

    System.out.println(string);

    // "When I do a getbytes(encoding) and "
    byte[] iso88591bytes = string.getBytes(iso88591charset);

    for ( byte b : iso88591bytes )
        System.out.printf("%02x ", b);

    System.out.println();

    // "then create a new string with the bytes in ISO-8859-1 encoding"
    String string2 = new String ( iso88591bytes, iso88591charset );

    // "I get a two different chars"
    System.out.println(string2);

this outputs strings and the iso88591 bytes correctly:

âabcd 
e2 61 62 63 64 
âabcd

So your byte array wasn't paired with the correct encoding:

    String failString = new String ( utf8bytes, iso88591charset );

    System.out.println(failString);

Outputs

âabcd

(either that, or you just wrote the utf8 bytes to a file and read them elsewhere as iso88591)

Loading PictureBox Image from resource file with path (Part 3)

Ok...so first you need to import the image into your project.

1) Select the PictureBox in the Form Design View

2) Open PictureBox Tasks
(it's the little arrow printed to right on the edge of the PictureBox)

3) Click on "Choose image..."

4) Select the second option "Project resource file:"
(this option will create a folder called "Resources" which you can access with Properties.Resources)

5) Click on "Import..." and select your image from your computer
(now a copy of the image will be saved in "Resources" folder created at step 4)

6) Click on "OK"

Now the image is in your project and you can use it with the Properties command. Just type this code when you want to change the picture in the PictureBox:

pictureBox1.Image = Properties.Resources.MyImage;

Note:
MyImage represent the name of the image...
After typing "Properties.Resources.", all imported image files are displayed...

CSS3 background image transition

I was struggling with this for a bit, I first used a stack of images on top of each other and every three seconds, I was trying to animate to the next image in the stack and throwing the current image to the bottom of the stack. At the same time I was using animations as shown above. I couldn't get it to work for the life of me.

You can use this library which allows for **dynamically-resized, slideshow-capable background image ** using jquery-backstretch.

https://github.com/jquery-backstretch/jquery-backstretch

How does inline Javascript (in HTML) work?

There seems to be a lot of bad practice being thrown around Event Handler Attributes. Bad practice is not knowing and using available features where it is most appropriate. The Event Attributes are fully W3C Documented standards and there is nothing bad practice about them. It's no different than placing inline styles, which is also W3C Documented and can be useful in times. Whether you place it wrapped in script tags or not, it's gonna be interpreted the same way.

https://www.w3.org/TR/html5/webappapis.html#event-handler-idl-attributes

Trying to use Spring Boot REST to Read JSON String from POST

To receive arbitrary Json in Spring-Boot, you can simply use Jackson's JsonNode. The appropriate converter is automatically configured.

    @PostMapping(value="/process")
    public void process(@RequestBody com.fasterxml.jackson.databind.JsonNode payload) {
        System.out.println(payload);
    }

Similarity String Comparison in Java

There are indeed a lot of string similarity measures out there:

  • Levenshtein edit distance;
  • Damerau-Levenshtein distance;
  • Jaro-Winkler similarity;
  • Longest Common Subsequence edit distance;
  • Q-Gram (Ukkonen);
  • n-Gram distance (Kondrak);
  • Jaccard index;
  • Sorensen-Dice coefficient;
  • Cosine similarity;
  • ...

You can find explanation and java implementation of these here: https://github.com/tdebatty/java-string-similarity

PDF Parsing Using Python - extracting formatted and plain texts

You can also take a look at PDFMiner (or for older versions of Python see PDFMiner and PDFMiner).

A particular feature of interest in PDFMiner is that you can control how it regroups text parts when extracting them. You do this by specifying the space between lines, words, characters, etc. So, maybe by tweaking this you can achieve what you want (that depends of the variability of your documents). PDFMiner can also give you the location of the text in the page, it can extract data by Object ID and other stuff. So dig in PDFMiner and be creative!

But your problem is really not an easy one to solve because, in a PDF, the text is not continuous, but made from a lot of small groups of characters positioned absolutely in the page. The focus of PDF is to keep the layout intact. It's not content oriented but presentation oriented.

How to add an element to a list?

Elements are added to list using append():

>>> data = {'list': [{'a':'1'}]}
>>> data['list'].append({'b':'2'})
>>> data
{'list': [{'a': '1'}, {'b': '2'}]}

If you want to add element to a specific place in a list (i.e. to the beginning), use insert() instead:

>>> data['list'].insert(0, {'b':'2'})
>>> data
{'list': [{'b': '2'}, {'a': '1'}]}

After doing that, you can assemble JSON again from dictionary you modified:

>>> json.dumps(data)
'{"list": [{"b": "2"}, {"a": "1"}]}'

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.

Laravel 5 not finding css files

Here is the solution

  {!! Html::style('css/select2.min.css') !!}
  {!! Html::script('js/select2.min.js') !!}

How do I find ' % ' with the LIKE operator in SQL Server?

I would use

WHERE columnName LIKE '%[%]%'

SQL Server stores string summary statistics for use in estimating the number of rows that will match a LIKE clause. The cardinality estimates can be better and lead to a more appropriate plan when the square bracket syntax is used.

The response to this Connect Item states

We do not have support for precise cardinality estimation in the presence of user defined escape characters. So we probably get a poor estimate and a poor plan. We'll consider addressing this issue in a future release.

An example

CREATE TABLE T
(
X VARCHAR(50),
Y CHAR(2000) NULL
)

CREATE NONCLUSTERED INDEX IX ON T(X)

INSERT INTO T (X)
SELECT TOP (5) '10% off'
FROM master..spt_values
UNION ALL
SELECT  TOP (100000)  'blah'
FROM master..spt_values v1,  master..spt_values v2


SET STATISTICS IO ON;
SELECT *
FROM T 
WHERE X LIKE '%[%]%'

SELECT *
FROM T
WHERE X LIKE '%\%%' ESCAPE '\'

Shows 457 logical reads for the first query and 33,335 for the second.

Finding the average of a list

Both can give you close to similar values on an integer or at least 10 decimal values. But if you are really considering long floating values both can be different. Approach can vary on what you want to achieve.

>>> l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
>>> print reduce(lambda x, y: x + y, l) / len(l)
20
>>> sum(l)/len(l)
20

Floating values

>>> print reduce(lambda x, y: x + y, l) / float(len(l))
20.1111111111
>>> print sum(l)/float(len(l))
20.1111111111

@Andrew Clark was correct on his statement.

How do I import modules or install extensions in PostgreSQL 9.1+?

In addition to the extensions which are maintained and provided by the core PostgreSQL development team, there are extensions available from third parties. Notably, there is a site dedicated to that purpose: http://www.pgxn.org/

Ajax using https on an http page

Add the Access-Control-Allow-Origin header from the server

Access-Control-Allow-Origin: https://www.mysite.com

http://en.wikipedia.org/wiki/Cross-Origin_Resource_Sharing

What's the difference between JavaScript and JScript?

JScript is Microsoft's equivalent of JavaScript.
Java is an Oracle product and used to be a Sun product.

Oracle bought Sun.

JavaScript + Microsoft = JScript

ArrayList initialization equivalent to array initialization

Here is the closest you can get:

ArrayList<String> list = new ArrayList(Arrays.asList("Ryan", "Julie", "Bob"));

You can go even simpler with:

List<String> list = Arrays.asList("Ryan", "Julie", "Bob")

Looking at the source for Arrays.asList, it constructs an ArrayList, but by default is cast to List. So you could do this (but not reliably for new JDKs):

ArrayList<String> list = (ArrayList<String>)Arrays.asList("Ryan", "Julie", "Bob")

List<String> to ArrayList<String> conversion issue

First of all, why is the map a HashMap<String, ArrayList<String>> and not a HashMap<String, List<String>>? Is there some reason why the value must be a specific implementation of interface List (ArrayList in this case)?

Arrays.asList does not return a java.util.ArrayList, so you can't assign the return value of Arrays.asList to a variable of type ArrayList.

Instead of:

allWords = Arrays.asList(strTemp.toLowerCase().split("\\s+"));

Try this:

allWords.addAll(Arrays.asList(strTemp.toLowerCase().split("\\s+")));

Ruby: character to ascii from a string

"a"[0]

or

?a

Both would return their ASCII equivalent.

MySQL ON DUPLICATE KEY UPDATE for multiple rows insert in single query

I was looking for the same behavior using jdbi's BindBeanList and found the syntax is exactly the same as Peter Lang's answer above. In case anybody is running into this question, here's my code:

  @SqlUpdate("INSERT INTO table_one (col_one, col_two) VALUES <beans> ON DUPLICATE KEY UPDATE col_one=VALUES(col_one), col_two=VALUES(col_two)")
void insertBeans(@BindBeanList(value = "beans", propertyNames = {"colOne", "colTwo"}) List<Beans> beans);

One key detail to note is that the propertyName you specify within @BindBeanList annotation is not same as the column name you pass into the VALUES() call on update.

How to determine when Fragment becomes visible in ViewPager

We have a special case with MVP where the fragment needs to notify the presenter that the view has become visible, and the presenter is injected by Dagger in fragment.onAttach().

setUserVisibleHint() is not enough, we've detected 3 different cases that needed to be addressed (onAttach() is mentioned so that you know when the presenter is available):

  1. Fragment has just been created. The system makes the following calls:

    setUserVisibleHint() // before fragment's lifecycle calls, so presenter is null
    onAttach()
    ...
    onResume()
    
  2. Fragment already created and home button is pressed. When restoring the app to foreground, this is called:

    onResume()
    
  3. Orientation change:

    onAttach() // presenter available
    onResume()
    setUserVisibleHint()
    

We only want the visibility hint to get to the presenter once, so this is how we do it:

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View root = inflater.inflate(R.layout.fragment_list, container, false);
    setHasOptionsMenu(true);

    if (savedInstanceState != null) {
        lastOrientation = savedInstanceState.getInt(STATE_LAST_ORIENTATION,
              getResources().getConfiguration().orientation);
    } else {
        lastOrientation = getResources().getConfiguration().orientation;
    }

    return root;
}

@Override
public void onResume() {
    super.onResume();
    presenter.onResume();

    int orientation = getResources().getConfiguration().orientation;
    if (orientation == lastOrientation) {
        if (getUserVisibleHint()) {
            presenter.onViewBecomesVisible();
        }
    }
    lastOrientation = orientation;
}

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (presenter != null && isResumed() && isVisibleToUser) {
        presenter.onViewBecomesVisible();
    }
}

@Override public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt(STATE_LAST_ORIENTATION, lastOrientation);
}

List of phone number country codes

Searching this I found this project:

https://github.com/mledoze/countries

It seems to generate a lot of formats...

How can I rebuild indexes and update stats in MySQL innoDB?

This is done with

ANALYZE TABLE table_name;

Read more about it here.

ANALYZE TABLE analyzes and stores the key distribution for a table. During the analysis, the table is locked with a read lock for MyISAM, BDB, and InnoDB. This statement works with MyISAM, BDB, InnoDB, and NDB tables.

How to make a link open multiple pages when clicked

I created a bit of a hybrid approach between Paul & Adam's approach:

The link that opens the array of links is already in the html. The jquery just creates the array of links and opens each one when the "open-all" button is clicked:

HTML:

<ul class="links">
<li><a href="http://www.google.com/"></a></li>
<li><a href="http://www.yahoo.com/"></a></li>
</ul>

<a id="open-all" href="#">OPEN ALL</a>

JQUERY:

$(function() { // On DOM content ready...
    var hrefs = [];

    $('.links a').each(function() {
        hrefs.push(this.href); // Store the URLs from the links...
    });

    $('#open-all').click(function() {
        for (var i in hrefs) {
            window.open(hrefs[i]); // ...that opens each stored link in its own window when clicked...
        }
    });
});

You can check it out here: https://jsfiddle.net/daveaseeman/vonob51n/1/

How to implement a binary search tree in Python?

class TreeNode:
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None


class BinaryTree:
    def __init__(self, root=None):
        self.root = root

    def add_node(self, node, value):
        """
        Node points to the left of value if node > value; right otherwise,
        BST cannot have duplicate values
        """
        if node is not None:
            if value < node.value:
                if node.left is None:
                    node.left = TreeNode(value)
                else:
                    self.add_node(node.left, value)
            else:
                if node.right is None:
                    node.right = TreeNode(value)
                else:
                    self.add_node(node.right, value)
        else:
            self.root = TreeNode(value)

    def search(self, value):
        """
        Value will be to the left of node if node > value; right otherwise.
        """
        node = self.root
        while node is not None:
            if node.value == value:
                return True     # node.value
            if node.value > value:
                node = node.left
            else:
                node = node.right
        return False

    def traverse_inorder(self, node):
        """
        Traverse the left subtree of a node as much as possible, then traverse
        the right subtree, followed by the parent/root node.
        """
        if node is not None:
            self.traverse_inorder(node.left)
            print(node.value)
            self.traverse_inorder(node.right)


def main():
    binary_tree = BinaryTree()
    binary_tree.add_node(binary_tree.root, 200)
    binary_tree.add_node(binary_tree.root, 300)
    binary_tree.add_node(binary_tree.root, 100)
    binary_tree.add_node(binary_tree.root, 30)
    binary_tree.traverse_inorder(binary_tree.root)
    print(binary_tree.search(200))


if __name__ == '__main__':
    main()

JSON to TypeScript class instance?

What is actually the most robust and elegant automated solution for deserializing JSON to TypeScript runtime class instances?

Using property decorators with ReflectDecorators to record runtime-accessible type information that can be used during a deserialization process provides a surprisingly clean and widely adaptable approach, that also fits into existing code beautifully. It is also fully automatable, and works for nested objects as well.

An implementation of this idea is TypedJSON, which I created precisely for this task:

@JsonObject
class Foo {
    @JsonMember
    name: string;

    getName(): string { return this.name };
}
var foo = TypedJSON.parse('{"name": "John Doe"}', Foo);

foo instanceof Foo; // true
foo.getName(); // "John Doe"

How do I prevent CSS inheritance?

just set them back to their defaults in the "#sidebar ul li" selector

Linux error while loading shared libraries: cannot open shared object file: No such file or directory

Update
While what I write below is true as a general answer about shared libraries, I think the most frequent cause of these sorts of message is because you've installed a package, but not installed the "-dev" version of that package.


Well, it's not lying - there is no libpthread_rt.so.1 in that listing. You probably need to re-configure and re-build it so that it depends on the library you have, or install whatever provides libpthread_rt.so.1.

Generally, the numbers after the .so are version numbers, and you'll often find that they are symlinks to each other, so if you have version 1.1 of libfoo.so, you'll have a real file libfoo.so.1.0, and symlinks foo.so and foo.so.1 pointing to the libfoo.so.1.0. And if you install version 1.1 without removing the other one, you'll have a libfoo.so.1.1, and libfoo.so.1 and libfoo.so will now point to the new one, but any code that requires that exact version can use the libfoo.so.1.0 file. Code that just relies on the version 1 API, but doesn't care if it's 1.0 or 1.1 will specify libfoo.so.1. As orip pointed out in the comments, this is explained well at http://tldp.org/HOWTO/Program-Library-HOWTO/shared-libraries.html.

In your case, you might get away with symlinking libpthread_rt.so.1 to libpthread_rt.so. No guarantees that it won't break your code and eat your TV dinners, though.

Why is "except: pass" a bad programming practice?

?Handling errors is very important in programming. You do need to show the user what went wrong. In very few cases you can ignore the errors. This is it is very bad programming practice.

Passing a String by Reference in Java?

objects are passed by reference, primitives are passed by value.

String is not a primitive, it is an object, and it is a special case of object.

This is for memory-saving purpose. In JVM, there is a string pool. For every string created, JVM will try to see if the same string exist in the string pool, and point to it if there were already one.

public class TestString
{
    private static String a = "hello world";
    private static String b = "hello world";
    private static String c = "hello " + "world";
    private static String d = new String("hello world");

    private static Object o1 = new Object();
    private static Object o2 = new Object();

    public static void main(String[] args)
    {
        System.out.println("a==b:"+(a == b));
        System.out.println("a==c:"+(a == c));
        System.out.println("a==d:"+(a == d));
        System.out.println("a.equals(d):"+(a.equals(d)));
        System.out.println("o1==o2:"+(o1 == o2));

        passString(a);
        passString(d);
    }

    public static void passString(String s)
    {
        System.out.println("passString:"+(a == s));
    }
}

/* OUTPUT */

a==b:true
a==c:true
a==d:false
a.equals(d):true
o1==o2:false
passString:true
passString:false

the == is checking for memory address (reference), and the .equals is checking for contents (value)

What is FCM token in Firebase?

They deprecated getToken() method in the below release notes. Instead, we have to use getInstanceId.

https://firebase.google.com/docs/reference/android/com/google/firebase/iid/FirebaseInstanceId

Task<InstanceIdResult> task = FirebaseInstanceId.getInstance().getInstanceId();
task.addOnSuccessListener(new OnSuccessListener<InstanceIdResult>() {
      @Override
      public void onSuccess(InstanceIdResult authResult) {
          // Task completed successfully
          // ...
          String fcmToken = authResult.getToken();
      }
});

task.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
    // Task failed with an exception
    // ...
}
});

To handle success and failure in the same listener, attach an OnCompleteListener:

task.addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
@Override
public void onComplete(@NonNull Task<InstanceIdResult> task) {
    if (task.isSuccessful()) {
        // Task completed successfully
        InstanceIdResult authResult = task.getResult();
        String fcmToken = authResult.getToken();
    } else {
        // Task failed with an exception
        Exception exception = task.getException();
    }
}
});

Also, the FirebaseInstanceIdService Class is deprecated and they came up with onNewToken method in FireBaseMessagingService as replacement for onTokenRefresh,

you can refer to the release notes here, https://firebase.google.com/support/release-notes/android

@Override
public void onNewToken(String s) {
    super.onNewToken(s);
    Use this code logic to send the info to your server.
    //sendRegistrationToServer(s);
}

Unable to verify leaf signature

You have to include the Intermediate certificate in your server. This solves the [Error: UNABLE_TO_VERIFY_LEAF_SIGNATURE]

How to add multiple files to Git at the same time

When you change files or add a new ones in repository you first must stage them.

git add <file>

or if you want to stage all

git add .

By doing this you are telling to git what files you want in your next commit. Then you do:

git commit -m 'your message here'

You use

git push origin master

where origin is the remote repository branch and master is your local repository branch.

Nginx: Job for nginx.service failed because the control process exited

Try to run the following two commands:

sudo fuser -k 80/tcp

sudo fuser -k 443/tcp

Then execute

sudo service nginx restart

If that worked, your hosting provider might be installing Apache on your server by default during a fresh install, so keep reading for a more permenant fix. If that didn't work, keep reading to identify the issue.

Run nginx -t and if it doesn't return anything, I would verify Nginx error log. By default, it should be located in /var/log/nginx/error.log.

You can open it with any text editor: sudo nano /var/log/nginx/error.log

Can you find something suspicious there?

The second log you can check is the following

sudo nano /var/log/syslog

When I had this issue, it was because my hosting provider was automatically installing Apache during a clean install. It was blocking port 80.

When I executed sudo nano /var/log/nginx/error.log I got the following as the error log:

2018/08/04 06:17:33 [emerg] 634#0: bind() to 0.0.0.0:80 failed (98: Address already in use)
2018/08/04 06:17:33 [emerg] 634#0: bind() to [::]:80 failed (98: Address already in use)
2018/08/04 06:17:33 [emerg] 634#0: bind() to 0.0.0.0:80 failed (98: Address already in use)

What the above error is telling is that it was not able to bind nginx to port 80 because it was already in use.

To fix this, you need to run the following:

yum install net-tools

sudo netstat -tulpn

When you execute the above you will get something like the following:

Proto Recv-Q Send-Q Local Address           Foreign Address         State    PID/Program name
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      1762/httpd
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1224/sshd
tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN      1528/sendmail:acce
tcp6       0      0 :::22                   :::*                    LISTEN      1224/sshd

You can see that port 80 is blocked by httpd (Apache). This could also be port 443 if you are using SSL.

Get the PID of the process that uses port 80 or 443. And send the kill command changing the <PID> value:

sudo kill -2 <PID>

Note in my example the PID value of Apache was 1762 so I would execute sudo kill -2 1762

Aternatively you can execute the following:

sudo fuser -k 80/tcp

sudo fuser -k 443/tcp

Now that port 80 or 443 is clear, you can start Nginx by running the following:

sudo service nginx restart

It is also advisable to remove whatever was previously blocking port 80 & 443. This will avoid any conflict in the future. Since Apache (httpd) was blocking my ports I removed it by running the following:

yum remove httpd httpd-devel httpd-manual httpd-tools mod_auth_kerb mod_auth_mysql mod_auth_pgsql mod_authz_ldap mod_dav_svn mod_dnssd mod_nss mod_perl mod_revocator mod_ssl mod_wsgi

Hope this helps.

Checking for Undefined In React

You can check undefined object using below code.

ReactObject === 'undefined'

Check whether variable is number or string in JavaScript

Type checking

You can check the type of variable by using typeof operator:

typeof variable

Value checking

The code below returns true for numbers and false for anything else:

!isNaN(+variable);

Launch an event when checking a checkbox in Angular2

StackBlitz

Template: You can either use the native change event or NgModel directive's ngModelChange.

<input type="checkbox" (change)="onNativeChange($event)"/>

or

<input type="checkbox" ngModel (ngModelChange)="onNgModelChange($event)"/>

TS:

onNativeChange(e) { // here e is a native event
  if(e.target.checked){
    // do something here
  }
}

onNgModelChange(e) { // here e is a boolean, true if checked, otherwise false
  if(e){
    // do something here
  }
}

Move existing, uncommitted work to a new branch in Git

I used @Robin answer & listing all that I did,

git status                               <-- review/list uncommitted changes
git stash                                <-- stash uncommitted changes
git stash branch <new-branch> stash@{1}  <-- create a branch from stash
git add .                                <-- add local changes
git status                               <-- review the status; ready to commit
git commit -m "local changes ..."        <-- commit the changes
git branch --list                        <-- see list of branches incl the one created above
git status                               <-- nothing to commit, working tree (new-branch) is clean
git checkout <old-branch>                <-- switch back

! If the repo has more than one stash, see which one to apply to the new-branch:

git stash list  
  stash@{0}: WIP on ...  
  stash@{1}: WIP on ...

and inspect the individual stash by,

git stash show stash@{1}

Or inspect all stashes at once:

git stash list -p

docker command not found even though installed with apt-get

SET UP THE REPOSITORY

For Ubuntu 14.04/16.04/16.10/17.04:

sudo add-apt-repository "deb [arch=amd64] \
     https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"

For Ubuntu 17.10:

sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu zesty stable"

Add Docker’s official GPG key:

$ curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -

Then install

$ sudo apt-get update && sudo apt-get -y install docker-ce

How to add new line into txt file

Why not do it with one method call:

File.AppendAllLines("file.txt", new[] { DateTime.Now.ToString() });

which will do the newline for you, and allow you to insert multiple lines at once if you want.

How to get Current Timestamp from Carbon in Laravel 5

You can try this if you want date time string:

use Carbon\Carbon;
$current_date_time = Carbon::now()->toDateTimeString(); // Produces something like "2019-03-11 12:25:00"

If you want timestamp, you can try:

use Carbon\Carbon;
$current_timestamp = Carbon::now()->timestamp; // Produces something like 1552296328

See the official Carbon documentation here.

How to pass in a react component into another react component to transclude the first component's content?

Note I provided a more in-depth answer here

Runtime wrapper:

It's the most idiomatic way.

const Wrapper = ({children}) => (
  <div>
    <div>header</div>
    <div>{children}</div>
    <div>footer</div>
  </div>
);

const App = () => <div>Hello</div>;

const WrappedApp = () => (
  <Wrapper>
    <App/>
  </Wrapper>
);

Note that children is a "special prop" in React, and the example above is syntactic sugar and is (almost) equivalent to <Wrapper children={<App/>}/>


Initialization wrapper / HOC

You can use an Higher Order Component (HOC). They have been added to the official doc recently.

// Signature may look fancy but it's just 
// a function that takes a component and returns a new component
const wrapHOC = (WrappedComponent) => (props) => (
  <div>
    <div>header</div>
    <div><WrappedComponent {...props}/></div>
    <div>footer</div>
  </div>
)

const App = () => <div>Hello</div>;

const WrappedApp = wrapHOC(App);

This can lead to (little) better performances because the wrapper component can short-circuit the rendering one step ahead with shouldComponentUpdate, while in the case of a runtime wrapper, the children prop is likely to always be a different ReactElement and cause re-renders even if your components extend PureComponent.

Notice that connect of Redux used to be a runtime wrapper but was changed to an HOC because it permits to avoid useless re-renders if you use the pure option (which is true by default)

You should never call an HOC during the render phase because creating React components can be expensive. You should rather call these wrappers at initialization.


Note that when using functional components like above, the HOC version do not provide any useful optimisation because stateless functional components do not implement shouldComponentUpdate

More explanations here: https://stackoverflow.com/a/31564812/82609

What do Clustered and Non clustered index actually mean?

With a clustered index the rows are stored physically on the disk in the same order as the index. Therefore, there can be only one clustered index.

With a non clustered index there is a second list that has pointers to the physical rows. You can have many non clustered indices, although each new index will increase the time it takes to write new records.

It is generally faster to read from a clustered index if you want to get back all the columns. You do not have to go first to the index and then to the table.

Writing to a table with a clustered index can be slower, if there is a need to rearrange the data.

How do I uninstall a Windows service if the files do not exist anymore?

From the command prompt, use the Windows "sc.exe" utility. You will run something like this:

sc delete <service-name>

Array Length in Java

It contains the allocated size, 10. The remaining indexes will contain the default value which is 0.

Unable to find a @SpringBootConfiguration when doing a JpaTest

I had the same issue and I solved by adding an empty class annotated with SpringBootApplication in the root package of the folder src/test/java

package org.enricogiurin.core;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class CoreTestConfiguration {}

How do I finish the merge after resolving my merge conflicts?

After all files have been added, the next step is a "git commit".

"git status" will suggest what to do: files yet to add are listed at the bottom, and once they are all done, it will suggest a commit at the top, where it explains the merge status of the current branch.

jQuery + client-side template = "Syntax error, unrecognized expression"

I had the same error:
"Syntax error, unrecognized expression: // "
It is known bug at JQuery, so i needed to think on workaround solution,
What I did is:
I changed "script" tag to "div"
and added at angular this code
and the error is gone...

app.run(['$templateCache', function($templateCache) {
    var url = "survey-input.html";
    content = angular.element(document.getElementById(url)).html()
    $templateCache.put(url, content);
}]);

How to find and replace with regex in excel

If you want a formula to do it then:

=IF(ISNUMBER(SEARCH("*texts are *",A1)),LEFT(A1,FIND("texts are ",A1) + 9) & "WORD",A1)

This will do it. Change `"WORD" To the word you want.

tap gesture recognizer - which object was tapped?

Use this code in Swift

func tappGeastureAction(sender: AnyObject) {
    if let tap = sender as? UITapGestureRecognizer {
        let point = tap.locationInView(locatedView)
        if filterView.pointInside(point, withEvent: nil) == true {
            // write your stuff here                
        }
    }
}

List changes unexpectedly after assignment. How do I clone or copy it to prevent this?

Let's start from the beginning and explore this question.

So let's suppose you have two lists:

list_1=['01','98']
list_2=[['01','98']]

And we have to copy both lists, now starting from the first list:

So first let's try by setting the variable copy to our original list, list_1:

copy=list_1

Now if you are thinking copy copied the list_1, then you are wrong. The id function can show us if two variables can point to the same object. Let's try this:

print(id(copy))
print(id(list_1))

The output is:

4329485320
4329485320

Both variables are the exact same argument. Are you surprised?

So as we know python doesn't store anything in a variable, Variables are just referencing to the object and object store the value. Here object is a list but we created two references to that same object by two different variable names. This means that both variables are pointing to the same object, just with different names.

When you do copy=list_1, it is actually doing:

enter image description here

Here in the image list_1 and copy are two variable names but the object is same for both variable which is list

So if you try to modify copied list then it will modify the original list too because the list is only one there, you will modify that list no matter you do from the copied list or from the original list:

copy[0]="modify"

print(copy)
print(list_1)

output:

['modify', '98']
['modify', '98']

So it modified the original list :

Now let's move onto a pythonic method for copying lists.

copy_1=list_1[:]

This method fixes the first issue we had:

print(id(copy_1))
print(id(list_1))

4338792136
4338791432

So as we can see our both list having different id and it means that both variables are pointing to different objects. So what actually going on here is:

enter image description here

Now let's try to modify the list and let's see if we still face the previous problem:

copy_1[0]="modify"

print(list_1)
print(copy_1)

The output is:

['01', '98']
['modify', '98']

As you can see, it only modified the copied list. That means it worked.

Do you think we're done? No. Let's try to copy our nested list.

copy_2=list_2[:]

list_2 should reference to another object which is copy of list_2. Let's check:

print(id((list_2)),id(copy_2))

We get the output:

4330403592 4330403528

Now we can assume both lists are pointing different object, so now let's try to modify it and let's see it is giving what we want:

copy_2[0][1]="modify"

print(list_2,copy_2)

This gives us the output:

[['01', 'modify']] [['01', 'modify']]

This may seem a little bit confusing, because the same method we previously used worked. Let's try to understand this.

When you do:

copy_2=list_2[:]

You're only copying the outer list, not the inside list. We can use the id function once again to check this.

print(id(copy_2[0]))
print(id(list_2[0]))

The output is:

4329485832
4329485832

When we do copy_2=list_2[:], this happens:

enter image description here

It creates the copy of list but only outer list copy, not the nested list copy, nested list is same for both variable, so if you try to modify the nested list then it will modify the original list too as the nested list object is same for both lists.

What is the solution? The solution is the deepcopy function.

from copy import deepcopy
deep=deepcopy(list_2)

Let's check this:

print(id((list_2)),id(deep))

4322146056 4322148040

Both outer lists have different IDs, let's try this on the inner nested lists.

print(id(deep[0]))
print(id(list_2[0]))

The output is:

4322145992
4322145800

As you can see both IDs are different, meaning we can assume that both nested lists are pointing different object now.

This means when you do deep=deepcopy(list_2) what actually happens:

enter image description here

Both nested lists are pointing different object and they have separate copy of nested list now.

Now let's try to modify the nested list and see if it solved the previous issue or not:

deep[0][1]="modify"
print(list_2,deep)

It outputs:

[['01', '98']] [['01', 'modify']]

As you can see, it didn't modify the original nested list, it only modified the copied list.

jQuery AJAX Call to PHP Script with JSON Return

Make it dataType instead of datatype.

And add below code in php as your ajax request is expecting json and will not accept anything, but json.

header('Content-Type: application/json');

Correct Content type for JSON and JSONP

The response visible in firebug is text data. Check Content-Type of the response header to verify, if the response is json. It should be application/json for dataType:'json' and text/html for dataType:'html'.

Adding data attribute to DOM

 $(document.createElement("img")).attr({
                src: 'https://graph.facebook.com/'+friend.id+'/picture',
                title: friend.name ,
                'data-friend-id':friend.id,
                'data-friend-name':friend.name
            }).appendTo(divContainer);

Powershell equivalent of bash ampersand (&) for forking/running background processes

From PowerShell Core 6.0 you are able to write & at end of command and it will be equivalent to running you pipeline in background in current working directory.

It's not equivalent to & in bash, it's just a nicer syntax for current PowerShell jobs feature. It returns a job object so you can use all other command that you would use for jobs. For example Receive-Job:

C:\utils> ping google.com &

Id     Name            PSJobTypeName   State         HasMoreData     Location             Command
--     ----            -------------   -----         -----------     --------             -------
35     Job35           BackgroundJob   Running       True            localhost            Microsoft.PowerShell.M...


C:\utils> Receive-Job 35

Pinging google.com [172.217.16.14] with 32 bytes of data:
Reply from 172.217.16.14: bytes=32 time=11ms TTL=55
Reply from 172.217.16.14: bytes=32 time=11ms TTL=55
Reply from 172.217.16.14: bytes=32 time=10ms TTL=55
Reply from 172.217.16.14: bytes=32 time=10ms TTL=55

Ping statistics for 172.217.16.14:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 10ms, Maximum = 11ms, Average = 10ms
C:\utils>

If you want to execute couple of statements in background you can combine & call operator, { } script block and this new & background operator like here:

& { cd .\SomeDir\; .\SomeLongRunningOperation.bat; cd ..; } &

Here's some more info from documentation pages:

from What's New in PowerShell Core 6.0:

Support backgrounding of pipelines with ampersand (&) (#3360)

Putting & at the end of a pipeline causes the pipeline to be run as a PowerShell job. When a pipeline is backgrounded, a job object is returned. Once the pipeline is running as a job, all of the standard *-Job cmdlets can be used to manage the job. Variables (ignoring process-specific variables) used in the pipeline are automatically copied to the job so Copy-Item $foo $bar & just works. The job is also run in the current directory instead of the user's home directory. For more information about PowerShell jobs, see about_Jobs.

from about_operators / Ampersand background operator &:

Ampersand background operator &

Runs the pipeline before it in a PowerShell job. The ampersand background operator acts similarly to the UNIX "ampersand operator" which famously runs the command before it as a background process. The ampersand background operator is built on top of PowerShell jobs so it shares a lot of functionality with Start-Job. The following command contains basic usage of the ampersand background operator.

Get-Process -Name pwsh &

This is functionally equivalent to the following usage of Start-Job.

Start-Job -ScriptBlock {Get-Process -Name pwsh}

Since it's functionally equivalent to using Start-Job, the ampersand background operator returns a Job object just like Start-Job does. This means that you are able to use Receive-Job and Remove-Job just as you would if you had used Start-Job to start the job.

$job = Get-Process -Name pwsh &
Receive-Job $job

Output

NPM(K)    PM(M)      WS(M)     CPU(s)      Id  SI ProcessName
------    -----      -----     ------      --  -- -----------
    0     0.00     221.16      25.90    6988 988 pwsh
    0     0.00     140.12      29.87   14845 845 pwsh
    0     0.00      85.51       0.91   19639 988 pwsh


$job = Get-Process -Name pwsh &
Remove-Job $job

For more information on PowerShell jobs, see about_Jobs.

if else statement in AngularJS templates

In this case you want to "calculate" a pixel value depending of an object property.

I would define a function in the controller that calculates the pixel values.

In the controller:


$scope.GetHeight = function(aspect) {
   if(bla bla bla) return 270;
   return 360;
}

Then in your template you just write:


element height="{{ GetHeight(aspect) }}px "

Add line break to ::after or ::before pseudo-element content

Add line break to ::after or ::before pseudo-element content

.yourclass:before {
    content: 'text here first \A  text here second';
    white-space: pre;
}

Can a table row expand and close?

To answer your question, no. That would be possible with div though. THe only question is would cause a hazzle if the functionality were done with div rather than tables.

How to save a base64 image to user's disk using JavaScript?

This Works

function saveBase64AsFile(base64, fileName) {
    var link = document.createElement("a");
    document.body.appendChild(link);
    link.setAttribute("type", "hidden");
    link.href = "data:text/plain;base64," + base64;
    link.download = fileName;
    link.click();  
    document.body.removeChild(link);
}

Based on the answer above but with some changes

How can I check if a program exists from a Bash script?

In case you want to check if a program exists and is really a program, not a Bash built-in command, then command, type and hash are not appropriate for testing as they all return 0 exit status for built-in commands.

For example, there is the time program which offers more features than the time built-in command. To check if the program exists, I would suggest using which as in the following example:

# First check if the time program exists
timeProg=`which time`
if [ "$timeProg" = "" ]
then
  echo "The time program does not exist on this system."
  exit 1
fi

# Invoke the time program
$timeProg --quiet -o result.txt -f "%S %U + p" du -sk ~
echo "Total CPU time: `dc -f result.txt` seconds"
rm result.txt

How do I get into a non-password protected Java keystore or change the password?

Getting into a non-password protected Java keystore and changing the password can be done with a help of Java programming language itself.

That article contains the code for that:

thetechawesomeness.ideasmatter.info

What is href="#" and why is it used?

The href attribute defines the URL of the resource of a link. If the anchor tag does not have href tag then it will not become hyperlink. The href attribute have the following values:

1. Absolute path: move to another site like href="http://www.google.com"
2. Relative path: move to another page within the site like herf ="defaultpage.aspx"
3. Move to an element with a specified id within the page like href="#bottom"
4. href="javascript:void(0)", it does not move anywhere.
5. href="#" , it does not move anywhere but scroll on the top of the current page.
6. href= "" , it will load the current page but some browsers causes forbidden errors.

Note: When we do not need to specified any url inside a anchor tag then use 
<a href="javascript:void(0)">Test1</a>

How to format a UTC date as a `YYYY-MM-DD hh:mm:ss` string using NodeJS?

Alternative #6233....

Add the UTC offset to the local time then convert it to the desired format with the toLocaleDateString() method of the Date object:

// Using the current date/time
let now_local = new Date();
let now_utc = new Date();

// Adding the UTC offset to create the UTC date/time
now_utc.setMinutes(now_utc.getMinutes() + now_utc.getTimezoneOffset())

// Specify the format you want
let date_format = {};
date_format.year = 'numeric';
date_format.month = 'numeric';
date_format.day = '2-digit';
date_format.hour = 'numeric';
date_format.minute = 'numeric';
date_format.second = 'numeric';

// Printing the date/time in UTC then local format
console.log('Date in UTC: ', now_utc.toLocaleDateString('us-EN', date_format));
console.log('Date in LOC: ', now_local.toLocaleDateString('us-EN', date_format));

I'm creating a date object defaulting to the local time. I'm adding the UTC off-set to it. I'm creating a date-formatting object. I'm displaying the UTC date/time in the desired format:

enter image description here

How can I add a background thread to flask?

Your additional threads must be initiated from the same app that is called by the WSGI server.

The example below creates a background thread that executes every 5 seconds and manipulates data structures that are also available to Flask routed functions.

import threading
import atexit
from flask import Flask

POOL_TIME = 5 #Seconds

# variables that are accessible from anywhere
commonDataStruct = {}
# lock to control access to variable
dataLock = threading.Lock()
# thread handler
yourThread = threading.Thread()

def create_app():
    app = Flask(__name__)

    def interrupt():
        global yourThread
        yourThread.cancel()

    def doStuff():
        global commonDataStruct
        global yourThread
        with dataLock:
        # Do your stuff with commonDataStruct Here

        # Set the next thread to happen
        yourThread = threading.Timer(POOL_TIME, doStuff, ())
        yourThread.start()   

    def doStuffStart():
        # Do initialisation stuff here
        global yourThread
        # Create your thread
        yourThread = threading.Timer(POOL_TIME, doStuff, ())
        yourThread.start()

    # Initiate
    doStuffStart()
    # When you kill Flask (SIGTERM), clear the trigger for the next thread
    atexit.register(interrupt)
    return app

app = create_app()          

Call it from Gunicorn with something like this:

gunicorn -b 0.0.0.0:5000 --log-config log.conf --pid=app.pid myfile:app

Angularjs simple file download causes router to redirect

We also had to develop a solution which would even work with APIs requiring authentication (see this article)

Using AngularJS in a nutshell here is how we did it:

Step 1: Create a dedicated directive

// jQuery needed, uses Bootstrap classes, adjust the path of templateUrl
app.directive('pdfDownload', function() {
return {
    restrict: 'E',
    templateUrl: '/path/to/pdfDownload.tpl.html',
    scope: true,
    link: function(scope, element, attr) {
        var anchor = element.children()[0];

        // When the download starts, disable the link
        scope.$on('download-start', function() {
            $(anchor).attr('disabled', 'disabled');
        });

        // When the download finishes, attach the data to the link. Enable the link and change its appearance.
        scope.$on('downloaded', function(event, data) {
            $(anchor).attr({
                href: 'data:application/pdf;base64,' + data,
                download: attr.filename
            })
                .removeAttr('disabled')
                .text('Save')
                .removeClass('btn-primary')
                .addClass('btn-success');

            // Also overwrite the download pdf function to do nothing.
            scope.downloadPdf = function() {
            };
        });
    },
    controller: ['$scope', '$attrs', '$http', function($scope, $attrs, $http) {
        $scope.downloadPdf = function() {
            $scope.$emit('download-start');
            $http.get($attrs.url).then(function(response) {
                $scope.$emit('downloaded', response.data);
            });
        };
    }] 
});

Step 2: Create a template

<a href="" class="btn btn-primary" ng-click="downloadPdf()">Download</a>

Step 3: Use it

<pdf-download url="/some/path/to/a.pdf" filename="my-awesome-pdf"></pdf-download>

This will render a blue button. When clicked, a PDF will be downloaded (Caution: the backend has to deliver the PDF in Base64 encoding!) and put into the href. The button turns green and switches the text to Save. The user can click again and will be presented with a standard download file dialog for the file my-awesome.pdf.

Our example uses PDF files, but apparently you could provide any binary format given it's properly encoded.

How do I specify the columns and rows of a multiline Editor-For in ASP.MVC?

In ASP.NET MVC 5 you could use the [DataType(DataType.MultilineText)] attribute. It will render a TextArea tag.

public class MyModel
{
    [DataType(DataType.MultilineText)]
    public string MyField { get; set; }
}

Then in the view if you need to specify the rows you can do it like this:

@Html.EditorFor(model => model.MyField, new { htmlAttributes = new { rows = 10 } })

Or just use the TextAreaFor with the right overload:

@Html.TextAreaFor(model => model.MyField, 10, 20, null)

How do I use this JavaScript variable in HTML?

Try this:

<body>
    <div id="divMsg"></div>
</body>
<script>
    var name = prompt("What's your name?");
    var lengthOfName = name.length;
    document.getElementById("divMsg").innerHTML = "Length: " + lengthOfName;
</script>

Favicon: .ico or .png / correct tags?

I know this is an old question.

Here's another option - attending to different platform requirements - Source

<link rel='shortcut icon' type='image/vnd.microsoft.icon' href='/favicon.ico'> <!-- IE -->
<link rel='apple-touch-icon' type='image/png' href='/icon.57.png'> <!-- iPhone -->
<link rel='apple-touch-icon' type='image/png' sizes='72x72' href='/icon.72.png'> <!-- iPad -->
<link rel='apple-touch-icon' type='image/png' sizes='114x114' href='/icon.114.png'> <!-- iPhone4 -->
<link rel='icon' type='image/png' href='/icon.114.png'> <!-- Opera Speed Dial, at least 144×114 px -->

This is the broadest approach I have found so far.

Ultimately the decision depends on your own needs. Ask yourself, who is your target audience?

UPDATE May 27, 2018: As expected, time goes by and things change. But there's good news too. I found a tool called Real Favicon Generator that generates all the required lines for the icon to work on all modern browsers and platforms. It doesn't handle backwards compatibility though.

@class vs. #import

The common practice is using @class in header files (but you still need to #import the superclass), and #import in implementation files. This will avoid any circular inclusions, and it just works.

"for" vs "each" in Ruby

I just want to make a specific point about the for in loop in Ruby. It might seem like a construct similar to other languages, but in fact it is an expression like every other looping construct in Ruby. In fact, the for in works with Enumerable objects just as the each iterator.

The collection passed to for in can be any object that has an each iterator method. Arrays and hashes define the each method, and many other Ruby objects do, too. The for/in loop calls the each method of the specified object. As that iterator yields values, the for loop assigns each value (or each set of values) to the specified variable (or variables) and then executes the code in body.

This is a silly example, but illustrates the point that the for in loop works with ANY object that has an each method, just like how the each iterator does:

class Apple
  TYPES = %w(red green yellow)
  def each
    yield TYPES.pop until TYPES.empty?
  end
end

a = Apple.new
for i in a do
  puts i
end
yellow
green
red
=> nil

And now the each iterator:

a = Apple.new
a.each do |i|
  puts i
end
yellow
green
red
=> nil

As you can see, both are responding to the each method which yields values back to the block. As everyone here stated, it is definitely preferable to use the each iterator over the for in loop. I just wanted to drive home the point that there is nothing magical about the for in loop. It is an expression that invokes the each method of a collection and then passes it to its block of code. Hence, it is a very rare case you would need to use for in. Use the each iterator almost always (with the added benefit of block scope).

Toolbar Navigation Hamburger Icon missing

Maybe you can try this, but you will lose animation between arrow and hamburger icon

@Override
protected void onCreate(Bundle arg0) {
    super.onCreate(arg0);
    super.setContentView(R.layout.activity_menu_drawer_left);

_drawerToggle = new ActionBarDrawerToggle(this, _drawerLayout, R.string.drawer_opened, R.string.drawer_closed) {
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            changeDrawerIconOnDrawerClick(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
        }

        /** Called when a drawer has settled in a completely closed state. */
        public void onDrawerClosed(View view) {
            super.onDrawerClosed(view);
            changeDrawerIconOnDrawerClick(R.drawable.ic_drawer);
        }
    };

     //to change default icon to hamburger item initially
    changeDrawerIconOnDrawerClick(R.drawable.ic_drawer);    }



private void changeDrawerIconOnDrawerClick(int resourceId) {
    //Drawable icon = ContextCompat.getDrawable(getApplicationContext(), resourceId);
    Drawable icon = ResourcesCompat.getDrawable(getResources(), resourceId, null);
    icon.setColorFilter(getResources().getColor(R.color.white), PorterDuff.Mode.SRC_ATOP);
    _drawerToggle.setDrawerIndicatorEnabled(false);
    _drawerToggle.setHomeAsUpIndicator(icon);
}

Differences between dependencyManagement and dependencies in Maven

It's like you said; dependencyManagementis used to pull all the dependency information into a common POM file, simplifying the references in the child POM file.

It becomes useful when you have multiple attributes that you don't want to retype in under multiple children projects.

Finally, dependencyManagement can be used to define a standard version of an artifact to use across multiple projects.

Setting up and using Meld as your git difftool and mergetool

This is an answer targeting primarily developers using Windows, as the path syntax of the diff tool differs from other platforms.

I use Kdiff3 as the git mergetool, but to set up the git difftool as Meld, I first installed the latest version of Meld from Meldmerge.org then added the following to my global .gitconfig using:

git config --global -e

Note, if you rather want Sublime Text 3 instead of the default Vim as core ditor, you can add this to the .gitconfig file:

[core]
editor = 'c:/Program Files/Sublime Text 3/sublime_text.exe'

Then you add inn Meld as the difftool

[diff]
tool = meld
guitool = meld 

[difftool "meld"]
cmd = \"C:/Program Files (x86)/Meld/Meld.exe\" \"$LOCAL\" \"$REMOTE\" --label \"DIFF 
(ORIGINAL MY)\"
prompt = false
path = C:\\Program Files (x86)\\Meld\\Meld.exe

Note the leading slash in the cmd above, on Windows it is necessary.

It is also possible to set up an alias to show the current git diff with a --dir-diff option. This will list the changed files inside Meld, which is handy when you have altered multiple files (a very common scenario indeed).

The alias looks like this inside the .gitconfig file, beneath [alias] section:

showchanges = difftool --dir-diff

To show the changes I have made to the code I then just enter the following command:

git showchanges

The following image shows how this --dir-diff option can show a listing of changed files (example): Meld showing list of files with changes between the $LOCAL and $REMOTE

Then it is possible to click on each file and show the changes inside Meld.

How to configure socket connect timeout

I had the Same problem when connecting to a Socket and I came up with the below solution ,It works Fine for me. `

private bool CheckConnectivityForProxyHost(string hostName, int port)
       {
           if (string.IsNullOrEmpty(hostName))
               return false;

           bool isUp = false;
           Socket testSocket = null;

           try
           {

               testSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
               IPAddress ip = null;
               if (testSocket != null && NetworkingCollaboratorBase.GetResolvedConnecionIPAddress(hostName, out ip))//Use a method to resolve your IP
               {
                   IPEndPoint ipEndPoint = new IPEndPoint(ip, port);

                   isUp = false;
//time out 5 Sec
                  CallWithTimeout(ConnectToProxyServers, 5000, testSocket, ipEndPoint);

                       if (testSocket != null && testSocket.Connected)
                       {
                           isUp = true;
                       }
                   }

               }
           }
           catch (Exception ex)
           {
               isUp = false;
           }
           finally
           {
               try
               {
                   if (testSocket != null)
                   {
                       testSocket.Shutdown(SocketShutdown.Both);
                   }
               }
               catch (Exception ex)
               {

               }
               finally
               {
                   if (testSocket != null)
                       testSocket.Close();
               }

           }

           return isUp;
       }


 private void CallWithTimeout(Action<Socket, IPEndPoint> action, int timeoutMilliseconds, Socket socket, IPEndPoint ipendPoint)
       {
           try
           {
               Action wrappedAction = () =>
               {
                   action(socket, ipendPoint);
               };

               IAsyncResult result = wrappedAction.BeginInvoke(null, null);

               if (result.AsyncWaitHandle.WaitOne(timeoutMilliseconds))
               {
                   wrappedAction.EndInvoke(result);
               }

           }
           catch (Exception ex)
           {

           }
       }

  private void ConnectToProxyServers(Socket testSocket, IPEndPoint ipEndPoint)
       {
           try
           {
               if (testSocket == null || ipEndPoint == null)
                   return;

                   testSocket.Connect(ipEndPoint);

           }
           catch (Exception ex)
           {

           }
       } 

Confirm postback OnClientClick button ASP.NET

try this :

<asp:Button runat="server" ID="btnUserDelete" Text="Delete" CssClass="GreenLightButton" 
   onClientClick=" return confirm('Are you sure you want to delete this user?')" 
   OnClick="BtnUserDelete_Click"  meta:resourcekey="BtnUserDeleteResource1"  />

How to get selenium to wait for ajax response?

In my case the issue seemed due to ajax delays but was related to internal iframes inside the main page. In seleminum it is possible to switch to internal frames with:

    driver.switchTo().frame("body");
    driver.switchTo().frame("bodytab");

I use java. After that I was able to locate the element

    driver.findElement(By.id("e_46")).click();

How to return a PNG image from Jersey REST service method to the browser

in regard of answer from @Perception, its true to be very memory-consuming when working with byte arrays, but you could also simply write back into the outputstream

@Path("/picture")
public class ProfilePicture {
  @GET
  @Path("/thumbnail")
  @Produces("image/png")
  public StreamingOutput getThumbNail() {
    return new StreamingOutput() {
      @Override
      public void write(OutputStream os) throws IOException, WebApplicationException {
        //... read your stream and write into os
      }
    };
  }
}

Can I underline text in an Android layout?

Most Easy Way

TextView tv = findViewById(R.id.tv);
tv.setText("some text");
setUnderLineText(tv, "some");

Also support TextView childs like EditText, Button, Checkbox

public void setUnderLineText(TextView tv, String textToUnderLine) {
        String tvt = tv.getText().toString();
        int ofe = tvt.indexOf(textToUnderLine, 0);

        UnderlineSpan underlineSpan = new UnderlineSpan();
        SpannableString wordToSpan = new SpannableString(tv.getText());
        for (int ofs = 0; ofs < tvt.length() && ofe != -1; ofs = ofe + 1) {
            ofe = tvt.indexOf(textToUnderLine, ofs);
            if (ofe == -1)
                break;
            else {
                wordToSpan.setSpan(underlineSpan, ofe, ofe + textToUnderLine.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                tv.setText(wordToSpan, TextView.BufferType.SPANNABLE);
            }
        }
    }

If you want

- Clickable underline text?

- Underline multiple parts of TextView?

Then Check This Answer

Count the Number of Tables in a SQL Server Database

USE MyDatabase
SELECT Count(*)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE';

to get table counts

SELECT COUNT(*)
FROM information_schema.tables
WHERE table_schema = 'dbName';

this also works

USE databasename;
SHOW TABLES;
SELECT FOUND_ROWS();

Angular.js vs Knockout.js vs Backbone.js

It depends on the nature of your application. And, since you did not describe it in great detail, it is an impossible question to answer. I find Backbone to be the easiest, but I work in Angular all day. Performance is more up to the coder than the framework, in my opinion.

Are you doing heavy DOM manipulation? I would use jQuery and Backbone.

Very data driven app? Angular with its nice data binding.

Game programming? None - direct to canvas; maybe a game engine.

Visual Studio Copy Project

I use Visual Studio 2013 where Project > Export Template is not an option. Here is what I use to clone a project.

From your solution: File > Export Template > select project to make template from, note save path

Download and install VS 2013 SDK Here

Create new VSIX project under Extensibility

From the VSIXManifest Dialog select the Assets tab

Fill in the Author textbox

Choose "Project Template" for Type and Browse to add the exported template (saved at path you noted in step 1)

Save and build the VSIX project. Go to the VSIX project's .../bin/Debug folder and double click to run the .vsix file

Start new instance of Visual Studio and you should see your template under whatever project type your template is. Create a new project from your template

You will have to re-add any dll references

Error: vector does not name a type

Also you can add #include<vector> in the header. When two of the above solutions don't work.

Python 3: ImportError "No Module named Setuptools"

EDIT: Official setuptools dox page:

If you have Python 2 >=2.7.9 or Python 3 >=3.4 installed from python.org, you will already have pip and setuptools, but will need to upgrade to the latest version:

On Linux or OS X:

pip install -U pip setuptools 

On Windows:

python -m pip install -U pip setuptools

Therefore the rest of this post is probably obsolete (e.g. some links don't work).

Distribute - is a setuptools fork which "offers Python 3 support". Installation instructions for distribute(setuptools) + pip:

curl -O http://python-distribute.org/distribute_setup.py
python distribute_setup.py
easy_install pip

Similar issue here.

UPDATE: Distribute seems to be obsolete, i.e. merged into Setuptools: Distribute is a deprecated fork of the Setuptools project. Since the Setuptools 0.7 release, Setuptools and Distribute have merged and Distribute is no longer being maintained. All ongoing effort should reference the Setuptools project and the Setuptools documentation.

You may try with instructions found on setuptools pypi page (I haven't tested this, sorry :( ):

wget https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py -O - | python
easy_install pip

How do I paste multi-line bash codes into terminal and run it all at once?

Try

out=$(cat)

Then paste your lines and press Ctrl-D (insert EOF character). All input till Ctrl-D will be redirected to cat's stdout.

How can I time a code segment for testing performance with Pythons timeit?

Focus on one specific thing. Disk I/O is slow, so I'd take that out of the test if all you are going to tweak is the database query.

And if you need to time your database execution, look for database tools instead, like asking for the query plan, and note that performance varies not only with the exact query and what indexes you have, but also with the data load (how much data you have stored).

That said, you can simply put your code in a function and run that function with timeit.timeit():

def function_to_repeat():
    # ...

duration = timeit.timeit(function_to_repeat, number=1000)

This would disable the garbage collection, repeatedly call the function_to_repeat() function, and time the total duration of those calls using timeit.default_timer(), which is the most accurate available clock for your specific platform.

You should move setup code out of the repeated function; for example, you should connect to the database first, then time only the queries. Use the setup argument to either import or create those dependencies, and pass them into your function:

def function_to_repeat(var1, var2):
    # ...

duration = timeit.timeit(
    'function_to_repeat(var1, var2)',
    'from __main__ import function_to_repeat, var1, var2', 
    number=1000)

would grab the globals function_to_repeat, var1 and var2 from your script and pass those to the function each repetition.

Python string.replace regular expression

re.sub is definitely what you are looking for. And so you know, you don't need the anchors and the wildcards.

re.sub(r"(?i)interfaceOpDataFile", "interfaceOpDataFile %s" % filein, line)

will do the same thing--matching the first substring that looks like "interfaceOpDataFile" and replacing it.

Jquery - animate height toggle

Worked for me:

$(".filter-mobile").click(function() {
   if ($("#menuProdutos").height() > 0) {
      $("#menuProdutos").animate({
         height: 0
      }, 200);
   } else {
      $("#menuProdutos").animate({
         height: 500
      }, 200);
   }
});

Left-pad printf with spaces

If you want exactly 40 spaces before the string then you should just do:

printf("                                        %s\n", myStr );

If that is too dirty, you can do (but it will be slower than manually typing the 40 spaces): printf("%40s%s", "", myStr );

If you want the string to be lined up at column 40 (that is, have up to 39 spaces proceeding it such that the right most character is in column 40) then do this: printf("%40s", myStr);

You can also put "up to" 40 spaces AfTER the string by doing: printf("%-40s", myStr);

Practical uses of git reset --soft?

Another potential use is as an alternative to stashing (which some people don't like, see e.g. https://codingkilledthecat.wordpress.com/2012/04/27/git-stash-pop-considered-harmful/).

For example, if I'm working on a branch and need to fix something urgently on master, I can just do:

git commit -am "In progress."

then checkout master and do the fix. When I'm done, I return to my branch and do

git reset --soft HEAD~1

to continue working where I left off.

latex large division sign in a math formula

Another option is to use \dfrac instead of \frac, which makes the whole fraction larger and hence more readable.

And no, I don't know if there is an option to get something in between \frac and \dfrac, sorry.

403 Forbidden You don't have permission to access /folder-name/ on this server

**403 Forbidden **

You don't have permission to access /Folder-Name/ on this server**

The solution for this problem is:

1.go to etc/apache2/apache2.conf

2.find the below code and change AllowOverride all to AllowOverride none

 <Directory /var/www/>
    Options Indexes FollowSymLinks
    AllowOverride all      Change this to--->  AllowOverride none
    Require all granted
 </Directory>

It will work fine on your Ubuntu server

Where does forever store console.log output?

You need to add the log destination specifiers before the filename to run. So

forever -e /path/error.txt -o /path/output.txt start index.js

How to disable an input box using angular.js

<input type="text" input-disabled="editableInput" />
<button ng-click="editableInput = !editableInput">enable/disable</button>

app.controller("myController", function(){
  $scope.editableInput = false;
});

app.directive("inputDisabled", function(){
  return function(scope, element, attrs){
    scope.$watch(attrs.inputDisabled, function(val){
      if(val)
        element.removeAttr("disabled");
      else
        element.attr("disabled", "disabled");
    });
  }
});

How do I clear/delete the current line in terminal?

I have the complete shortcuts list:

  1. Ctrl+a Move cursor to start of line
  2. Ctrl+e Move cursor to end of line
  3. Ctrl+b Move back one character
  4. Alt+b Move back one word
  5. Ctrl+f Move forward one character
  6. Alt+f Move forward one word
  7. Ctrl+d Delete current character
  8. Ctrl+w Cut the last word
  9. Ctrl+k Cut everything after the cursor
  10. Alt+d Cut word after the cursor
  11. Alt+w Cut word before the cursor
  12. Ctrl+y Paste the last deleted command
  13. Ctrl+_ Undo
  14. Ctrl+u Cut everything before the cursor
  15. Ctrl+xx Toggle between first and current position
  16. Ctrl+l Clear the terminal
  17. Ctrl+c Cancel the command
  18. Ctrl+r Search command in history - type the search term
  19. Ctrl+j End the search at current history entry
  20. Ctrl+g Cancel the search and restore original line
  21. Ctrl+n Next command from the History
  22. Ctrl+p previous command from the History

top nav bar blocking top content of the page

As seen on this example from Twitter, add this before the line that includes the responsive styles declarations:

<style> 
    body {
        padding-top: 60px;
    }
</style>

Like so:

<link href="Z/bootstrap/css/bootstrap.min.css" rel="stylesheet" />
<style type="text/css">
    body {
        padding-top: 60px;
    }
</style>
<link href="Z/bootstrap/css/bootstrap-responsive.min.css" rel="stylesheet" />

How to invert a grep expression

As stated multiple times, inversion is achieved by the -v option to grep. Let me add the (hopefully amusing) note that you could have figured this out yourself by grepping through the grep help text:

grep --help | grep invert

-v, --invert-match select non-matching lines

Search a whole table in mySQL for a string

A PHP Based Solution for search entire table ! Search string is $string . This is generic and will work with all the tables with any number of fields

$sql="SELECT * from client_wireless";
$sql_query=mysql_query($sql);
$logicStr="WHERE ";
$count=mysql_num_fields($sql_query);
for($i=0 ; $i < mysql_num_fields($sql_query) ; $i++){
 if($i == ($count-1) )
$logicStr=$logicStr."".mysql_field_name($sql_query,$i)." LIKE '%".$string."%' ";
else
$logicStr=$logicStr."".mysql_field_name($sql_query,$i)." LIKE '%".$string."%' OR ";
}
// start the search in all the fields and when a match is found, go on printing it .
$sql="SELECT * from client_wireless ".$logicStr;
//echo $sql;
$query=mysql_query($sql);

Serializing enums with Jackson

An easy way to serialize Enum is using @JsonFormat annotation. @JsonFormat can configure the serialization of a Enum in three ways.

@JsonFormat.Shape.STRING
public Enum OrderType {...}

uses OrderType::name as the serialization method. Serialization of OrderType.TypeA is “TYPEA”

@JsonFormat.Shape.NUMBER
Public Enum OrderTYpe{...}

uses OrderType::ordinal as the serialization method. Serialization of OrderType.TypeA is 1

@JsonFormat.Shape.OBJECT
Public Enum OrderType{...}

treats OrderType as a POJO. Serialization of OrderType.TypeA is {"id":1,"name":"Type A"}

JsonFormat.Shape.OBJECT is what you need in your case.

A little more complicated way is your solution, specifying a serializer for the Enum.

Check out this reference: https://fasterxml.github.io/jackson-annotations/javadoc/2.2.0/com/fasterxml/jackson/annotation/JsonFormat.html

Default value in an asp.net mvc view model

In case you need to post the same model to server the solution with having default bool value in constructor would not be viable for you. Let's imagine that you have following model:

public class SearchModel
{
    public bool IsMale { get; set; }

    public SearchModel()
    { 
        IsMale = true;
    }
}

On view you would have something like this:

@Html.CheckBoxFor(n => n.IsMale)

The problem is when user uncheck this checkbox and post it to the server - you would end up with default value set up in constructor (which in this case is true).

So in this case I would end up with just specifying default value on view:

@Html.CheckBoxFor(n => n.IsMale, new { @checked = "checked" })

Android Studio: Default project directory

This worked for me Android Studio 4.0.1:

  1. Close Android Studio.

  2. Navigate to C:\Users[Username].AndroidStudio4.0\config\options

  3. Locate recentProjects.xml and open it.

  4. Scroll down the page you will notice: <option name="lastProjectLocation" value="$USER_HOME$/AndroidStudioProjects" />

  5. Change $USER_HOME$/AndroidStudioProjects to your desired location: /home/USER/AndroidStudioProjects/

  6. Reopen Android studio.

NameError: global name is not defined

try

from sqlitedbx import SqliteDBzz

How to split a number into individual digits in c#?

Substring and Join methods are usable for this statement.

string no = "12345";
string [] numberArray = new string[no.Length];
int counter = 0;

   for (int i = 0; i < no.Length; i++)
   {
     numberArray[i] = no.Substring(counter, 1); // 1 is split length
     counter++;
   }

Console.WriteLine(string.Join(" ", numberArray)); //output >>> 0 1 2 3 4 5

Generate sql insert script from excel worksheet

Here is a link to an Online automator to convert CSV files to SQL Insert Into statements:

CSV-to-SQL

Closure in Java 7

According to Tom Hawtin

A closure is a block of code that can be referenced (and passed around) with access to the variables of the enclosing scope.

Now I'm trying to emulate the JavaScript closure example on Wikipedia, with a "straigth" translation to Java, in the hope to be useful:

//ECMAScript
var f, g;
function foo() {
  var x = 0;
  f = function() { return ++x; };
  g = function() { return --x; };
  x = 1;
  print('inside foo, call to f(): ' + f()); // "2"  
}
foo();
print('call to g(): ' + g()); // "1"
print('call to f(): ' + f()); // "2"

Now the java part: Function1 is "Functor" interface with arity 1 (one argument). Closure is the class implementing the Function1, a concrete Functor that acts as function (int -> int). In the main() method I just instantiate foo as a Closure object, replicating the calls from the JavaScript example. The IntBox class is just a simple container, it behave like an array of 1 int:

int a[1] = {0}

interface Function1   {
    public final IntBag value = new IntBag();
    public int apply();
}

class Closure implements Function1 {
   private IntBag x = value;
   Function1 f;
   Function1 g;

   @Override
   public int apply()  {
    // print('inside foo, call to f(): ' + f()); // "2"
    // inside apply, call to f.apply()
       System.out.println("inside foo, call to f.apply(): " + f.apply());
       return 0;
   }

   public Closure() {
       f = new Function1() {
           @Override
           public int apply()  {
               x.add(1);
                return x.get();
           }
       };
       g = new Function1() {
           @Override
           public int apply()  {
               x.add(-1);
               return x.get();
           }
       };
    // x = 1;
       x.set(1);
   }
}
public class ClosureTest {
    public static void main(String[] args) {
        // foo()
        Closure foo = new Closure();
        foo.apply();
        // print('call to g(): ' + g()); // "1"
        System.out.println("call to foo.g.apply(): " + foo.g.apply());
        // print('call to f(): ' + f()); // "2"
        System.out.println("call to foo.f.apply(): " + foo.f.apply());

    }
}

It prints:

inside foo, call to f.apply(): 2
call to foo.g.apply(): 1
call to foo.f.apply(): 2 

How to print a string multiple times?

def repeat_char_rows_cols(char, rows, cols):
    return (char*cols + '\n')*rows

>>> print(repeat_char_rows_cols('@', 4, 2))
@@
@@
@@
@@

How to get the 'height' of the screen using jquery

$(window).height();   // returns height of browser viewport
$(document).height(); // returns height of HTML document

As documented here: http://api.jquery.com/height/

HTML-Tooltip position relative to mouse pointer

For default tooltip behavior simply add the title attribute. This can't contain images though.

<div title="regular tooltip">Hover me</div>

Before you clarified the question I did this up in pure JavaScript, hope you find it useful. The image will pop up and follow the mouse.

jsFiddle

JavaScript

var tooltipSpan = document.getElementById('tooltip-span');

window.onmousemove = function (e) {
    var x = e.clientX,
        y = e.clientY;
    tooltipSpan.style.top = (y + 20) + 'px';
    tooltipSpan.style.left = (x + 20) + 'px';
};

CSS

.tooltip span {
    display:none;
}
.tooltip:hover span {
    display:block;
    position:fixed;
    overflow:hidden;
}

Extending for multiple elements

One solution for multiple elements is to update all tooltip span's and setting them under the cursor on mouse move.

jsFiddle

var tooltips = document.querySelectorAll('.tooltip span');

window.onmousemove = function (e) {
    var x = (e.clientX + 20) + 'px',
        y = (e.clientY + 20) + 'px';
    for (var i = 0; i < tooltips.length; i++) {
        tooltips[i].style.top = y;
        tooltips[i].style.left = x;
    }
};

Error: JAVA_HOME is not defined correctly executing maven

Use these two commands (for Java 8):

sudo update-java-alternatives --set java-8-oracle
java -XshowSettings 2>&1 | grep -e 'java.home' | awk '{print "JAVA_HOME="$3}' | sed "s/\/jre//g" >> /etc/environment

In PowerShell, how can I test if a variable holds a numeric value?

If you want to check if a string has a numeric value, use this code:

$a = "44.4"
$b = "ad"
$rtn = ""
[double]::TryParse($a,[ref]$rtn)
[double]::TryParse($b,[ref]$rtn)

Credits go here

Using Java with Nvidia GPUs (CUDA)

I'd start by using one of the projects out there for Java and CUDA: http://www.jcuda.org/

JSP : JSTL's <c:out> tag

As said Will Wagner, in old version of jsp you should always use c:out to output dynamic text.

Moreover, using this syntax:

<c:out value="${person.name}">No name</c:out>

you can display the text "No name" when name is null.

Android button with different background colors

You have to put the selector.xml file in the drwable folder. Then write: android:background="@drawable/selector". This takes care of the pressed and focussed states.

fileReader.readAsBinaryString to upload files

Use fileReader.readAsDataURL( fileObject ), this will encode it to base64, which you can safely upload to your server.

What is the meaning of "__attribute__((packed, aligned(4))) "

The attribute packed means that the compiler will not add padding between fields of the struct. Padding is usually used to make fields aligned to their natural size, because some architectures impose penalties for unaligned access or don't allow it at all.

aligned(4) means that the struct should be aligned to an address that is divisible by 4.

How to read a single character from the user?

A comment in one of the other answers mentioned cbreak mode, which is important for Unix implementations because you generally don't want ^C (KeyboardError) to be consumed by getchar (as it will when you set the terminal to raw mode, as done by most other answers).

Another important detail is that if you're looking to read one character and not one byte, you should read 4 bytes from the input stream, as that's the maximum number of bytes a single character will consist of in UTF-8 (Python 3+). Reading only a single byte will produce unexpected results for multi-byte characters such as keypad arrows.

Here's my changed implementation for Unix:

import contextlib
import os
import sys
import termios
import tty


_MAX_CHARACTER_BYTE_LENGTH = 4


@contextlib.contextmanager
def _tty_reset(file_descriptor):
    """
    A context manager that saves the tty flags of a file descriptor upon
    entering and restores them upon exiting.
    """
    old_settings = termios.tcgetattr(file_descriptor)
    try:
        yield
    finally:
        termios.tcsetattr(file_descriptor, termios.TCSADRAIN, old_settings)


def get_character(file=sys.stdin):
    """
    Read a single character from the given input stream (defaults to sys.stdin).
    """
    file_descriptor = file.fileno()
    with _tty_reset(file_descriptor):
        tty.setcbreak(file_descriptor)
        return os.read(file_descriptor, _MAX_CHARACTER_BYTE_LENGTH)

Vim multiline editing like in sublimetext?

if you use the "global" command, you can repeat what you can do on one online an any number of lines.

:g/<search>/.<your ex command>

example:

:g/foo/.s/bar/baz/g

The above command finds all lines that have foo, and replace all occurrences of bar on that line with baz.

:g/.*/

will do on every line

UINavigationBar custom back button without title

You don't have access to the navigation backButtonItem with the way you want, you need to create your own back button like below:

- (void)loadView
{
    [super loadView];
    UIButton *backButton = [[UIButton alloc] initWithFrame: CGRectMake(0, 0, 44.0f, 30.0f)];
    [backButton setImage:[UIImage imageNamed:@"back.png"]  forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(popVC) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
}

And off course:

- (void) popVC{
  [self.navigationController popViewControllerAnimated:YES];
}

Table overflowing outside of div

You can prevent tables from expanding beyond their parent div by using table-layout:fixed.

The CSS below will make your tables expand to the width of the div surrounding it.

table 
{
    table-layout:fixed;
    width:100%;
}

I found this trick here.

Tkinter: How to use threads to preventing main event loop from "freezing"

I have used RxPY which has some nice threading functions to solve this in a fairly clean manner. No queues, and I have provided a function that runs on the main thread after completion of the background thread. Here is a working example:

import rx
from rx.scheduler import ThreadPoolScheduler
import time
import tkinter as tk

class UI:
   def __init__(self):
      self.root = tk.Tk()
      self.pool_scheduler = ThreadPoolScheduler(1) # thread pool with 1 worker thread
      self.button = tk.Button(text="Do Task", command=self.do_task).pack()

   def do_task(self):
      rx.empty().subscribe(
         on_completed=self.long_running_task, 
         scheduler=self.pool_scheduler
      )

   def long_running_task(self):
      # your long running task here... eg:
      time.sleep(3)
      # if you want a callback on the main thread:
      self.root.after(5, self.on_task_complete)

   def on_task_complete(self):
       pass # runs on main thread

if __name__ == "__main__":
    ui = UI()
    ui.root.mainloop()

Another way to use this construct which might be cleaner (depending on preference):

tk.Button(text="Do Task", command=self.button_clicked).pack()

...

def button_clicked(self):

   def do_task(_):
      time.sleep(3) # runs on background thread
             
   def on_task_done():
      pass # runs on main thread

   rx.just(1).subscribe(
      on_next=do_task, 
      on_completed=lambda: self.root.after(5, on_task_done), 
      scheduler=self.pool_scheduler
   )

pip: no module named _internal

I have the same problem on my virtual environment after upgrade python installation from 3.6 to 3.7 but only on vent globally pip work fine, to solve it I deactivate and delete my virtual environment after recreate again and now is fine, on venv:

deactivate
rm -rvf venv 

and after recreate the virtual environment. I use mac OS 10.11, and python 3

how do you increase the height of an html textbox

Don't the height and font-size CSS properties work for you ?

How to get disk capacity and free space of remote computer

PS> Get-CimInstance -ComputerName bobPC win32_logicaldisk | where caption -eq "C:" | foreach-object {write " $($_.caption) $('{0:N2}' -f ($_.Size/1gb)) GB total, $('{0:N2}' -f ($_.FreeSpace/1gb)) GB free "}  
C: 117.99 GB total, 16.72 GB free 

PS> 

What's the best way to generate a UML diagram from Python source code?

If you use eclipse, maybe PyUML. Haven't used it, though.

android:drawableLeft margin and/or padding

You can use a padding for the button and you can play with drawablePadding

 <Button
    style="@style/botonesMenu"
    android:padding="15dp"
    android:drawablePadding="-15dp"
    android:text="@string/actualizarBD"
    android:textAlignment="gravity"
    android:gravity="center"
    android:layout_row="1"
    android:layout_column="0"
    android:drawableTop="@drawable/actualizar"
    android:id="@+id/btnActualizar"
    android:onClick="actualizarBD" />

you can use a specific padding depends where put your drawable, with android:paddingLeft="10dp" or android:paddingBottom="10dp" or android:paddingRight="10dp" or android:paddingTop="10dp"

How do I unload (reload) a Python module?

For those like me who want to unload all modules (when running in the Python interpreter under Emacs):

   for mod in sys.modules.values():
      reload(mod)

More information is in Reloading Python modules.

Space between border and content? / Border distance from content?

You usually use padding to add distance between a border and a content.However, background are spread on padding.

You can still do it with nested element.

html :

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

outter div :

border-style: ridge;
border-color: #567498;
border-spacing:10px;
min-width: 100px;
min-height: 100px;
float:left;

inner div :

width: 100px;
min-height: 100px;
margin: 10px;
background-image: -webkit-gradient(
    linear,
    left bottom,
    left top,
    color-stop(0, rgb(39,54,73)),
    color-stop(1, rgb(30,42,54))
);
background-image: -moz-linear-gradient(
    center bottom,
    rgb(39,54,73) 0%,
    rgb(30,42,54) 100%
        );}

What is an abstract class in PHP?

An abstract class is a class that is only partially implemented by the programmer. It may contain one or more abstract methods. An abstract method is simply a function definition that serves to tell the programmer that the method must be implemented in a child class.

There is good explanation of that here.

With form validation: why onsubmit="return functionname()" instead of onsubmit="functionname()"?

An extension to what GenericTypeTea says - Here is a concrete example:

<form onsubmit="return false">

The above form will not submit, whereas...

<form onsubmit="false">

...does nothing, i.e. the form will submit.

Without the return, onsubmit doesn't receive a value and the event is executed just like without any handler at all.

Auto Increment after delete in MySQL

Its definitely not recommendable. If you have a large database with multiple tables, you may probably have saved a userid as id in table 2. if you rearrange table 1 then probably the intended userid will not end up being the intended table 2 id.

jQuery's .click - pass parameters to user function

For thoroughness, I came across another solution which was part of the functionality introduced in version 1.4.3 of the jQuery click event handler.

It allows you to pass a data map to the event object that automatically gets fed back to the event handler function by jQuery as the first parameter. The data map would be handed to the .click() function as the first parameter, followed by the event handler function.

Here's some code to illustrate what I mean:

// say your selector and click handler looks something like this...
$("some selector").click({param1: "Hello", param2: "World"}, cool_function);

// in your function, just grab the event object and go crazy...
function cool_function(event){
    alert(event.data.param1);
    alert(event.data.param2);
}

I know it's late in the game for this question, but the previous answers led me to this solution, so I hope it helps someone sometime!

splitting a string based on tab in the file

Python has support for CSV files in the eponymous csv module. It is relatively misnamed since it support much more that just comma separated values.

If you need to go beyond basic word splitting you should take a look. Say, for example, because you are in need to deal with quoted values...

Accessing a resource via codebehind in WPF

You can use a resource key like this:

<UserControl.Resources>
    <SolidColorBrush x:Key="{x:Static local:Foo.MyKey}">Blue</SolidColorBrush>
</UserControl.Resources>
<Grid Background="{StaticResource {x:Static local:Foo.MyKey}}" />

public partial class Foo : UserControl
{
    public Foo()
    {
        InitializeComponent();
        var brush = (SolidColorBrush)FindResource(MyKey);
    }

    public static ResourceKey MyKey { get; } = CreateResourceKey();

    private static ComponentResourceKey CreateResourceKey([CallerMemberName] string caller = null)
    {
        return new ComponentResourceKey(typeof(Foo), caller); ;
    }
}

Jenkins, specifying JAVA_HOME

i saw into Eclipse > Preferences>installed JREs > JRE Definition i found the directory of java_home so it's /Library/Java/JavaVirtualMachines/jdk1.7.0_17.jdk/Contents/Home

How to make a <div> or <a href="#"> to align center

You can use css like below;

 <a href="contact.html" style="margin:auto; text-align:center; display:block;" class="button large hpbottom">Get Started</a>

How to set a default Value of a UIPickerView

I too had this problem. But apparently there is an issue of the order of method calls. You must call:

[self.picker selectRow:2 inComponent:0 animated:YES];

after calling

[self.view addSubview:self.picker];

How can I use async/await at the top level?

Top-Level await has moved to stage 3, so the answer to your question How can I use async/await at the top level? is to just add await the call to main() :

async function main() {
    var value = await Promise.resolve('Hey there');
    console.log('inside: ' + value);
    return value;
}

var text = await main();  
console.log('outside: ' + text)

Or just:

const text = await Promise.resolve('Hey there');
console.log('outside: ' + text)

Compatibility

JQuery or JavaScript: How determine if shift key being pressed while clicking anchor tag hyperlink?

var shiftDown = false;
this.onkeydown = function(evt){
    var evt2 = evt || window.event;
    var keyCode = evt2.keyCode || evt2.which;       
    if(keyCode==16)shiftDown = true;
}
this.onkeyup = function(){
    shiftDown = false;
}

demo

Parse query string into an array

There are several possible methods, but for you, there is already a builtin parse_str function

$array = array();
parse_str($string, $array);
var_dump($array);

How disable / remove android activity label and label bar?

You have two ways to hide the title bar by hiding it in a specific activity or hiding it on all of the activity in your app.

You can achieve this by create a custom theme in your styles.xml.

<resources>
    <style name="MyTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>
</resources>

If you are using AppCompatActivity, there is a bunch of themes that android provides nowadays. And if you choose a theme that has .NoActionBaror .NoTitleBar. It will disable you action bar for your theme.

After setting up a custom theme, you might want to use the theme in you activity/activities. Go to manifest and choose the activity that you want to set the theme on.

SPECIFIC ACTIVITY

AndroidManifest.xml

<application
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name">

    <activity android:name=".FirstActivity"
        android:label="@string/app_name"
        android:theme="@style/MyTheme">
    </activity>
</application>

Notice that I have set the FirstActivity theme to the custom theme MyTheme. This way the theme will only be affected on certain activity. If you don't want to hide toolbar for all your activity then try this approach.

The second approach is where you set the theme to all of your activity.

ALL ACTIVITY

<application
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/MyTheme">

    <activity android:name=".FirstActivity"
        android:label="@string/app_name">
    </activity>
</application>

Notice that I have set the application theme to the custom theme MyTheme. This way the theme will only be affected on all of activity. If you want to hide toolbar for all your activity then try this approach instead.

python: restarting a loop

Changing the index variable i from within the loop is unlikely to do what you expect. You may need to use a while loop instead, and control the incrementing of the loop variable yourself. Each time around the for loop, i is reassigned with the next value from range(). So something like:

i = 2
while i < n:
    if(something):
        do something
    else:
        do something else
        i = 2 # restart the loop
        continue
    i += 1

In my example, the continue statement jumps back up to the top of the loop, skipping the i += 1 statement for that iteration. Otherwise, i is incremented as you would expect (same as the for loop).

How can I determine installed SQL Server instances and their versions?

-- T-SQL Query to find list of Instances Installed on a machine

DECLARE @GetInstances TABLE
( Value nvarchar(100),
 InstanceNames nvarchar(100),
 Data nvarchar(100))

Insert into @GetInstances
EXECUTE xp_regread
  @rootkey = 'HKEY_LOCAL_MACHINE',
  @key = 'SOFTWARE\Microsoft\Microsoft SQL Server',
  @value_name = 'InstalledInstances'

Select InstanceNames from @GetInstances 

How to find out mySQL server ip address from phpmyadmin

As an alternative, since you know the hostname, resolve the database server IP via hostname from the web server.

http://php.net/manual/en/function.gethostbyname.php

iPad Safari scrolling causes HTML elements to disappear and reappear with a delay

I faced this problem in a Framework7 & Cordova project. I tried all the solutions above. They did not solve my problem.

In my case, I was using 10+ css animations on the same page with infinite rotation (transform). I had to remove the animations. It is ok now with the lack of some visual features.

If the solutions above do not help you, you may start eliminating some animations.

Simple function to sort an array of objects

var data = [ 1, 2, 5, 3, 1]; data.sort(function(a,b) { return a-b });

With a small compartor and using sort, we can do it

Is there a typical state machine implementation pattern?

For compiler which support __COUNTER__ , you can use them for simple (but large) state mashines.

  #define START 0      
  #define END 1000

  int run = 1;
  state = START;    
  while(run)
  {
    switch (state)
    {
        case __COUNTER__:
            //do something
            state++;
            break;
        case __COUNTER__:
            //do something
            if (input)
               state = END;
            else
               state++;
            break;
            .
            .
            .
        case __COUNTER__:
            //do something
            if (input)
               state = START;
            else
               state++;
            break;
        case __COUNTER__:
            //do something
            state++;
            break;
        case END:
            //do something
            run = 0;
            state = START;
            break;
        default:
            state++;
            break;
     } 
  } 

The advantage of using __COUNTER__ instead of hard coded numbers is that you can add states in the middle of other states, without renumbering everytime everything. If the compiler doesnt support __COUNTER__, in a limited way its posible to use with precaution __LINE__

Passing parameter to controller action from a Html.ActionLink

You are using incorrect overload. You should use this overload

public static MvcHtmlString ActionLink(
    this HtmlHelper htmlHelper,
    string linkText,
    string actionName,
    string controllerName,
    Object routeValues,
    Object htmlAttributes
) 

And the correct code would be

<%= Html.ActionLink("Create New Part", "CreateParts", "PartList", new { parentPartId = 0 }, null)%>

Note that extra parameter at the end. For the other overloads, visit LinkExtensions.ActionLink Method. As you can see there is no string, string, string, object overload that you are trying to use.

Why is it string.join(list) instead of list.join(string)?

This was discussed in the String methods... finally thread in the Python-Dev achive, and was accepted by Guido. This thread began in Jun 1999, and str.join was included in Python 1.6 which was released in Sep 2000 (and supported Unicode). Python 2.0 (supported str methods including join) was released in Oct 2000.

  • There were four options proposed in this thread:
    • str.join(seq)
    • seq.join(str)
    • seq.reduce(str)
    • join as a built-in function
  • Guido wanted to support not only lists, tuples, but all sequences/iterables.
  • seq.reduce(str) is difficult for new-comers.
  • seq.join(str) introduces unexpected dependency from sequences to str/unicode.
  • join() as a built-in function would support only specific data types. So using a built in namespace is not good. If join() supports many datatypes, creating optimized implementation would be difficult, if implemented using the __add__ method then it's O(n²).
  • The separator string (sep) should not be omitted. Explicit is better than implicit.

There are no other reasons offered in this thread.

Here are some additional thoughts (my own, and my friend's):

  • Unicode support was coming, but it was not final. At that time UTF-8 was the most likely about to replace UCS2/4. To calculate total buffer length of UTF-8 strings it needs to know character coding rule.
  • At that time, Python had already decided on a common sequence interface rule where a user could create a sequence-like (iterable) class. But Python didn't support extending built-in types until 2.2. At that time it was difficult to provide basic iterable class (which is mentioned in another comment).

Guido's decision is recorded in a historical mail, deciding on str.join(seq):

Funny, but it does seem right! Barry, go for it...
--Guido van Rossum

How can I display the users profile pic using the facebook graph api?

to get different sizes, you can use the type parameter:

You can specify the picture size you want with the type argument, which should be one of square (50x50), small (50 pixels wide, variable height), and large (about 200 pixels wide, variable height): http://graph.facebook.com/squall3d/picture?type=large.

SQL Server - Convert varchar to another collation (code page) to fix character encoding

I think SELECT CAST( CAST([field] AS VARBINARY(120)) AS varchar(120)) for your update

Color text in terminal applications in UNIX

You probably want ANSI color codes. Most *nix terminals support them.

Angular 4 checkbox change value

changed = (evt) => {    
this.isChecked = evt.target.checked;
}

<input type="checkbox" [checked]="checkbox" (change)="changed($event)" id="no"/>

Where to place the 'assets' folder in Android Studio?

Two ways:

  1. Select app/main folder, Right click and select New => Folder => Asset Folder. It will create 'assets' directory in main.

  2. Select main folder, Right click and select New => Directory Enter name as 'assets' = > Ok.

enter image description here

Can I start the iPhone simulator without "Build and Run"?

To follow up on that the new command from @jimbojw to create a shortcut with the new Xcode (installing through preferences) is:

ln -s /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Applications/iPhone\ Simulator.app /Applications/iPhone\ Simulator.app

Which will create a shortcut in the applications folder for you.

"Could not run curl-config: [Errno 2] No such file or directory" when installing pycurl

On Debian I needed the following packages to fix this

sudo apt install libcurl4-openssl-dev libssl-dev

Get file size before uploading

Best solution working on all browsers ;)

function GetFileSize(fileid) {
    try {
        var fileSize = 0;
        // for IE
        if(checkIE()) { //we could use this $.browser.msie but since it's deprecated, we'll use this function
            // before making an object of ActiveXObject, 
            // please make sure ActiveX is enabled in your IE browser
            var objFSO = new ActiveXObject("Scripting.FileSystemObject");
            var filePath = $("#" + fileid)[0].value;
            var objFile = objFSO.getFile(filePath);
            var fileSize = objFile.size; //size in b
            fileSize = fileSize / 1048576; //size in mb 
        }
        // for FF, Safari, Opeara and Others
        else {
            fileSize = $("#" + fileid)[0].files[0].size //size in b
            fileSize = fileSize / 1048576; //size in mb 
        }
        alert("Uploaded File Size is" + fileSize + "MB");
    }
    catch (e) {
        alert("Error is :" + e);
    }
}

from http://www.dotnet-tricks.com/Tutorial/jquery/HHLN180712-Get-file-size-before-upload-using-jquery.html

UPDATE : We'll use this function to check if it's IE browser or not

function checkIE() {
    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE ");

    if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)){  
        // If Internet Explorer, return version number
        alert(parseInt(ua.substring(msie + 5, ua.indexOf(".", msie))));
    } else {
        // If another browser, return 0
        alert('otherbrowser');
    }

    return false;
}

NoSuchMethodError in javax.persistence.Table.indexes()[Ljavax/persistence/Index

I could solve the issue simply by replacing the JPA api jar file which is located jboss7/modules/javax/persistence/api/main with 'hibernate-jpa-2.1-api'. also with updating module.xml in the directory.

"Port 4200 is already in use" when running the ng serve command

ng serve --port <YOUR_GIVEN_PORT_NUMBER>

You should try above command to run on your given port.

Create array of all integers between two numbers, inclusive, in Javascript/jQuery

_x000D_
_x000D_
        function getRange(a,b)_x000D_
        {_x000D_
            ar = new Array();_x000D_
            var y = a - b > 0 ? a - b : b - a;_x000D_
            for (i=1;i<y;i++)_x000D_
            {_x000D_
                ar.push(i+b);_x000D_
            }_x000D_
            return ar;_x000D_
        }
_x000D_
_x000D_
_x000D_

CURL to access a page that requires a login from a different page

Also you might want to log in via browser and get the command with all headers including cookies:

Open the Network tab of Developer Tools, log in, navigate to the needed page, use "Copy as cURL".

screenshot

https connection using CURL from command line

I had the same problem - I was fetching a page from my own site, which was served over HTTPS, but curl was giving the same "SSL certificate problem" message. I worked around it by adding a -k flag to the call to allow insecure connections.

curl -k https://whatever.com/script.php

Edit: I discovered the root of the problem. I was using an SSL certificate (from StartSSL, but I don't think that matters much) and hadn't set up the intermediate certificate properly. If you're having the same problem as user1270392 above, it's probably a good idea to test your SSL cert and fix any issues with it before resorting to the curl -k fix.

Android SDK Manager Not Installing Components

For Linux/ubuntu User

  • Why it's happening?
    due to lock icon on some folder(not having read/write access) in
    "/yourpath/android-studio-SDK"

  • Sort and sweet solution
    -Open Terminal (Ctrl +alt +t)
    -copy pest sudo chown -R $USER: $HOME
    -wait for a while.....
    -now Try again to update your SDK

Happy Coding :)

How can I get table names from an MS Access Database?

SELECT 
Name 
FROM 
MSysObjects 
WHERE 
(Left([Name],1)<>"~") 
AND (Left([Name],4) <> "MSys") 
AND ([Type] In (1, 4, 6)) 
ORDER BY 
Name

Razor View Without Layout

I think it's better work with individual "views", Im trying to move from PHP to MVC4, its really hard but im on the right way...

Answering your question, if you'll work individual pages, just edit the _ViewStart.cshtml

@{
  Layout = null;
}

Another tip if you're getting some issues with CSS path...

Put "../" before of the url

This are the 2 problems that i get today, and I resolve in that way!

Regards;

Best way to do multi-row insert in Oracle?

This works in Oracle:

insert into pager (PAG_ID,PAG_PARENT,PAG_NAME,PAG_ACTIVE)
          select 8000,0,'Multi 8000',1 from dual
union all select 8001,0,'Multi 8001',1 from dual

The thing to remember here is to use the from dual statement.

How to properly use jsPDF library

first, you have to create a handler.

var specialElementHandlers = {
    '#editor': function(element, renderer){
        return true;
    }
};

then write this code in click event:

doc.fromHTML($('body').get(0), 15, 15, {
    'width': 170, 
    'elementHandlers': specialElementHandlers
        });

var pdfOutput = doc.output();
            console.log(">>>"+pdfOutput );

assuming you've already declared doc variable. And Then you have save this pdf file using File-Plugin.

complex if statement in python

It's often easier to think in the positive sense, and wrap it in a not:

elif not (var1 == 80 or var1 == 443 or (1024 <= var1 <= 65535)):
  # fail

You could of course also go all out and be a bit more object-oriented:

class PortValidator(object):
  @staticmethod
  def port_allowed(p):
    if p == 80: return True
    if p == 443: return True
    if 1024 <= p <= 65535: return True
    return False


# ...
elif not PortValidator.port_allowed(var1):
  # fail

Eclipse Java error: This selection cannot be launched and there are no recent launches

Check if the filename is same as the classname used by your program.

eg.:

class Dfs{ psvm(String[] args){}}

filename should be Dfs.java

How to completely uninstall python 2.7.13 on Ubuntu 16.04

Sometimes you need to first update the apt repo list.

sudo apt-get update
sudo apt purge python2.7-minimal

Git resolve conflict using --ours/--theirs for all files

git diff --name-only --diff-filter=U | xargs git checkout --theirs

Seems to do the job. Note that you have to be cd'ed to the root directory of the git repo to achieve this.

The localhost page isn’t working localhost is currently unable to handle this request. HTTP ERROR 500

It maybe solve your problem, check your files access level

$ sudo chmod -R 777 /"your files location"

ToggleClass animate jQuery?

You can simply use CSS transitions, see this fiddle

.on {
color:#fff;
transition:all 1s;
}

.off{
color:#000;
transition:all 1s;
}

CertPathValidatorException : Trust anchor for certificate path not found - Retrofit Android

After a long reserch and digging too deep i found the solution of certificate pinning in android and yes its different from iOS where we need a certificate itself but in android we just need a hash pin and that's it.

How to get hash pin for certificate?

Initially just use a wrong hash pin and your java class will throw an error with correct hash pins or pin chain, just copy and paste into your code thats it.

This solution fixed my problem : https://stackoverflow.com/a/45853669/3448003

How to add title to subplots in Matplotlib?

A shorthand answer assuming import matplotlib.pyplot as plt:

plt.gca().set_title('title')

as in:

plt.subplot(221)
plt.gca().set_title('title')
plt.subplot(222)
etc...

Then there is no need for superfluous variables.

How to drop columns by name in a data frame

First, you can use direct indexing (with booleans vectors) instead of re-accessing column names if you are working with the same data frame; it will be safer as pointed out by Ista, and quicker to write and to execute. So what you will only need is:

var.out.bool <- !names(data) %in% c("iden", "name", "x_serv", "m_serv")

and then, simply reassign data:

data <- data[,var.out.bool] # or...
data <- data[,var.out.bool, drop = FALSE] # You will need this option to avoid the conversion to an atomic vector if there is only one column left

Second, quicker to write, you can directly assign NULL to the columns you want to remove:

data[c("iden", "name", "x_serv", "m_serv")] <- list(NULL) # You need list() to respect the target structure.

Finally, you can use subset(), but it cannot really be used in the code (even the help file warns about it). Specifically, a problem to me is that if you want to directly use the drop feature of susbset() you need to write without quotes the expression corresponding to the column names:

subset( data, select = -c("iden", "name", "x_serv", "m_serv") ) # WILL NOT WORK
subset( data, select = -c(iden, name, x_serv, m_serv) ) # WILL

As a bonus, here is small benchmark of the different options, that clearly shows that subset is the slower, and that the first, reassigning method is the faster:

                                        re_assign(dtest, drop_vec)  46.719  52.5655  54.6460  59.0400  1347.331
                                      null_assign(dtest, drop_vec)  74.593  83.0585  86.2025  94.0035  1476.150
               subset(dtest, select = !names(dtest) %in% drop_vec) 106.280 115.4810 120.3435 131.4665 65133.780
 subset(dtest, select = names(dtest)[!names(dtest) %in% drop_vec]) 108.611 119.4830 124.0865 135.4270  1599.577
                                  subset(dtest, select = -c(x, y)) 102.026 111.2680 115.7035 126.2320  1484.174

Microbench graph

Code is below :

dtest <- data.frame(x=1:5, y=2:6, z = 3:7)
drop_vec <- c("x", "y")

null_assign <- function(df, names) {
  df[names] <- list(NULL)
  df
}

re_assign <- function(df, drop) {
  df <- df [, ! names(df) %in% drop, drop = FALSE]
  df
}

res <- microbenchmark(
  re_assign(dtest,drop_vec),
  null_assign(dtest,drop_vec),
  subset(dtest, select = ! names(dtest) %in% drop_vec),
  subset(dtest, select = names(dtest)[! names(dtest) %in% drop_vec]),
  subset(dtest, select = -c(x, y) ),
times=5000)

plt <- ggplot2::qplot(y=time, data=res[res$time < 1000000,], colour=expr)
plt <- plt + ggplot2::scale_y_log10() + 
  ggplot2::labs(colour = "expression") + 
  ggplot2::scale_color_discrete(labels = c("re_assign", "null_assign", "subset_bool", "subset_names", "subset_drop")) +
  ggplot2::theme_bw(base_size=16)
print(plt)

Laravel Migration Error: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes

Instead of setting a limit on length I would propose the following, which has worked for me.

Inside:

config/database.php

replace this line for mysql:

'engine' => 'InnoDB ROW_FORMAT=DYNAMIC',

with:

'engine' => null,

Converting two lists into a matrix

The standard numpy function for what you want is np.column_stack:

>>> np.column_stack(([1, 2, 3], [4, 5, 6]))
array([[1, 4],
       [2, 5],
       [3, 6]])

So with your portfolio and index arrays, doing

np.column_stack((portfolio, index))

would yield something like:

[[portfolio_value1, index_value1],
 [portfolio_value2, index_value2],
 [portfolio_value3, index_value3],
 ...]

Error - SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM

If you are using NHibernate, check that appropriate DateTime properties that are nullable are set to nullable in the mappings.

How to connect to MongoDB in Windows?

  1. Go to C:\Program Files\MongoDB\Server\3.4\bin using cmd and write mongod.
  2. Open another cmd by right click and run as admin point to your monogodb installed directory as mentioned above and then just like write this mongo.exe
  3. After that, write db.test.save({Field:'Hello mongodb'}) this command will insert a field having name Field and value is Hello mongodb.
  4. After, check the record db.test.find() and press enter you will find the record that you have recently entered.

Moment JS start and end of given month

Try the following code:

const moment=require('moment');
console.log("startDate=>",moment().startOf('month').format("YYYY-DD-MM"));
console.log("endDate=>",moment().endOf('month').format("YYYY-DD-MM"));

Excel formula is only showing the formula rather than the value within the cell in Office 2010

Make sure you include the = sign in addition to passing the arguments to the function. I.E.

=SUM(A1:A3) //this would give you the sum of cells A1, A2, and A3.

Chrome not rendering SVG referenced via <img> tag

I came here because I had a similar problem, the image was not being rendered. What I found out was that the content type header of my testing server wasn't correct. I fixed it by adding the following to my .htaccess file:

AddType image/svg+xml svg svgz
AddEncoding gzip svgz

How to write super-fast file-streaming code in C#?

You shouldn't re-open the source file each time you do a copy, better open it once and pass the resulting BinaryReader to the copy function. Also, it might help if you order your seeks, so you don't make big jumps inside the file.

If the lengths aren't too big, you can also try to group several copy calls by grouping offsets that are near to each other and reading the whole block you need for them, for example:

offset = 1234, length = 34
offset = 1300, length = 40
offset = 1350, length = 1000

can be grouped to one read:

offset = 1234, length = 1074

Then you only have to "seek" in your buffer and can write the three new files from there without having to read again.

How can I keep a container running on Kubernetes?

There are many different ways for accomplishing this, but one of the most elegant one is:

kubectl run -i --tty --image ubuntu:latest ubuntu-test --restart=Never --rm /bin/sh

Make element fixed on scroll

window.addEventListener("scroll", function(evt) {
    var pos_top = document.body.scrollTop;   
    if(pos_top == 0){
       $('#divID').css('position','fixed');
    }

    else if(pos_top > 0){
       $('#divId').css('position','static');
    }
});

Google Maps API V3 : How show the direction from a point A to point B (Blue line)?

  // First Initiate your map. Tie it to some ID in the HTML eg. 'MyMapID'
  var map = new google.maps.Map(
    document.getElementById('MyMapID'),
    {
      center: {
        lat: Some.latitude,
        lng: Some.longitude
      }
    }
  );
  // Create a new directionsService object.
  var directionsService = new google.maps.DirectionsService;
    directionsService.route({
      origin: origin.latitude +','+ origin.longitude,
      destination: destination.latitude +','+ destination.longitude,
      travelMode: 'DRIVING',
    }, function(response, status) {
      if (status === google.maps.DirectionsStatus.OK) {
        var directionsDisplay = new google.maps.DirectionsRenderer({
          suppressMarkers: true,
          map: map,
          directions: response,
          draggable: false,
          suppressPolylines: true, 
          // IF YOU SET `suppressPolylines` TO FALSE, THE LINE WILL BE
          // AUTOMATICALLY DRAWN FOR YOU.
        });

        // IF YOU WISH TO APPLY USER ACTIONS TO YOUR LINE YOU NEED TO CREATE A 
        // `polyLine` OBJECT BY LOOPING THROUGH THE RESPONSE ROUTES AND CREATING A 
        // LIST
        pathPoints = response.routes[0].overview_path.map(function (location) {
          return {lat: location.lat(), lng: location.lng()};
        });

        var assumedPath = new google.maps.Polyline({
         path: pathPoints, //APPLY LIST TO PATH
         geodesic: true,
         strokeColor: '#708090',
         strokeOpacity: 0.7,
         strokeWeight: 2.5
       });

       assumedPath.setMap(map); // Set the path object to the map

ERROR Android emulator gets killed

Check the free space of the emulator installation drive is more than 5 GB

Convert json data to a html table

Thanks all for your replies. I wrote one myself. Please note that this uses jQuery.

Code snippet:

_x000D_
_x000D_
var myList = [_x000D_
  { "name": "abc", "age": 50 },_x000D_
  { "age": "25", "hobby": "swimming" },_x000D_
  { "name": "xyz", "hobby": "programming" }_x000D_
];_x000D_
_x000D_
// Builds the HTML Table out of myList._x000D_
function buildHtmlTable(selector) {_x000D_
  var columns = addAllColumnHeaders(myList, selector);_x000D_
_x000D_
  for (var i = 0; i < myList.length; i++) {_x000D_
    var row$ = $('<tr/>');_x000D_
    for (var colIndex = 0; colIndex < columns.length; colIndex++) {_x000D_
      var cellValue = myList[i][columns[colIndex]];_x000D_
      if (cellValue == null) cellValue = "";_x000D_
      row$.append($('<td/>').html(cellValue));_x000D_
    }_x000D_
    $(selector).append(row$);_x000D_
  }_x000D_
}_x000D_
_x000D_
// Adds a header row to the table and returns the set of columns._x000D_
// Need to do union of keys from all records as some records may not contain_x000D_
// all records._x000D_
function addAllColumnHeaders(myList, selector) {_x000D_
  var columnSet = [];_x000D_
  var headerTr$ = $('<tr/>');_x000D_
_x000D_
  for (var i = 0; i < myList.length; i++) {_x000D_
    var rowHash = myList[i];_x000D_
    for (var key in rowHash) {_x000D_
      if ($.inArray(key, columnSet) == -1) {_x000D_
        columnSet.push(key);_x000D_
        headerTr$.append($('<th/>').html(key));_x000D_
      }_x000D_
    }_x000D_
  }_x000D_
  $(selector).append(headerTr$);_x000D_
_x000D_
  return columnSet;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<body onLoad="buildHtmlTable('#excelDataTable')">_x000D_
  <table id="excelDataTable" border="1">_x000D_
  </table>_x000D_
</body>
_x000D_
_x000D_
_x000D_

SQL Query to fetch data from the last 30 days?

SELECT COUNT(job_id) FROM jobs WHERE posted_date < NOW()-30;

Now() returns the current Date and Time.

Get the content of a sharepoint folder with Excel VBA

I spent some time on this very problem - I was trying to verify a file existed before opening it.

Eventually, I came up with a solution using XML and SOAP - use the EnumerateFolder method and pull in an XML response with the folder's contents.

I blogged about it here.

Convert list to dictionary using linq and not worrying about duplicates

LINQ solution:

// Use the first value in group
var _people = personList
    .GroupBy(p => p.FirstandLastName, StringComparer.OrdinalIgnoreCase)
    .ToDictionary(g => g.Key, g => g.First(), StringComparer.OrdinalIgnoreCase);

// Use the last value in group
var _people = personList
    .GroupBy(p => p.FirstandLastName, StringComparer.OrdinalIgnoreCase)
    .ToDictionary(g => g.Key, g => g.Last(), StringComparer.OrdinalIgnoreCase);

If you prefer a non-LINQ solution then you could do something like this:

// Use the first value in list
var _people = new Dictionary<string, Person>(StringComparer.OrdinalIgnoreCase);
foreach (var p in personList)
{
    if (!_people.ContainsKey(p.FirstandLastName))
        _people[p.FirstandLastName] = p;
}

// Use the last value in list
var _people = new Dictionary<string, Person>(StringComparer.OrdinalIgnoreCase);
foreach (var p in personList)
{
    _people[p.FirstandLastName] = p;
}

What's the difference between ConcurrentHashMap and Collections.synchronizedMap(Map)?

ConcurrentHashMap

  • You should use ConcurrentHashMap when you need very high concurrency in your project.
  • It is thread safe without synchronizing the whole map.
  • Reads can happen very fast while write is done with a lock.
  • There is no locking at the object level.
  • The locking is at a much finer granularity at a hashmap bucket level.
  • ConcurrentHashMap doesn’t throw a ConcurrentModificationException if one thread tries to modify it while another is iterating over it.
  • ConcurrentHashMap uses multitude of locks.

SynchronizedHashMap

  • Synchronization at Object level.
  • Every read/write operation needs to acquire lock.
  • Locking the entire collection is a performance overhead.
  • This essentially gives access to only one thread to the entire map & blocks all the other threads.
  • It may cause contention.
  • SynchronizedHashMap returns Iterator, which fails-fast on concurrent modification.

source

Frequency table for a single variable

You can use list comprehension on a dataframe to count frequencies of the columns as such

[my_series[c].value_counts() for c in list(my_series.select_dtypes(include=['O']).columns)]

Breakdown:

my_series.select_dtypes(include=['O']) 

Selects just the categorical data

list(my_series.select_dtypes(include=['O']).columns) 

Turns the columns from above into a list

[my_series[c].value_counts() for c in list(my_series.select_dtypes(include=['O']).columns)] 

Iterates through the list above and applies value_counts() to each of the columns