Programs & Examples On #Beta distribution

A two-parameter family of univariate distributions defined on the interval [0,1].

PNG transparency issue in IE8

Dan Tello fix worked well for me.

One additional issue I found with IE8 was that if the PNG was held in a DIV with smaller CSS width or height dimensions than the PNG then the black edge prob was re-triggered.

Correcting the width and height CSS or removing them altogether fixed.

How to grep (search) committed code in the Git history

git rev-list --all | xargs -n 5 git grep EXPRESSION

is a tweak to Jeet's solution, so it shows results while it searches and not just at the end (which can take a long time in a large repository).

Saving a Numpy array as an image

There's opencv for python (documentation here).

import cv2
import numpy as np

img = ... # Your image as a numpy array 

cv2.imwrite("filename.png", img)

useful if you need to do more processing other than saving.

How to decode a Base64 string?

I had issues with spaces showing in between my output and there was no answer online at all to fix this issue. I literally spend many hours trying to find a solution and found one from playing around with the code to the point that I almost did not even know what I typed in at the time that I got it to work. Here is my fix for the issue: [System.Text.Encoding]::UTF8.GetString(([System.Convert]::FromBase64String($base64string)|?{$_}))

Add MIME mapping in web.config for IIS Express

I'm not using IIS Express but developing against my Local Full IIS 7.

So if anyone else get's here trying to do that, I had to add the mime type for woff via IIS Manager

Mime Types >> Click Add link on right and then enter Extension: .woff MIME type: application/font-woff

Console.WriteLine does not show up in Output window

Old Thread, But in VS 2015 Console.WriteLine does not Write to Output Window If "Enable the Visual Studio Hosting Process" does not Checked or its Disabled in Project Properties -> Debug tab

How to create a SQL Server function to "join" multiple rows from a subquery into a single delimited field?

From what I can see FOR XML (as posted earlier) is the only way to do it if you want to also select other columns (which I'd guess most would) as the OP does. Using COALESCE(@var... does not allow inclusion of other columns.

Update: Thanks to programmingsolutions.net there is a way to remove the "trailing" comma to. By making it into a leading comma and using the STUFF function of MSSQL you can replace the first character (leading comma) with an empty string as below:

stuff(
    (select ',' + Column 
     from Table
         inner where inner.Id = outer.Id 
     for xml path('')
), 1,1,'') as Values

Using variable in SQL LIKE statement

This works for me on the Northwind sample DB, note that SearchLetter has 2 characters to it and SearchLetter also has to be declared for this to run:

declare @SearchLetter2 char(2)
declare @SearchLetter char(1)
Set @SearchLetter = 'A'
Set @SearchLetter2 = @SearchLetter+'%'
select * from Customers where ContactName like @SearchLetter2 and Region='WY'

Regex match entire words only

To match any whole word you would use the pattern (\w+)

Assuming you are using PCRE or something similar:

enter image description here

Above screenshot taken from this live example: http://regex101.com/r/cU5lC2

Matching any whole word on the commandline with (\w+)

I'll be using the phpsh interactive shell on Ubuntu 12.10 to demonstrate the PCRE regex engine through the method known as preg_match

Start phpsh, put some content into a variable, match on word.

el@apollo:~/foo$ phpsh

php> $content1 = 'badger'
php> $content2 = '1234'
php> $content3 = '$%^&'

php> echo preg_match('(\w+)', $content1);
1

php> echo preg_match('(\w+)', $content2);
1

php> echo preg_match('(\w+)', $content3);
0

The preg_match method used the PCRE engine within the PHP language to analyze variables: $content1, $content2 and $content3 with the (\w)+ pattern.

$content1 and $content2 contain at least one word, $content3 does not.

Match a number of literal words on the commandline with (dart|fart)

el@apollo:~/foo$ phpsh

php> $gun1 = 'dart gun';
php> $gun2 = 'fart gun';
php> $gun3 = 'farty gun';
php> $gun4 = 'unicorn gun';

php> echo preg_match('(dart|fart)', $gun1);
1

php> echo preg_match('(dart|fart)', $gun2);
1

php> echo preg_match('(dart|fart)', $gun3);
1

php> echo preg_match('(dart|fart)', $gun4);
0

variables gun1 and gun2 contain the string dart or fart. gun4 does not. However it may be a problem that looking for word fart matches farty. To fix this, enforce word boundaries in regex.

Match literal words on the commandline with word boundaries.

el@apollo:~/foo$ phpsh

php> $gun1 = 'dart gun';
php> $gun2 = 'fart gun';
php> $gun3 = 'farty gun';
php> $gun4 = 'unicorn gun';

php> echo preg_match('(\bdart\b|\bfart\b)', $gun1);
1

php> echo preg_match('(\bdart\b|\bfart\b)', $gun2);
1

php> echo preg_match('(\bdart\b|\bfart\b)', $gun3);
0

php> echo preg_match('(\bdart\b|\bfart\b)', $gun4);
0

So it's the same as the previous example except that the word fart with a \b word boundary does not exist in the content: farty.

change cursor to finger pointer

Here is something cool if you want to go the extra mile with this. in the url, you can use a link or save an image png and use the path. for example:

url('assets/imgs/theGoods.png');

below is the code:

.cursor{
  cursor:url(http://www.icon100.com/up/3772/128/425-hand-pointer.png), auto;
}

So this will only work under the size 128 X 128, any bigger and the image wont load. But you can practically use any image you want! This would be consider pure css3, and some html. all you got to do in html is

<div class='cursor'></div>

and only in that div, that cursor will show. So I usually add it to the body tag.

Eclipse error: "The import XXX cannot be resolved"

I faced the same issue and I solved it by removing a jar which was added twice in two different dependencies on my pom.xml. Removing one of the dependency solved the issue.

Using Exit button to close a winform program

Try this:

private void btnExitProgram_Click(object sender, EventArgs e) {
    this.Close();
}

Where does VBA Debug.Print log to?

Debug.Print outputs to the "Immediate" window.

Debug.Print outputs to the Immediate window

Also, you can simply type ? and then a statement directly into the immediate window (and then press Enter) and have the output appear right below, like this:

simply type ? and then a statement directly into the immediate window

This can be very handy to quickly output the property of an object...

? myWidget.name

...to set the property of an object...

myWidget.name = "thingy"

...or to even execute a function or line of code, while in debugging mode:

Sheet1.MyFunction()

Regular expression for only characters a-z, A-Z

This /[^a-z]/g solves the problem.

_x000D_
_x000D_
function pangram(str) {
    let regExp = /[^a-z]/g;
    let letters = str.toLowerCase().replace(regExp, '');
    document.getElementById('letters').innerHTML = letters;
}
pangram('GHV 2@# %hfr efg uor7 489(*&^% knt lhtkjj ngnm!@#$%^&*()_');
_x000D_
<h4 id="letters"></h4>
_x000D_
_x000D_
_x000D_

How do I tokenize a string in C++?

Many overly complicated suggestions here. Try this simple std::string solution:

using namespace std;

string someText = ...

string::size_type tokenOff = 0, sepOff = tokenOff;
while (sepOff != string::npos)
{
    sepOff = someText.find(' ', sepOff);
    string::size_type tokenLen = (sepOff == string::npos) ? sepOff : sepOff++ - tokenOff;
    string token = someText.substr(tokenOff, tokenLen);
    if (!token.empty())
        /* do something with token */;
    tokenOff = sepOff;
}

build-impl.xml:1031: The module has not been deployed

If you add jars in tomcat's lib folder you can see this error

How do I delete a Git branch locally and remotely?

If you want to delete a branch, first checkout to the branch other than the branch to be deleted.

git checkout other_than_branch_to_be_deleted

Deleting the local branch:

git branch -D branch_to_be_deleted

Deleting the remote branch:

git push origin --delete branch_to_be_deleted

Wipe data/Factory reset through ADB

After a lot of digging around I finally ended up downloading the source code of the recovery section of Android. Turns out you can actually send commands to the recovery.

 * The arguments which may be supplied in the recovery.command file:
 *   --send_intent=anystring - write the text out to recovery.intent
 *   --update_package=path - verify install an OTA package file
 *   --wipe_data - erase user data (and cache), then reboot
 *   --wipe_cache - wipe cache (but not user data), then reboot
 *   --set_encrypted_filesystem=on|off - enables / diasables encrypted fs

Those are the commands you can use according to the one I found but that might be different for modded files. So using adb you can do this:

adb shell
recovery --wipe_data

Using --wipe_data seemed to do what I was looking for which was handy although I have not fully tested this as of yet.

EDIT:

For anyone still using this topic, these commands may change based on which recovery you are using. If you are using Clockword recovery, these commands should still work. You can find other commands in /cache/recovery/command

For more information please see here: https://github.com/CyanogenMod/android_bootable_recovery/blob/cm-10.2/recovery.c

Java: set timeout on a certain block of code?

EDIT: Peter Lawrey is completely right: it's not as simple as interrupting a thread (my original suggestion), and Executors & Callables are very useful ...

Rather than interrupting threads, you could set a variable on the Callable once the timeout is reached. The callable should check this variable at appropriate points in task execution, to know when to stop.

Callables return Futures, with which you can specify a timeout when you try to 'get' the future's result. Something like this:

try {
   future.get(timeoutSeconds, TimeUnit.SECONDS)
} catch(InterruptedException e) {
   myCallable.setStopMeAtAppropriatePlace(true);
}

See Future.get, Executors, and Callable ...

https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Future.html#get-long-java.util.concurrent.TimeUnit-

https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Callable.html

https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executors.html#newFixedThreadPool%28int%29

How to open google chrome from terminal?

I'm not sure how extensively you've searched, but this seems to be similar to what you're searching for:

https://apple.stackexchange.com/questions/83630/create-a-terminal-command-to-open-file-with-chrome

(I just assumed you're using Mac since you used the word "terminal")

Getting a machine's external IP address with Python

You should use the UPnP protocol to query your router for this information. Most importantly, this does not rely on an external service, which all the other answers to this question seem to suggest.

There's a Python library called miniupnp which can do this, see e.g. miniupnpc/testupnpigd.py.

pip install miniupnpc

Based on their example you should be able to do something like this:

import miniupnpc

u = miniupnpc.UPnP()
u.discoverdelay = 200
u.discover()
u.selectigd()
print('external ip address: {}'.format(u.externalipaddress()))

angular.min.js.map not found, what is it exactly?

As eaon21 and monkey said, source map files basically turn minified code into its unminified version for debugging.

You can find the .map files here. Just add them into the same directory as the minified js files and it'll stop complaining. The reason they get fetched is the

/*
//@ sourceMappingURL=angular.min.js.map
*/

at the end of angular.min.js. If you don't want to add the .map files you can remove those lines and it'll stop the fetch attempt, but if you plan on debugging it's always good to keep the source maps linked.

How do I enable NuGet Package Restore in Visual Studio?

If you have any problems or are missing any packages you can simply right-click in your project and select "Manage NuGet Packages for Solution...". After clicking on this a screen will open where you see a menu bar saying "Restore": Restore

Click on it and the required packages will be installed automatically.
I believe this is what you're looking for, this solved my problems.

Doing a cleanup action just before Node.js exits

In the case where the process was spawned by another node process, like:

var child = spawn('gulp', ['watch'], {
    stdio: 'inherit',
});

And you try to kill it later, via:

child.kill();

This is how you handle the event [on the child]:

process.on('SIGTERM', function() {
    console.log('Goodbye!');
});

Submitting the value of a disabled input field

I know this is old but I just ran into this problem and none of the answers are suitable. nickf's solution works but it requires javascript. The best way is to disable the field and still pass the value is to use a hidden input field to pass the value to the form. For example,

<input type="text" value="22.2222" disabled="disabled" />
<input type="hidden" name="lat" value="22.2222" />

This way the value is passed but the user sees the greyed out field. The readonly attribute does not gray it out.

Pandas sum by groupby, but exclude certain columns

You can select the columns of a groupby:

In [11]: df.groupby(['Country', 'Item_Code'])[["Y1961", "Y1962", "Y1963"]].sum()
Out[11]:
                       Y1961  Y1962  Y1963
Country     Item_Code
Afghanistan 15            10     20     30
            25            10     20     30
Angola      15            30     40     50
            25            30     40     50

Note that the list passed must be a subset of the columns otherwise you'll see a KeyError.

Java 8 Lambda Stream forEach with multiple statements

List<String> items = new ArrayList<>();
items.add("A");
items.add("B");
items.add("C");
items.add("D");
items.add("E");

//lambda
//Output : A,B,C,D,E
items.forEach(item->System.out.println(item));

//Output : C
items.forEach(item->{
    System.out.println(item);
    System.out.println(item.toLowerCase());
  }
});

How do I compare if a string is not equal to?

Either != or ne will work, but you need to get the accessor syntax and nested quotes sorted out.

<c:if test="${content.contentType.name ne 'MCE'}">
    <%-- snip --%>
</c:if>

How to emulate GPS location in the Android Emulator?

In eclipse:

You may have to drag the DDMS window down. 'Location Controls' is located under 'Telephony Actions' and may be hidden by a normally sized console view ( the bar with console, LogCat etc may be covering it!)

~

Get public/external IP address?

With a few lines of code you can write your own Http Server for this.

HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://+/PublicIP/");
listener.Start();
while (true)
{
    HttpListenerContext context = listener.GetContext();
    string clientIP = context.Request.RemoteEndPoint.Address.ToString();
    using (Stream response = context.Response.OutputStream)
    using (StreamWriter writer = new StreamWriter(response))
        writer.Write(clientIP);

    context.Response.Close();
}

Then anytime you need to know your public ip, you can do this.

WebClient client = new WebClient();
string ip = client.DownloadString("http://serverIp/PublicIP");

iOS app with framework crashed on device, dyld: Library not loaded, Xcode 6 Beta

In my case app crash only on real device and it occurred for standard library's. I tryied a lot of steps meintioned before, after 1h i just delete app from real device and install it again.

AngularJS: How to run additional code after AngularJS has rendered a template?

Neither $scope.$evalAsync() or $timeout(fn, 0) worked reliably for me.

I had to combine the two. I made a directive and also put a priority higher than the default value for good measure. Here's a directive for it (Note I use ngInject to inject dependencies):

app.directive('postrenderAction', postrenderAction);

/* @ngInject */
function postrenderAction($timeout) {
    // ### Directive Interface
    // Defines base properties for the directive.
    var directive = {
        restrict: 'A',
        priority: 101,
        link: link
    };
    return directive;

    // ### Link Function
    // Provides functionality for the directive during the DOM building/data binding stage.
    function link(scope, element, attrs) {
        $timeout(function() {
            scope.$evalAsync(attrs.postrenderAction);
        }, 0);
    }
}

To call the directive, you would do this:

<div postrender-action="functionToRun()"></div>

If you want to call it after an ng-repeat is done running, I added an empty span in my ng-repeat and ng-if="$last":

<li ng-repeat="item in list">
    <!-- Do stuff with list -->
    ...

    <!-- Fire function after the last element is rendered -->
    <span ng-if="$last" postrender-action="$ctrl.postRender()"></span>
</li>

How to change the color of text in javafx TextField?

The CSS styles for text input controls such as TextField for JavaFX 8 are defined in the modena.css stylesheet as below. Create a custom CSS stylesheet and modify the colors as you wish. Use the CSS reference guide if you need help understanding the syntax and available attributes and values.

.text-input {
    -fx-text-fill: -fx-text-inner-color;
    -fx-highlight-fill: derive(-fx-control-inner-background,-20%);
    -fx-highlight-text-fill: -fx-text-inner-color;
    -fx-prompt-text-fill: derive(-fx-control-inner-background,-30%);
    -fx-background-color: linear-gradient(to bottom, derive(-fx-text-box-border, -10%), -fx-text-box-border),
        linear-gradient(from 0px 0px to 0px 5px, derive(-fx-control-inner-background, -9%), -fx-control-inner-background);
    -fx-background-insets: 0, 1;
    -fx-background-radius: 3, 2;
    -fx-cursor: text;
    -fx-padding: 0.333333em 0.583em 0.333333em 0.583em; /* 4 7 4 7 */
}
.text-input:focused {
    -fx-highlight-fill: -fx-accent;
    -fx-highlight-text-fill: white;
    -fx-background-color: 
        -fx-focus-color,
        -fx-control-inner-background,
        -fx-faint-focus-color,
        linear-gradient(from 0px 0px to 0px 5px, derive(-fx-control-inner-background, -9%), -fx-control-inner-background);
    -fx-background-insets: -0.2, 1, -1.4, 3;
    -fx-background-radius: 3, 2, 4, 0;
    -fx-prompt-text-fill: transparent;
}

Although using an external stylesheet is a preferred way to do the styling, you can style inline, using something like below:

textField.setStyle("-fx-text-inner-color: red;");

How to save and load cookies using Python + Selenium WebDriver

You can save the current cookies as a Python object using pickle. For example:

import pickle
import selenium.webdriver

driver = selenium.webdriver.Firefox()
driver.get("http://www.google.com")
pickle.dump( driver.get_cookies() , open("cookies.pkl","wb"))

And later to add them back:

import pickle
import selenium.webdriver

driver = selenium.webdriver.Firefox()
driver.get("http://www.google.com")
cookies = pickle.load(open("cookies.pkl", "rb"))
for cookie in cookies:
    driver.add_cookie(cookie)

When to choose mouseover() and hover() function?

As you can read at http://api.jquery.com/mouseenter/

The mouseenter JavaScript event is proprietary to Internet Explorer. Because of the event's general utility, jQuery simulates this event so that it can be used regardless of browser. This event is sent to an element when the mouse pointer enters the element. Any HTML element can receive this event.

CSS media queries: max-width OR max-height

Use a comma to specify two (or more) different rules:

@media screen and (max-width: 995px), 
       screen and (max-height: 700px) {
  ...
}

From https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries

Commas are used to combine multiple media queries into a single rule. Each query in a comma-separated list is treated separately from the others. Thus, if any of the queries in a list is true, the entire media statement returns true. In other words, lists behave like a logical or operator.

Toggle show/hide on click with jQuery

Make use of jquery toggle function which do the task for you

.toggle() - Display or hide the matched elements.

$('#myelement').click(function(){
      $('#another-element').toggle('slow');
  });

How to call a Python function from Node.js

The Boa is good for your needs, see the example which extends Python tensorflow keras.Sequential class in JavaScript.

const fs = require('fs');
const boa = require('@pipcook/boa');
const { tuple, enumerate } = boa.builtins();

const tf = boa.import('tensorflow');
const tfds = boa.import('tensorflow_datasets');

const { keras } = tf;
const { layers } = keras;

const [
  [ train_data, test_data ],
  info
] = tfds.load('imdb_reviews/subwords8k', boa.kwargs({
  split: tuple([ tfds.Split.TRAIN, tfds.Split.TEST ]),
  with_info: true,
  as_supervised: true
}));

const encoder = info.features['text'].encoder;
const padded_shapes = tuple([
  [ null ], tuple([])
]);
const train_batches = train_data.shuffle(1000)
  .padded_batch(10, boa.kwargs({ padded_shapes }));
const test_batches = test_data.shuffle(1000)
  .padded_batch(10, boa.kwargs({ padded_shapes }));

const embedding_dim = 16;
const model = keras.Sequential([
  layers.Embedding(encoder.vocab_size, embedding_dim),
  layers.GlobalAveragePooling1D(),
  layers.Dense(16, boa.kwargs({ activation: 'relu' })),
  layers.Dense(1, boa.kwargs({ activation: 'sigmoid' }))
]);

model.summary();
model.compile(boa.kwargs({
  optimizer: 'adam',
  loss: 'binary_crossentropy',
  metrics: [ 'accuracy' ]
}));

The complete example is at: https://github.com/alibaba/pipcook/blob/master/example/boa/tf2/word-embedding.js

I used Boa in another project Pipcook, which is to address the machine learning problems for JavaScript developers, we implemented ML/DL models upon the Python ecosystem(tensorflow,keras,pytorch) by the boa library.

"This SqlTransaction has completed; it is no longer usable."... configuration error?

In my case , I've some codes which needs to execute after committing the transaction at the same try catch block.One of the code threw an error then try block handed over the error to it's catch block which contains the transaction rollback. It will show the similar error. For example look at the code structure below :

SqlTransaction trans = null;

try{
 trans = Con.BeginTransaction();
// your codes

  trans.Commit();
//your codes having errors

}
catch(Exception ex)
{
     trans.Rollback(); //transaction roll back
    // error message
}

finally
{ 
    // connection close
}

Hope it will someone :)

Get screen width and height in Android

DisplayMetrics lDisplayMetrics = getResources().getDisplayMetrics();
int widthPixels = lDisplayMetrics.widthPixels;
int heightPixels = lDisplayMetrics.heightPixels;

Git copy changes from one branch to another

Copy content of BranchA into BranchB

git checkout BranchA
git pull origin BranchB
git push -u origin BranchA

Using LIKE in an Oracle IN clause

Yes, you can use this query (Instead of 'Specialist' and 'Developer', type any strings you want separated by comma and change employees table with your table)

SELECT * FROM employees em
    WHERE EXISTS (select 1 from table(sys.dbms_debug_vc2coll('Specialist', 'Developer')) mt where em.job like ('%' || mt.column_value || '%'));

Why my query is better than the accepted answer: You don't need a CREATE TABLE permission to run it. This can be executed with just SELECT permissions.

How can I implement a tree in Python?

class Node:
    """
    Class Node
    """
    def __init__(self, value):
        self.left = None
        self.data = value
        self.right = None

class Tree:
    """
    Class tree will provide a tree as well as utility functions.
    """

    def createNode(self, data):
        """
        Utility function to create a node.
        """
        return Node(data)

    def insert(self, node , data):
        """
        Insert function will insert a node into tree.
        Duplicate keys are not allowed.
        """
        #if tree is empty , return a root node
        if node is None:
            return self.createNode(data)
        # if data is smaller than parent , insert it into left side
        if data < node.data:
            node.left = self.insert(node.left, data)
        elif data > node.data:
            node.right = self.insert(node.right, data)

        return node


    def search(self, node, data):
        """
        Search function will search a node into tree.
        """
        # if root is None or root is the search data.
        if node is None or node.data == data:
            return node

        if node.data < data:
            return self.search(node.right, data)
        else:
            return self.search(node.left, data)



    def deleteNode(self,node,data):
        """
        Delete function will delete a node into tree.
        Not complete , may need some more scenarion that we can handle
        Now it is handling only leaf.
        """

        # Check if tree is empty.
        if node is None:
            return None

        # searching key into BST.
        if data < node.data:
            node.left = self.deleteNode(node.left, data)
        elif data > node.data:
            node.right = self.deleteNode(node.right, data)
        else: # reach to the node that need to delete from BST.
            if node.left is None and node.right is None:
                del node
            if node.left == None:
                temp = node.right
                del node
                return  temp
            elif node.right == None:
                temp = node.left
                del node
                return temp

        return node

    def traverseInorder(self, root):
        """
        traverse function will print all the node in the tree.
        """
        if root is not None:
            self.traverseInorder(root.left)
            print(root.data)
            self.traverseInorder(root.right)

    def traversePreorder(self, root):
        """
        traverse function will print all the node in the tree.
        """
        if root is not None:
            print(root.data)
            self.traversePreorder(root.left)
            self.traversePreorder(root.right)

    def traversePostorder(self, root):
        """
        traverse function will print all the node in the tree.
        """
        if root is not None:
            self.traversePostorder(root.left)
            self.traversePostorder(root.right)
            print(root.data)


def main():
    root = None
    tree = Tree()
    root = tree.insert(root, 10)
    print(root)
    tree.insert(root, 20)
    tree.insert(root, 30)
    tree.insert(root, 40)
    tree.insert(root, 70)
    tree.insert(root, 60)
    tree.insert(root, 80)

    print("Traverse Inorder")
    tree.traverseInorder(root)

    print("Traverse Preorder")
    tree.traversePreorder(root)

    print("Traverse Postorder")
    tree.traversePostorder(root)


if __name__ == "__main__":
    main()

How to multiply individual elements of a list with a number?

In NumPy it is quite simple

import numpy as np
P=2.45
S=[22, 33, 45.6, 21.6, 51.8]
SP = P*np.array(S)

I recommend taking a look at the NumPy tutorial for an explanation of the full capabilities of NumPy's arrays:

https://scipy.github.io/old-wiki/pages/Tentative_NumPy_Tutorial

Function overloading in Python: Missing

As unwind noted, keyword arguments with default values can go a long way.

I'll also state that in my opinion, it goes against the spirit of Python to worry a lot about what types are passed into methods. In Python, I think it's more accepted to use duck typing -- asking what an object can do, rather than what it is.

Thus, if your method may accept a string or a tuple, you might do something like this:

def print_names(names):
    """Takes a space-delimited string or an iterable"""
    try:
        for name in names.split(): # string case
            print name
    except AttributeError:
        for name in names:
            print name

Then you could do either of these:

print_names("Ryan Billy")
print_names(("Ryan", "Billy"))

Although an API like that sometimes indicates a design problem.

Enabling SSL with XAMPP

For XAMPP, do the following steps:

  1. G:\xampp\apache\conf\extra\httpd-ssl.conf"

  2. Search 'DocumentRoot' text.

  3. Change DocumentRoot DocumentRoot "G:/xampp/htdocs" to DocumentRoot "G:/xampp/htdocs/project name".

Is there a way to get a <button> element to link to a location without wrapping it in an <a href ... tag?

Inline Javascript:

<button onclick="window.location='http://www.example.com';">Visit Page Now</button>

Defining a function in Javascript:

<script>
    function visitPage(){
        window.location='http://www.example.com';
    }
</script>
<button onclick="visitPage();">Visit Page Now</button>

or in Jquery

<button id="some_id">Visit Page Now</button>

$('#some_id').click(function() {
  window.location='http://www.example.com';
});

Upload file to FTP using C#

The following works for me:

public virtual void Send(string fileName, byte[] file)
{
    ByteArrayToFile(fileName, file);

    var request = (FtpWebRequest) WebRequest.Create(new Uri(ServerUrl + fileName));

    request.Method = WebRequestMethods.Ftp.UploadFile;
    request.UsePassive = false;
    request.Credentials = new NetworkCredential(UserName, Password);
    request.ContentLength = file.Length;

    var requestStream = request.GetRequestStream();
    requestStream.Write(file, 0, file.Length);
    requestStream.Close();

    var response = (FtpWebResponse) request.GetResponse();

    if (response != null)
        response.Close();
}

You can't read send the file parameter in your code as it is only the filename.

Use the following:

byte[] bytes = File.ReadAllBytes(dir + file);

To get the file so you can pass it to the Send method.

Setting a checkbox as checked with Vue.js

In the v-model the value of the property might not be a strict boolean value and the checkbox might not 'recognise' the value as checked/unchecked. There is a neat feature in VueJS to make the conversion to true or false:

<input
  type="checkbox"
  v-model="toggle"
  true-value="yes"
  false-value="no"
>

Setting a log file name to include current date in Log4j

Using log4j.properties file, and including apache-log4j-extras 1.1 in my POM with log4j 1.2.16

log4j.appender.LOGFILE=org.apache.log4j.rolling.RollingFileAppender
log4j.appender.LOGFILE.RollingPolicy=org.apache.log4j.rolling.TimeBasedRollingPolicy
log4j.appender.LOGFILE.RollingPolicy.FileNamePattern=/logs/application_%d{yyyy-MM-dd}.log

How to initialize an array in one step using Ruby?

You can do

array = ['1', '2', '3']

As others have noted, you can also initialize an array with %w notation like so:

array = %w(1 2 3)

or

array = %w[1 2 3]

Please note that in both cases each element is a string, rather than an integer. So if you want an array whose elements are integers, you should not wrap each element with apostrophes:

array_of_integers = [1, 2, 3]

Also, you don't need to put comma in between the elements (which is necessary when creating an array without this %w notation). If you do this (which I often did by mistake), as in:

wrong_array = %w(1, 2, 3)

its elements will be three strings ---- "1,", "2,", "3". So if you do:

puts wrong_array

the output will be:

1,
2,
3
=>nil

which is not what we want here.

Hope this helps to clarify the point!

How to find the size of a table in SQL?

SQL Server provides a built-in stored procedure that you can run to easily show the size of a table, including the size of the indexes… which might surprise you.

Syntax:

 sp_spaceused 'Tablename'

see in :

http://www.howtogeek.com/howto/database/determine-size-of-a-table-in-sql-server/

iOS Simulator to test website on Mac

iPhoney is designed specifically for Mac users

you can read about it and download it here

How to connect wireless network adapter to VMWare workstation?

Use a Linux Live cd/usb and boot an that to be able to directly connect to your wifi hardware or use linux as the main OS with direct access to the wifi card and then use windows as a guest os, I know that this maybe not the ideal way but it will work.

How to add a boolean datatype column to an existing table in sql?

The answer given by P????? creates a nullable bool, not a bool, which may be fine for you. For example in C# it would create: bool? AdminApprovednot bool AdminApproved.

If you need to create a bool (defaulting to false):

    ALTER TABLE person
    ADD AdminApproved BIT
    DEFAULT 0 NOT NULL;

Update built-in vim on Mac OS X

I just installed vim by:

brew install vim

now the new vim is accessed by vim and the old vim (built-in vim) by vi

UNIX export command

Unix

The commands env, set, and printenv display all environment variables and their values. env and set are also used to set environment variables and are often incorporated directly into the shell. printenv can also be used to print a single variable by giving that variable name as the sole argument to the command.

In Unix, the following commands can also be used, but are often dependent on a certain shell.

export VARIABLE=value  # for Bourne, bash, and related shells
setenv VARIABLE value  # for csh and related shells

You can have a look at this at

Resizing Images in VB.NET

This is basically Muhammad Saqib's answer except two diffs:

1: Adds width and height function parameters.

2: This is a small nuance which can be ignored... Saying 'As Bitmap', instead of 'As Image'. 'As Image' does work just fine. I just prefer to match Return types. See Image VS Bitmap Class.

Public Shared Function ResizeImage(ByVal InputBitmap As Bitmap, width As Integer, height As Integer) As Bitmap
    Return New Bitmap(InputImage, New Size(width, height))
End Function

Ex.

Dim someimage As New Bitmap("C:\somefile")
someimage = ResizeImage(someimage,800,600)

How to add soap header in java

i was facing the same issue and solved it by removing the xmlns:wsu attribute.Try not adding it in the usernameToken.Hope this solves your issue too.

Import/Index a JSON file into Elasticsearch

You are using

$ curl -s -XPOST localhost:9200/_bulk --data-binary @requests

If 'requests' is a json file then you have to change this to

$ curl -s -XPOST localhost:9200/_bulk --data-binary @requests.json

Now before this, if your json file is not indexed, you have to insert an index line before each line inside the json file. You can do this with JQ. Refer below link: http://kevinmarsh.com/2014/10/23/using-jq-to-import-json-into-elasticsearch.html

Go to elasticsearch tutorials (example the shakespeare tutorial) and download the json file sample used and have a look at it. In front of each json object (each individual line) there is an index line. This is what you are looking for after using the jq command. This format is mandatory to use the bulk API, plain json files wont work.

Unable to verify leaf signature

Another approach to solving this securely is to use the following module.

node_extra_ca_certs_mozilla_bundle

This module can work without any code modification by generating a PEM file that includes all root and intermediate certificates trusted by Mozilla. You can use the following environment variable (Works with Nodejs v7.3+),

NODE_EXTRA_CA_CERTS

To generate the PEM file to use with the above environment variable. You can install the module using:

npm install --save node_extra_ca_certs_mozilla_bundle

and then launch your node script with an environment variable.

NODE_EXTRA_CA_CERTS=node_modules/node_extra_ca_certs_mozilla_bundle/ca_bundle/ca_intermediate_root_bundle.pem node your_script.js

Other ways to use the generated PEM file are available at:

https://github.com/arvind-agarwal/node_extra_ca_certs_mozilla_bundle

NOTE: I am the author of the above module.

Simplest way to display current month and year like "Aug 2016" in PHP?

Here is a simple and more update format of getting the data:

   $now = new \DateTime('now');
   $month = $now->format('m');
   $year = $now->format('Y');

what do these symbolic strings mean: %02d %01d?

The answer from Alexander refers to complete docs...

Your simple example from the question simply prints out these values with 2 digits - appending leading 0 if necessary.

How to find tags with only certain attributes - BeautifulSoup

The easiest way to do this is with the new CSS style select method:

soup = BeautifulSoup(html)
results = soup.select('td[valign="top"]')

<button> background image

Replace button #rock With #rock

No need for additional selector scope. You're using an id which is as specific as you can be.

JsBin example: http://jsbin.com/idobar/1/edit

How do I change the background color with JavaScript?

Modify the JavaScript property document.body.style.background.

For example:

function changeBackground(color) {
   document.body.style.background = color;
}

window.addEventListener("load",function() { changeBackground('red') });

Note: this does depend a bit on how your page is put together, for example if you're using a DIV container with a different background colour you will need to modify the background colour of that instead of the document body.

How to store JSON object in SQLite database

https://github.com/app-z/Json-to-SQLite

At first generate Plain Old Java Objects from JSON http://www.jsonschema2pojo.org/

Main method

void createDb(String dbName, String tableName, List dataList, Field[] fields){ ...

Fields name will create dynamically

How to change a dataframe column from String type to Double type in PySpark?

There is no need for an UDF here. Column already provides cast method with DataType instance :

from pyspark.sql.types import DoubleType

changedTypedf = joindf.withColumn("label", joindf["show"].cast(DoubleType()))

or short string:

changedTypedf = joindf.withColumn("label", joindf["show"].cast("double"))

where canonical string names (other variations can be supported as well) correspond to simpleString value. So for atomic types:

from pyspark.sql import types 

for t in ['BinaryType', 'BooleanType', 'ByteType', 'DateType', 
          'DecimalType', 'DoubleType', 'FloatType', 'IntegerType', 
           'LongType', 'ShortType', 'StringType', 'TimestampType']:
    print(f"{t}: {getattr(types, t)().simpleString()}")
BinaryType: binary
BooleanType: boolean
ByteType: tinyint
DateType: date
DecimalType: decimal(10,0)
DoubleType: double
FloatType: float
IntegerType: int
LongType: bigint
ShortType: smallint
StringType: string
TimestampType: timestamp

and for example complex types

types.ArrayType(types.IntegerType()).simpleString()   
'array<int>'
types.MapType(types.StringType(), types.IntegerType()).simpleString()
'map<string,int>'

How to get HttpClient returning status code and response body?

Don't provide the handler to execute.

Get the HttpResponse object, use the handler to get the body and get the status code from it directly

try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
    final HttpGet httpGet = new HttpGet(GET_URL);

    try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
        StatusLine statusLine = response.getStatusLine();
        System.out.println(statusLine.getStatusCode() + " " + statusLine.getReasonPhrase());
        String responseBody = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
        System.out.println("Response body: " + responseBody);
    }
}

For quick single calls, the fluent API is useful:

Response response = Request.Get(uri)
        .connectTimeout(MILLIS_ONE_SECOND)
        .socketTimeout(MILLIS_ONE_SECOND)
        .execute();
HttpResponse httpResponse = response.returnResponse();
StatusLine statusLine = httpResponse.getStatusLine();

For older versions of java or httpcomponents, the code might look different.

How to format column to number format in Excel sheet?

This will format column A as text, B as General, C as a number.

Sub formatColumns()
 Columns(1).NumberFormat = "@"
 Columns(2).NumberFormat = "General"
 Columns(3).NumberFormat = "0"
End Sub

Asyncio.gather vs asyncio.wait

A very important distinction, which is easy to miss, is the default bheavior of these two functions, when it comes to exceptions.


I'll use this example to simulate a coroutine that will raise exceptions, sometimes -

import asyncio
import random


async def a_flaky_tsk(i):
    await asyncio.sleep(i)  # bit of fuzz to simulate a real-world example

    if i % 2 == 0:
        print(i, "ok")
    else:
        print(i, "crashed!")
        raise ValueError

coros = [a_flaky_tsk(i) for i in range(10)]

await asyncio.gather(*coros) outputs -

0 ok
1 crashed!
Traceback (most recent call last):
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 20, in <module>
    asyncio.run(main())
  File "/Users/dev/.pyenv/versions/3.8.2/lib/python3.8/asyncio/runners.py", line 43, in run
    return loop.run_until_complete(main)
  File "/Users/dev/.pyenv/versions/3.8.2/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
    return future.result()
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 17, in main
    await asyncio.gather(*coros)
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
    raise ValueError
ValueError

As you can see, the coros after index 1 never got to execute.


But await asyncio.wait(coros) continues to execute tasks, even if some of them fail -

0 ok
1 crashed!
2 ok
3 crashed!
4 ok
5 crashed!
6 ok
7 crashed!
8 ok
9 crashed!
Task exception was never retrieved
future: <Task finished name='Task-10' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
    raise ValueError
ValueError
Task exception was never retrieved
future: <Task finished name='Task-8' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
    raise ValueError
ValueError
Task exception was never retrieved
future: <Task finished name='Task-2' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
    raise ValueError
ValueError
Task exception was never retrieved
future: <Task finished name='Task-9' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
    raise ValueError
ValueError
Task exception was never retrieved
future: <Task finished name='Task-3' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
    raise ValueError
ValueError

Ofcourse, this behavior can be changed for both by using -

asyncio.gather(..., return_exceptions=True)

or,

asyncio.wait([...], return_when=asyncio.FIRST_EXCEPTION)


But it doesn't end here!

Notice: Task exception was never retrieved in the logs above.

asyncio.wait() won't re-raise exceptions from the child tasks until you await them individually. (The stacktrace in the logs are just messages, they cannot be caught!)

done, pending = await asyncio.wait(coros)
for tsk in done:
    try:
        await tsk
    except Exception as e:
        print("I caught:", repr(e))

Output -

0 ok
1 crashed!
2 ok
3 crashed!
4 ok
5 crashed!
6 ok
7 crashed!
8 ok
9 crashed!
I caught: ValueError()
I caught: ValueError()
I caught: ValueError()
I caught: ValueError()
I caught: ValueError()

On the other hand, to catch exceptions with asyncio.gather(), you must -

results = await asyncio.gather(*coros, return_exceptions=True)
for result_or_exc in results:
    if isinstance(result_or_exc, Exception):
        print("I caught:", repr(result_or_exc))

(Same output as before)

Write to .txt file?

Well, you need to first get a good book on C and understand the language.

FILE *fp;
fp = fopen("c:\\test.txt", "wb");
if(fp == null)
   return;
char x[10]="ABCDEFGHIJ";
fwrite(x, sizeof(x[0]), sizeof(x)/sizeof(x[0]), fp);
fclose(fp);

Calling a javascript function in another js file

Please note this only works if the

<script>

tags are in the body and NOT in the head.

So

<head>
...
<script type="text/javascript" src="first.js"></script>
<script type="text/javascript" src="second.js"></script>
</head>

=> unknown function fn1()

Fails and

<body>
...
<script type="text/javascript" src="first.js"></script>
<script type="text/javascript" src="second.js"></script>
</body>

works.

Limit text length to n lines using CSS

Currently you can't, but in future you will be able to use text-overflow:ellipis-lastline. Currently it's available with vendor prefix in Opera 10.60+: example

How to set Bullet colors in UL/LI html lists via CSS without using any images or span tags

A variation of Lea Verou solution with perfect indentation in multi-line entries could be something like this:

ul{
    list-style: none;
    position: relative;
    padding: 0;
    margin: 0;
}

li{
    padding-left: 1.5em; 
}

li:before {
    position: absolute;
    content: "•";
    color: red;
    left: 0;
}

How to add a new line of text to an existing file in Java?

In case you are looking for a cut and paste method that creates and writes to a file, here's one I wrote that just takes a String input. Remove 'true' from PrintWriter if you want to overwrite the file each time.

private static final String newLine = System.getProperty("line.separator");

private synchronized void writeToFile(String msg)  {
    String fileName = "c:\\TEMP\\runOutput.txt";
    PrintWriter printWriter = null;
    File file = new File(fileName);
    try {
        if (!file.exists()) file.createNewFile();
        printWriter = new PrintWriter(new FileOutputStream(fileName, true));
        printWriter.write(newLine + msg);
    } catch (IOException ioex) {
        ioex.printStackTrace();
    } finally {
        if (printWriter != null) {
            printWriter.flush();
            printWriter.close();
        }
    }
}

iOS9 getting error “an SSL error has occurred and a secure connection to the server cannot be made”

If you are just targeting specific domains you can try and add this in your application's Info.plist:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>example.com</key>
        <dict>
            <key>NSExceptionRequiresForwardSecrecy</key>
            <false/>
            <key>NSIncludesSubdomains</key>
            <true/>
        </dict>
    </dict>
</dict>

How to convert LINQ query result to List?

You need to somehow convert each tbcourse object to an instance of course. For instance course could have a constructor that takes a tbcourse. You could then write the query like this:

var qry = from c in obj.tbCourses
          select new course(c);

List<course> lst = qry.ToList();

Keep CMD open after BAT file executes

javac -d C:\xxx\lib\ -classpath C:\xxx\lib\ *.java

cmd cd C:\xxx\yourbat.bat

the second command make your cmd window not be closed. The important thing is you still able to input new command

How do I run a terminal inside of Vim?

The main new feature of Vim 8.1 is support for running a terminal in a Vim window.

:term will open the terminal in another window inside Vim.

C# generic list <T> how to get the type of T?

Given an object which I suspect to be some kind of IList<>, how can I determine of what it's an IList<>?

Here's the gutsy solution. It assumes you have the actual object to test (rather than a Type).

public static Type ListOfWhat(Object list)
{
    return ListOfWhat2((dynamic)list);
}

private static Type ListOfWhat2<T>(IList<T> list)
{
    return typeof(T);
}

Example usage:

object value = new ObservableCollection<DateTime>();
ListOfWhat(value).Dump();

Prints

typeof(DateTime)

When & why to use delegates?

A delegate is a simple class that is used to point to methods with a specific signature, becoming essentially a type-safe function pointer. A delegate's purpose is to facilitate a call back to another method (or methods), after one has been completed, in a structured way.

While it could be possible to create an extensive set of code to perform this functionality, you don’t need too. You can use a delegate.

Creating a delegate is easy to do. Identify the class as a delegate with the "delegate" keyword. Then specify the signature of the type.

How to install pip for Python 3 on Mac OS X?

To use Python EasyInstall (which is what I think you're wanting to use), is super easy!

sudo easy_install pip

so then with pip to install Pyserial you would do:

pip install pyserial

count number of lines in terminal output

Piping to 'wc' could be better IF the last line ends with a newline (I know that in this case, it will)
However, if the last line does not end with a newline 'wc -l' gives back a false result.

For example:

$ echo "asd" | wc -l

Will return 1 and

$ echo -n "asd" | wc -l

Will return 0


So what I often use is grep <anything> -c

$ echo "asd" | grep "^.*$" -c
1

$ echo -n "asd" | grep "^.*$" -c
1

This is closer to reality than what wc -l will return.

jQuery check if it is clicked or not

Using jQuery, I would suggest a shorter solution.

var elementClicked;
$("element").click(function(){
   elementClicked = true;
});
if( elementClicked != true ) {
    alert("element not clicked");
}else{
    alert("element clicked");
}

("element" here is to be replaced with the actual name tag)

How do I convert a string to a number in PHP?

Here is the function that achieves what you are looking for. First we check if the value can be understood as a number, if so we turn it into an int and a float. If the int and float are the same (e.g., 5 == 5.0) then we return the int value. If the int and float are not the same (e.g., 5 != 5.3) then we assume you need the precision of the float and return that value. If the value isn't numeric we throw a warning and return null.

function toNumber($val) {
    if (is_numeric($val)) {
        $int = (int)$val;
        $float = (float)$val;

        $val = ($int == $float) ? $int : $float;
        return $val;
    } else {
        trigger_error("Cannot cast $val to a number", E_USER_WARNING);
        return null;
    }
}

Compute a confidence interval from sample data

Start with looking up the z-value for your desired confidence interval from a look-up table. The confidence interval is then mean +/- z*sigma, where sigma is the estimated standard deviation of your sample mean, given by sigma = s / sqrt(n), where s is the standard deviation computed from your sample data and n is your sample size.

How do I find the parent directory in C#?

I've found variants of System.IO.Path.Combine(myPath, "..") to be the easiest and most reliable. Even more so if what northben says is true, that GetParent requires an extra call if there is a trailing slash. That, to me, is unreliable.

Path.Combine makes sure you never go wrong with slashes.

.. behaves exactly like it does everywhere else in Windows. You can add any number of \.. to a path in cmd or explorer and it will behave exactly as I describe below.

Some basic .. behavior:

  1. If there is a file name, .. will chop that off:

Path.Combine(@"D:\Grandparent\Parent\Child.txt", "..") => D:\Grandparent\Parent\

  1. If the path is a directory, .. will move up a level:

Path.Combine(@"D:\Grandparent\Parent\", "..") => D:\Grandparent\

  1. ..\.. follows the same rules, twice in a row:

Path.Combine(@"D:\Grandparent\Parent\Child.txt", @"..\..") => D:\Grandparent\ Path.Combine(@"D:\Grandparent\Parent\", @"..\..") => D:\

  1. And this has the exact same effect:

Path.Combine(@"D:\Grandparent\Parent\Child.txt", "..", "..") => D:\Grandparent\ Path.Combine(@"D:\Grandparent\Parent\", "..", "..") => D:\

Get image dimensions

<?php 
    list($width, $height) = getimagesize("http://site.com/image.png"); 
    $arr = array('h' => $height, 'w' => $width );
?>

Get height of div with no height set in css

Can do this in jQuery. Try all options .height(), .innerHeight() or .outerHeight().

$('document').ready(function() {
    $('#right_div').css({'height': $('#left_div').innerHeight()});
});

Example Screenshot

enter image description here

Hope this helps. Thanks!!

android: how to align image in the horizontal center of an imageview?

For me android:gravity="center" did the trick in the parent layout element.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/fullImageView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:contentDescription="@string/fullImageView"
        android:layout_gravity="center" />

</LinearLayout>

How to install 2 Anacondas (Python 2 and 3) on Mac OS

There is no need to install Anaconda again. Conda, the package manager for Anaconda, fully supports separated environments. The easiest way to create an environment for Python 2.7 is to do

conda create -n python2 python=2.7 anaconda

This will create an environment named python2 that contains the Python 2.7 version of Anaconda. You can activate this environment with

source activate python2

This will put that environment (typically ~/anaconda/envs/python2) in front in your PATH, so that when you type python at the terminal it will load the Python from that environment.

If you don't want all of Anaconda, you can replace anaconda in the command above with whatever packages you want. You can use conda to install packages in that environment later, either by using the -n python2 flag to conda, or by activating the environment.

Most common C# bitwise operations on enums

@Drew

Note that except in the simplest of cases, the Enum.HasFlag carries a heavy performance penalty in comparison to writing out the code manually. Consider the following code:

[Flags]
public enum TestFlags
{
    One = 1,
    Two = 2,
    Three = 4,
    Four = 8,
    Five = 16,
    Six = 32,
    Seven = 64,
    Eight = 128,
    Nine = 256,
    Ten = 512
}


class Program
{
    static void Main(string[] args)
    {
        TestFlags f = TestFlags.Five; /* or any other enum */
        bool result = false;

        Stopwatch s = Stopwatch.StartNew();
        for (int i = 0; i < 10000000; i++)
        {
            result |= f.HasFlag(TestFlags.Three);
        }
        s.Stop();
        Console.WriteLine(s.ElapsedMilliseconds); // *4793 ms*

        s.Restart();
        for (int i = 0; i < 10000000; i++)
        {
            result |= (f & TestFlags.Three) != 0;
        }
        s.Stop();
        Console.WriteLine(s.ElapsedMilliseconds); // *27 ms*        

        Console.ReadLine();
    }
}

Over 10 million iterations, the HasFlags extension method takes a whopping 4793 ms, compared to the 27 ms for the standard bitwise implementation.

Is it safe to clean docker/overlay2/

Friends, to keep everything clean you can use de commands:

  • docker system prune -a && docker volume prune.

What does template <unsigned int N> mean?

Yes, it is a non-type parameter. You can have several kinds of template parameters

  • Type Parameters.
    • Types
    • Templates (only classes and alias templates, no functions or variable templates)
  • Non-type Parameters
    • Pointers
    • References
    • Integral constant expressions

What you have there is of the last kind. It's a compile time constant (so-called constant expression) and is of type integer or enumeration. After looking it up in the standard, i had to move class templates up into the types section - even though templates are not types. But they are called type-parameters for the purpose of describing those kinds nonetheless. You can have pointers (and also member pointers) and references to objects/functions that have external linkage (those that can be linked to from other object files and whose address is unique in the entire program). Examples:

Template type parameter:

template<typename T>
struct Container {
    T t;
};

// pass type "long" as argument.
Container<long> test;

Template integer parameter:

template<unsigned int S>
struct Vector {
    unsigned char bytes[S];
};

// pass 3 as argument.
Vector<3> test;

Template pointer parameter (passing a pointer to a function)

template<void (*F)()>
struct FunctionWrapper {
    static void call_it() { F(); }
};

// pass address of function do_it as argument.
void do_it() { }
FunctionWrapper<&do_it> test;

Template reference parameter (passing an integer)

template<int &A>
struct SillyExample {
    static void do_it() { A = 10; }
};

// pass flag as argument
int flag;
SillyExample<flag> test;

Template template parameter.

template<template<typename T> class AllocatePolicy>
struct Pool {
    void allocate(size_t n) {
        int *p = AllocatePolicy<int>::allocate(n);
    }
};

// pass the template "allocator" as argument. 
template<typename T>
struct allocator { static T * allocate(size_t n) { return 0; } };
Pool<allocator> test;

A template without any parameters is not possible. But a template without any explicit argument is possible - it has default arguments:

template<unsigned int SIZE = 3>
struct Vector {
    unsigned char buffer[SIZE];
};

Vector<> test;

Syntactically, template<> is reserved to mark an explicit template specialization, instead of a template without parameters:

template<>
struct Vector<3> {
    // alternative definition for SIZE == 3
};

NSDictionary to NSArray?

NSArray * values = [dictionary allValues];

How can I get the status code from an http error in Axios?

You can put the error into an object and log the object, like this:

axios.get('foo.com')
    .then((response) => {})
    .catch((error) => {
        console.log({error}) // this will log an empty object with an error property
    });

Hope this help someone out there.

Select unique or distinct values from a list in UNIX shell script

With zsh you can do this:

% cat infile 
tar
more than one word
gz
java
gz
java
tar
class
class
zsh-5.0.0[t]% print -l "${(fu)$(<infile)}"
tar
more than one word
gz
java
class

Or you can use AWK:

% awk '!_[$0]++' infile    
tar
more than one word
gz
java
class

How do I view Android application specific cache?

Cached files are indeed stored in /data/data/my_app_package/cache

Make sure to store the files using the following method:

String cacheDir = context.getCacheDir();
File imageFile = new File(cacheDir, "image1.jpg");
FileOutputStream out = new FileOutputStream(imageFile);
out.write(imagebuffer, 0, imagebufferlength);

where imagebuffer[] contains image data in byte format and imagebufferlength is the length of the content to be written to the FileOutputStream.

Now, you may look at DDMS File Explorer or do an "adb shell" and cd to /data/data/my_app_package/cache and do an "ls". You will find the image files you have stored through code in this directory.

Moreover, from Android documentation:

If you'd like to cache some data, rather than store it persistently, you should use getCacheDir() to open a File that represents the internal directory where your application should save temporary cache files.

When the device is low on internal storage space, Android may delete these cache files to recover space. However, you should not rely on the system to clean up these files for you. You should always maintain the cache files yourself and stay within a reasonable limit of space consumed, such as 1MB. When the user uninstalls your application, these files are removed.

Pythonic way of checking if a condition holds for any element of a list

any():

if any(t < 0 for t in x):
    # do something

Also, if you're going to use "True in ...", make it a generator expression so it doesn't take O(n) memory:

if True in (t < 0 for t in x):

What's the difference between compiled and interpreted language?

Interpreted language is executed at the run time according to the instructions like in shell scripting and compiled language is one which is compiled (changed into Assembly language, which CPU can understand ) and then executed like in c++.

Clearing a string buffer/builder after loop

StringBuffer sb = new SringBuffer();
// do something wiht it
sb = new StringBuffer();

i think this code is faster.

Showing percentages above bars on Excel column graph

In Excel for Mac 2016 at least,if you place the labels in any spot on the graph and are looking to move them anywhere else (in this case above the bars), select:

Chart Design->Add Chart Element->Data Labels -> More Data Label Options

then you can grab each individual label and pull it where you would like it.

How create Date Object with values in java

Simplest ways:

Date date = Date.valueOf("2000-1-1");
LocalDate localdate = LocalDate.of(2000,1,1);
LocalDateTime localDateTime = LocalDateTime.of(2000,1,1,0,0);

How can I check if some text exist or not in the page using Selenium?

With XPath, it's not that hard. Simply search for all elements containing the given text:

List<WebElement> list = driver.findElements(By.xpath("//*[contains(text(),'" + text + "')]"));
Assert.assertTrue("Text not found!", list.size() > 0);

The official documentation is not very supportive with tasks like this, but it is the basic tool nonetheless.

The JavaDocs are greater, but it takes some time to get through everything useful and unuseful.

To learn XPath, just follow the internet. The spec is also a surprisingly good read.


EDIT:

Or, if you don't want your Implicit Wait to make the above code wait for the text to appear, you can do something in the way of this:

String bodyText = driver.findElement(By.tagName("body")).getText();
Assert.assertTrue("Text not found!", bodyText.contains(text));

Kill detached screen session

add this to your ~/.bashrc:

alias cleanscreen="screen -ls | tail -n +2 | head -n -2 | awk '{print $1}'| xargs -I{} screen -S {} -X quit"

Then use cleanscreen to clean all screen session.

What does "The APR based Apache Tomcat Native library was not found" mean?

On Mac OS X:

$ brew install tomcat-native
==> tomcat-native
In order for tomcat's APR lifecycle listener to find this library, you'll
need to add it to java.library.path. This can be done by adding this line
to $CATALINA_HOME/bin/setenv.sh

  CATALINA_OPTS="$CATALINA_OPTS -Djava.library.path=/usr/local/opt/tomcat-native/lib"

If $CATALINA_HOME/bin/setenv.sh doesn't exist, create it and make it executable.

Then add it to the eclipse's tomcat arguments (double-click Server > Open Launch Configuration > Arguments tab > VM arguments)

-Djava.library.path=/usr/local/opt/tomcat-native/lib

How to keep the console window open in Visual C++?

just add system("pause") at the end of the code before return 0 like this

#include <stdlib.h>

int main()
{
    //some code goes here
    system("pause")
    return 0;
}

How do I determine the size of my array in C?

You can use the & operator. Here is the source code:

#include<stdio.h>
#include<stdlib.h>
int main(){

    int a[10];

    int *p; 

    printf("%p\n", (void *)a); 
    printf("%p\n", (void *)(&a+1));
    printf("---- diff----\n");
    printf("%zu\n", sizeof(a[0]));
    printf("The size of array a is %zu\n", ((char *)(&a+1)-(char *)a)/(sizeof(a[0])));


    return 0;
};

Here is the sample output

1549216672
1549216712
---- diff----
4
The size of array a is 10

Call a React component method from outside

class AppProvider extends Component {
  constructor() {
    super();

    window.alertMessage = this.alertMessage.bind(this);
  }

  alertMessage() {
    console.log('Hello World');
 }
}

You can call this method from the window by using window.alertMessage().

How to fix: "No suitable driver found for jdbc:mysql://localhost/dbname" error when using pools?

I'm running Tomcat 7 in Eclipse with Java 7 and using the jdbc driver for MSSQL sqljdbc4.jar.

When running the code outside of tomcat, from a standalone java app, this worked just fine:

        connection = DriverManager.getConnection(conString, user, pw);

However, when I tried to run the same code inside of Tomcat 7, I found that I could only get it work by first registering the driver, changing the above to this:

        DriverManager.registerDriver(new com.microsoft.sqlserver.jdbc.SQLServerDriver());
        connection = DriverManager.getConnection(conString, user, pw);

What is a mixin, and why are they useful?

I think of them as a disciplined way of using multiple inheritance - because ultimately a mixin is just another python class that (might) follow the conventions about classes that are called mixins.

My understanding of the conventions that govern something you would call a Mixin are that a Mixin:

  • adds methods but not instance variables (class constants are OK)
  • only inherits from object (in Python)

That way it limits the potential complexity of multiple inheritance, and makes it reasonably easy to track the flow of your program by limiting where you have to look (compared to full multiple inheritance). They are similar to ruby modules.

If I want to add instance variables (with more flexibility than allowed for by single inheritance) then I tend to go for composition.

Having said that, I have seen classes called XYZMixin that do have instance variables.

How to convert C# nullable int to int

You can't do it if v1 is null, but you can check with an operator.

v2 = v1 ?? 0;

Joining two lists together

I just wanted to test how Union works with the default comparer on overlapping collections of reference type objects.

My object is:

class MyInt
{
    public int val;

    public override string ToString()
    {
        return val.ToString();
    }
}

My test code is:

MyInt[] myInts1 = new MyInt[10];
MyInt[] myInts2 = new MyInt[10];
int overlapFrom = 4;
Console.WriteLine("overlapFrom: {0}", overlapFrom);

Action<IEnumerable<MyInt>, string> printMyInts = (myInts, myIntsName) => Console.WriteLine("{2} ({0}): {1}", myInts.Count(), string.Join(" ", myInts), myIntsName);

for (int i = 0; i < myInts1.Length; i++)
    myInts1[i] = new MyInt { val = i };
printMyInts(myInts1, nameof(myInts1));

int j = 0;
for (; j + overlapFrom < myInts1.Length; j++)
    myInts2[j] = myInts1[j + overlapFrom];
for (; j < myInts2.Length; j++)
    myInts2[j] = new MyInt { val = j + overlapFrom };
printMyInts(myInts2, nameof(myInts2));

IEnumerable<MyInt> myUnion = myInts1.Union(myInts2);
printMyInts(myUnion, nameof(myUnion));

for (int i = 0; i < myInts2.Length; i++)
    myInts2[i].val += 10;
printMyInts(myInts2, nameof(myInts2));
printMyInts(myUnion, nameof(myUnion));

for (int i = 0; i < myInts1.Length; i++)
    myInts1[i].val = i;
printMyInts(myInts1, nameof(myInts1));
printMyInts(myUnion, nameof(myUnion));

The output is:

overlapFrom: 4
myInts1 (10): 0 1 2 3 4 5 6 7 8 9
myInts2 (10): 4 5 6 7 8 9 10 11 12 13
myUnion (14): 0 1 2 3 4 5 6 7 8 9 10 11 12 13
myInts2 (10): 14 15 16 17 18 19 20 21 22 23
myUnion (14): 0 1 2 3 14 15 16 17 18 19 20 21 22 23
myInts1 (10): 0 1 2 3 4 5 6 7 8 9
myUnion (14): 0 1 2 3 4 5 6 7 8 9 20 21 22 23

So, everything works fine.

Set type for function parameters?

Edit: Seven years later, this answer still gets occasional upvotes. It's fine if you are looking for runtime checking, but I would now recommend compile-time type checking using Typescript, or possibly Flow. See https://stackoverflow.com/a/31420719/610585 above for more.

Original answer:

It's not built into the language, but you can do it yourself quite easily. Vibhu's answer is what I would consider the typical way of type checking in Javascript. If you want something more generalized, try something like this: (just an example to get you started)

typedFunction = function(paramsList, f){
    //optionally, ensure that typedFunction is being called properly  -- here's a start:
    if (!(paramsList instanceof Array)) throw Error('invalid argument: paramsList must be an array');

    //the type-checked function
    return function(){
        for(var i=0,p,arg;p=paramsList[i],arg=arguments[i],i<paramsList.length; i++){
            if (typeof p === 'string'){
                if (typeof arg !== p) throw new Error('expected type ' + p + ', got ' + typeof arg);
            }
            else { //function
                if (!(arg instanceof p)) throw new Error('expected type ' + String(p).replace(/\s*\{.*/, '') + ', got ' + typeof arg);
            }
        }
        //type checking passed; call the function itself
        return f.apply(this, arguments);
    }
}

//usage:
var ds = typedFunction([Date, 'string'], function(d, s){
    console.log(d.toDateString(), s.substr(0));
});

ds('notadate', 'test');
//Error: expected type function Date(), got string
ds();
//Error: expected type function Date(), got undefined
ds(new Date(), 42);
//Error: expected type string, got number
ds(new Date(), 'success');
//Fri Jun 14 2013 success

Is there a way to word-wrap long words in a div?

Reading the original comment, rutherford is looking for a cross-browser way to wrap unbroken text (inferred by his use of word-wrap for IE, designed to break unbroken strings).

/* Source: http://snipplr.com/view/10979/css-cross-browser-word-wrap */
.wordwrap { 
   white-space: pre-wrap;      /* CSS3 */   
   white-space: -moz-pre-wrap; /* Firefox */    
   white-space: -pre-wrap;     /* Opera <7 */   
   white-space: -o-pre-wrap;   /* Opera 7 */    
   word-wrap: break-word;      /* IE */
}

I've used this class for a bit now, and works like a charm. (note: I've only tested in FireFox and IE)

Sql select rows containing part of string

you can use CHARINDEX in t-sql.

select * from table where CHARINDEX(url, 'http://url.com/url?url...') > 0

How to run Visual Studio post-build events for debug build only

In Visual Studio 2012 you have to use (I think in Visual Studio 2010, too)

if $(Configuration) == Debug xcopy

$(ConfigurationName) was listed as a macro, but it wasn't assigned.

Enter image description here

Compare: Macros for Build Commands and Properties

How to get Time from DateTime format in SQL?

To get the time from datetime, we can use

SELECT CONVERT(VARCHAR(20), GETDATE(), 114)

if else condition in blade file (laravel 5.3)

I think you are putting one too many curly brackets. Try this

 @if($user->status=='waiting')
            <td><a href="#" class="viewPopLink btn btn-default1" role="button" data-id="{!! $user->travel_id !!}" data-toggle="modal" data-target="#myModal">Approve/Reject</a> </td>
            @else
            <td>{!! $user->status !!}</td>
        @endif

Aligning a button to the center

You should use something like this:

<div style="text-align:center">  
    <input type="submit" />  
</div>  

Or you could use something like this. By giving the element a width and specifying auto for the left and right margins the element will center itself in its parent.

<input type="submit" style="width: 300px; margin: 0 auto;" />

How can I remove all text after a character in bash?

An example might have been useful, but if I understood you correctly, this would work:

echo "Hello: world" | cut -f1 -d":"

This will convert Hello: world into Hello.

Difference between socket and websocket?

WebSocket is just another application level protocol over TCP protocol, just like HTTP.

Some snippets < Spring in Action 4> quoted below, hope it can help you understand WebSocket better.

In its simplest form, a WebSocket is just a communication channel between two applications (not necessarily a browser is involved)...WebSocket communication can be used between any kinds of applications, but the most common use of WebSocket is to facilitate communication between a server application and a browser-based application.

Basic HTTP and Bearer Token Authentication

curl --anyauth

Tells curl to figure out authentication method by itself, and use the most secure one the remote site claims to support. This is done by first doing a request and checking the response- headers, thus possibly inducing an extra network round-trip. This is used instead of setting a specific authentication method, which you can do with --basic, --digest, --ntlm, and --negotiate.

`require': no such file to load -- mkmf (LoadError)

I also needed build-essential installed:

sudo apt-get install build-essential

How to resolve "Waiting for Debugger" message?

The Dialog Waiting for Debugger is shown if you are building a debug application or somewhere in your source code, you called Debug.waitingForDebugger();

Inside Android Studio 2.0 and above, there is an option of Attach Debugger to Android Process. It is the last menu item in the Run menu.

Screen shot of Run menu options in Android Studio

Python, TypeError: unhashable type: 'list'

The problem is that you can't use a list as the key in a dict, since dict keys need to be immutable. Use a tuple instead.

This is a list:

[x, y]

This is a tuple:

(x, y)

Note that in most cases, the ( and ) are optional, since , is what actually defines a tuple (as long as it's not surrounded by [] or {}, or used as a function argument).

You might find the section on tuples in the Python tutorial useful:

Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain an heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.

And in the section on dictionaries:

Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().


In case you're wondering what the error message means, it's complaining because there's no built-in hash function for lists (by design), and dictionaries are implemented as hash tables.

Enum Naming Convention - Plural

Coming in a bit late...

There's an important difference between your question and the one you mention (which I asked ;-):

You put the enum definition out of the class, which allows you to have the same name for the enum and the property:

public enum EntityType { 
  Type1, Type2 
} 

public class SomeClass { 
  public EntityType EntityType {get; set;} // This is legal

}

In this case, I'd follow the MS guidelins and use a singular name for the enum (plural for flags). It's probaby the easiest solution.

My problem (in the other question) is when the enum is defined in the scope of the class, preventing the use of a property named exactly after the enum.

How to list all AWS S3 objects in a bucket using Java

It might be a workaround but this solved my problem:

ObjectListing listing = s3.listObjects( bucketName, prefix );
List<S3ObjectSummary> summaries = listing.getObjectSummaries();

while (listing.isTruncated()) {
   listing = s3.listNextBatchOfObjects (listing);
   summaries.addAll (listing.getObjectSummaries());
}

JS - window.history - Delete a state

You may have moved on by now, but... as far as I know there's no way to delete a history entry (or state).

One option I've been looking into is to handle the history yourself in JavaScript and use the window.history object as a carrier of sorts.

Basically, when the page first loads you create your custom history object (we'll go with an array here, but use whatever makes sense for your situation), then do your initial pushState. I would pass your custom history object as the state object, as it may come in handy if you also need to handle users navigating away from your app and coming back later.

var myHistory = [];

function pageLoad() {
    window.history.pushState(myHistory, "<name>", "<url>");

    //Load page data.
}

Now when you navigate, you add to your own history object (or don't - the history is now in your hands!) and use replaceState to keep the browser out of the loop.

function nav_to_details() {
    myHistory.push("page_im_on_now");
    window.history.replaceState(myHistory, "<name>", "<url>");

    //Load page data.
}

When the user navigates backwards, they'll be hitting your "base" state (your state object will be null) and you can handle the navigation according to your custom history object. Afterward, you do another pushState.

function on_popState() {
    // Note that some browsers fire popState on initial load,
    // so you should check your state object and handle things accordingly.
    // (I did not do that in these examples!)

    if (myHistory.length > 0) {
        var pg = myHistory.pop();
        window.history.pushState(myHistory, "<name>", "<url>");

        //Load page data for "pg".
    } else {
        //No "history" - let them exit or keep them in the app.
    }
}

The user will never be able to navigate forward using their browser buttons because they are always on the newest page.

From the browser's perspective, every time they go "back", they've immediately pushed forward again.

From the user's perspective, they're able to navigate backwards through the pages but not forward (basically simulating the smartphone "page stack" model).

From the developer's perspective, you now have a high level of control over how the user navigates through your application, while still allowing them to use the familiar navigation buttons on their browser. You can add/remove items from anywhere in the history chain as you please. If you use objects in your history array, you can track extra information about the pages as well (like field contents and whatnot).

If you need to handle user-initiated navigation (like the user changing the URL in a hash-based navigation scheme), then you might use a slightly different approach like...

var myHistory = [];

function pageLoad() {
    // When the user first hits your page...
    // Check the state to see what's going on.

    if (window.history.state === null) {
        // If the state is null, this is a NEW navigation,
        //    the user has navigated to your page directly (not using back/forward).

        // First we establish a "back" page to catch backward navigation.
        window.history.replaceState(
            { isBackPage: true },
            "<back>",
            "<back>"
        );

        // Then push an "app" page on top of that - this is where the user will sit.
        // (As browsers vary, it might be safer to put this in a short setTimeout).
        window.history.pushState(
            { isBackPage: false },
            "<name>",
            "<url>"
        );

        // We also need to start our history tracking.
        myHistory.push("<whatever>");

        return;
    }

    // If the state is NOT null, then the user is returning to our app via history navigation.

    // (Load up the page based on the last entry of myHistory here)

    if (window.history.state.isBackPage) {
        // If the user came into our app via the back page,
        //     you can either push them forward one more step or just use pushState as above.

        window.history.go(1);
        // or window.history.pushState({ isBackPage: false }, "<name>", "<url>");
    }

    setTimeout(function() {
        // Add our popstate event listener - doing it here should remove
        //     the issue of dealing with the browser firing it on initial page load.
        window.addEventListener("popstate", on_popstate);
    }, 100);
}

function on_popstate(e) {
    if (e.state === null) {
        // If there's no state at all, then the user must have navigated to a new hash.

        // <Look at what they've done, maybe by reading the hash from the URL>
        // <Change/load the new page and push it onto the myHistory stack>
        // <Alternatively, ignore their navigation attempt by NOT loading anything new or adding to myHistory>

        // Undo what they've done (as far as navigation) by kicking them backwards to the "app" page
        window.history.go(-1);

        // Optionally, you can throw another replaceState in here, e.g. if you want to change the visible URL.
        // This would also prevent them from using the "forward" button to return to the new hash.
        window.history.replaceState(
            { isBackPage: false },
            "<new name>",
            "<new url>"
        );
    } else {
        if (e.state.isBackPage) {
            // If there is state and it's the 'back' page...

            if (myHistory.length > 0) {
                // Pull/load the page from our custom history...
                var pg = myHistory.pop();
                // <load/render/whatever>

                // And push them to our "app" page again
                window.history.pushState(
                    { isBackPage: false },
                    "<name>",
                    "<url>"
                );
            } else {
                // No more history - let them exit or keep them in the app.
            }
        }

        // Implied 'else' here - if there is state and it's NOT the 'back' page
        //     then we can ignore it since we're already on the page we want.
        //     (This is the case when we push the user back with window.history.go(-1) above)
    }
}

How do I rename all folders and files to lowercase on Linux?

This works on CentOS/Red Hat Linux or other distributions without the rename Perl script:

for i in $( ls | grep [A-Z] ); do mv -i "$i" "`echo $i | tr 'A-Z' 'a-z'`"; done

Source: Rename all file names from uppercase to lowercase characters

(In some distributions the default rename command comes from util-linux, and that is a different, incompatible tool.)

How do I update a formula with Homebrew?

I prefer to upgrade all homebrew formulae and homebrew cask formulae.

I added a Bourne shell function to my environment for this one (I load a .bashrc)

function updatebrew() {
set -x;
brew update;
brew cleanup;
brew cask upgrade --greedy
)
}
  • set -x for transparency: So that the terminal outputs whatever Homebrew is doing in the background.
  • brew update to update homebrew formulas
  • brew cleanup to remove any change left over after installations
  • brew cask upgrade --greedy will install all casks; both those with versioning information and those without

How to perform grep operation on all files in a directory?

In Linux, I normally use this command to recursively grep for a particular text within a dir

grep -rni "string" *

where,

r = recursive i.e, search subdirectories within the current directory
n = to print the line numbers to stdout
i = case insensitive search

Algorithm to find Largest prime factor of a number

I'm aware this is not a fast solution. Posting as hopefully easier to understand slow solution.

 public static long largestPrimeFactor(long n) {

        // largest composite factor must be smaller than sqrt
        long sqrt = (long)Math.ceil(Math.sqrt((double)n));

        long largest = -1;

        for(long i = 2; i <= sqrt; i++) {
            if(n % i == 0) {
                long test = largestPrimeFactor(n/i);
                if(test > largest) {
                    largest = test;
                }
            }
        }

        if(largest != -1) {
            return largest;
        }

        // number is prime
        return n;
    } 

CKEditor, Image Upload (filebrowserUploadUrl)

This simple demo may help you in getting what you want. Here is the html/php code from where you want to upload the image:

<html>
<head>
 <script src="http://cdn.ckeditor.com/4.6.2/standard-all/ckeditor.js"></script>
  </head>
<body>
<form  action="index.php" method="POST"  style="width:500xp;">

<textarea rows="5" name="content" id="content"></textarea>

<br>
<input type="submit" name="submit" value="Post">

</form>
<script>
 CKEDITOR.replace( 'content', {
  height: 300,
  filebrowserUploadUrl: "upload.php"
 });
</script>
</body>
</html>

and here is the code for upload.php file.

 <?php
if(isset($_FILES['upload']['name']))
{
 $file = $_FILES['upload']['tmp_name'];
 $file_name = $_FILES['upload']['name'];
 $file_name_array = explode(".", $file_name);
 $extension = end($file_name_array);
 //we want to save the image with timestamp and randomnumber
 $new_image_name = time() . rand(). '.' . $extension;
 chmod('upload', 0777);
 $allowed_extension = array("jpg", "gif", "png");
 if(in_array($extension, $allowed_extension))
 {
  move_uploaded_file($file, 'upload/' . $new_image_name);
  $function_number = $_GET['CKEditorFuncNum'];
  $url = 'upload/' . $new_image_name;
  $message = '';
  echo "<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction($function_number, '$url', '$message');</script>";
 }
}
?>

Note: Don't forget to create a folder "upload" in the same folder and keep all the three files in the same directory. Later you may change their directories once you understand how it works. Also not forget to press send it to the server as shown in picture below.

screenshot

If a DOM Element is removed, are its listeners also removed from memory?

Regarding jQuery, the following common methods will also remove other constructs such as data and event handlers:

remove()

In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed.

empty()

To avoid memory leaks, jQuery removes other constructs such as data and event handlers from the child elements before removing the elements themselves.

html()

Additionally, jQuery removes other constructs such as data and event handlers from child elements before replacing those elements with the new content.

How to customize the background/border colors of a grouped table view cell?

First of all thanks for this code. I have made some drawing changes in this function to remove corner problem of drawing.

-(void)drawRect:(CGRect)rect 
{
    // Drawing code

    CGContextRef c = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(c, [fillColor CGColor]);
    CGContextSetStrokeColorWithColor(c, [borderColor CGColor]);
    CGContextSetLineWidth(c, 2);

    if (position == CustomCellBackgroundViewPositionTop) {

        CGFloat minx = CGRectGetMinX(rect) , midx = CGRectGetMidX(rect), maxx = CGRectGetMaxX(rect) ;
        CGFloat miny = CGRectGetMinY(rect) , maxy = CGRectGetMaxY(rect) ;
        minx = minx + 1;
        miny = miny + 1;

        maxx = maxx - 1;
        maxy = maxy ;

        CGContextMoveToPoint(c, minx, maxy);
        CGContextAddArcToPoint(c, minx, miny, midx, miny, ROUND_SIZE);
        CGContextAddArcToPoint(c, maxx, miny, maxx, maxy, ROUND_SIZE);
        CGContextAddLineToPoint(c, maxx, maxy);

        // Close the path
        CGContextClosePath(c);
        // Fill & stroke the path
        CGContextDrawPath(c, kCGPathFillStroke);        
        return;
    } else if (position == CustomCellBackgroundViewPositionBottom) {

        CGFloat minx = CGRectGetMinX(rect) , midx = CGRectGetMidX(rect), maxx = CGRectGetMaxX(rect) ;
        CGFloat miny = CGRectGetMinY(rect) , maxy = CGRectGetMaxY(rect) ;
        minx = minx + 1;
        miny = miny ;

        maxx = maxx - 1;
        maxy = maxy - 1;

        CGContextMoveToPoint(c, minx, miny);
        CGContextAddArcToPoint(c, minx, maxy, midx, maxy, ROUND_SIZE);
        CGContextAddArcToPoint(c, maxx, maxy, maxx, miny, ROUND_SIZE);
        CGContextAddLineToPoint(c, maxx, miny);
        // Close the path
        CGContextClosePath(c);
        // Fill & stroke the path
        CGContextDrawPath(c, kCGPathFillStroke);    
        return;
    } else if (position == CustomCellBackgroundViewPositionMiddle) {
        CGFloat minx = CGRectGetMinX(rect) , maxx = CGRectGetMaxX(rect) ;
        CGFloat miny = CGRectGetMinY(rect) , maxy = CGRectGetMaxY(rect) ;
        minx = minx + 1;
        miny = miny ;

        maxx = maxx - 1;
        maxy = maxy ;

        CGContextMoveToPoint(c, minx, miny);
        CGContextAddLineToPoint(c, maxx, miny);
        CGContextAddLineToPoint(c, maxx, maxy);
        CGContextAddLineToPoint(c, minx, maxy);

        CGContextClosePath(c);
        // Fill & stroke the path
        CGContextDrawPath(c, kCGPathFillStroke);    
        return;
    }
}

How can I access each element of a pair in a pair list?

If you want to use names, try a namedtuple:

from collections import namedtuple

Pair = namedtuple("Pair", ["first", "second"])

pairs = [Pair("a", 1), Pair("b", 2), Pair("c", 3)]

for pair in pairs:
    print("First = {}, second = {}".format(pair.first, pair.second))

Returning JSON object from an ASP.NET page

If you get code behind, use some like this

        MyCustomObject myObject = new MyCustomObject();
        myObject.name='try';
        //OBJECT -> JSON
        var javaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        string myObjectJson = javaScriptSerializer.Serialize(myObject);
        //return JSON   
        Response.Clear();     
        Response.ContentType = "application/json; charset=utf-8";
        Response.Write(myObjectJson );
        Response.End();

So you return a json object serialized with all attributes of MyCustomObject.

Rename multiple files by replacing a particular pattern in the filenames using a shell script

for file in *.jpg ; do mv $file ${file//IMG/myVacation} ; done

Again assuming that all your image files have the string "IMG" and you want to replace "IMG" with "myVacation".

With bash you can directly convert the string with parameter expansion.

Example: if the file is IMG_327.jpg, the mv command will be executed as if you do mv IMG_327.jpg myVacation_327.jpg. And this will be done for each file found in the directory matching *.jpg.

IMG_001.jpg -> myVacation_001.jpg
IMG_002.jpg -> myVacation_002.jpg
IMG_1023.jpg -> myVacation_1023.jpg
etcetera...

How to store .pdf files into MySQL as BLOBs using PHP?

In regards to Gordon M's answer above, the 1st and 2nd parameter in mysqli_real_escape_string () call should be swapped for the newer php versions, according to: http://php.net/manual/en/mysqli.real-escape-string.php

Check for internet connection with Swift

If you are using Alamofire, you can do something like this:

let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.timeoutIntervalForRequest = 15 //Set timeouts in sec
configuration.timeoutIntervalForResource = 15

let alamoFireManager = Alamofire.Manager(configuration:configuration)
alamoFireManager?.request(.GET, "https://yourURL.com", parameters: headers, encoding: .URL)
                     .validate()
                              .responseJSON { response in

                                if let error = response.result.error {
                                   switch error.code{
                                    case -1001:
                                        print("Slow connection")
                                        return
                                    case -1009:
                                        print("No Connection!")
                                        return
                                    default: break
                                    }
                                }

Is it better to use path() or url() in urls.py for django 2.0?

Regular expressions don't seem to work with the path() function with the following arguments: path(r'^$', views.index, name="index").

It should be like this: path('', views.index, name="index").

The 1st argument must be blank to enter a regular expression.

SQL Server 2008 Row Insert and Update timestamps

try

CREATE TABLE [dbo].[Names]
(
    [Name] [nvarchar](64) NOT NULL,
    [CreateTS] [smalldatetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
    [UpdateTS] [smalldatetime] NOT NULL

)

PS I think a smalldatetime is good enough. You may decide differently.

Can you not do this at the "moment of impact" ?

In Sql Server, this is common:

Update dbo.MyTable 
Set 

ColA = @SomeValue , 
UpdateDS = CURRENT_TIMESTAMP
Where...........

Sql Server has a "timestamp" datatype.

But it may not be what you think.

Here is a reference:

http://msdn.microsoft.com/en-us/library/ms182776(v=sql.90).aspx

Here is a little RowVersion (synonym for timestamp) example:

CREATE TABLE [dbo].[Names]
(
    [Name] [nvarchar](64) NOT NULL,
    RowVers rowversion ,
    [CreateTS] [datetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
    [UpdateTS] [datetime] NOT NULL

)


INSERT INTO dbo.Names (Name,UpdateTS)
select 'John' , CURRENT_TIMESTAMP
UNION ALL select 'Mary' , CURRENT_TIMESTAMP
UNION ALL select 'Paul' , CURRENT_TIMESTAMP

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Update dbo.Names Set Name = Name

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Maybe a complete working example:

DROP TABLE [dbo].[Names]
GO


CREATE TABLE [dbo].[Names]
(
    [Name] [nvarchar](64) NOT NULL,
    RowVers rowversion ,
    [CreateTS] [datetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
    [UpdateTS] [datetime] NOT NULL

)

GO

CREATE TRIGGER dbo.trgKeepUpdateDateInSync_ByeByeBye ON dbo.Names
AFTER INSERT, UPDATE
AS

BEGIN

Update dbo.Names Set UpdateTS = CURRENT_TIMESTAMP from dbo.Names myAlias , inserted triggerInsertedTable where 
triggerInsertedTable.Name = myAlias.Name

END


GO






INSERT INTO dbo.Names (Name,UpdateTS)
select 'John' , CURRENT_TIMESTAMP
UNION ALL select 'Mary' , CURRENT_TIMESTAMP
UNION ALL select 'Paul' , CURRENT_TIMESTAMP

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Update dbo.Names Set Name = Name , UpdateTS = '03/03/2003' /* notice that even though I set it to 2003, the trigger takes over */

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Matching on the "Name" value is probably not wise.

Try this more mainstream example with a SurrogateKey

DROP TABLE [dbo].[Names]
GO


CREATE TABLE [dbo].[Names]
(
    SurrogateKey int not null Primary Key Identity (1001,1),
    [Name] [nvarchar](64) NOT NULL,
    RowVers rowversion ,
    [CreateTS] [datetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
    [UpdateTS] [datetime] NOT NULL

)

GO

CREATE TRIGGER dbo.trgKeepUpdateDateInSync_ByeByeBye ON dbo.Names
AFTER UPDATE
AS

BEGIN

   UPDATE dbo.Names
    SET UpdateTS = CURRENT_TIMESTAMP
    From  dbo.Names myAlias
    WHERE exists ( select null from inserted triggerInsertedTable where myAlias.SurrogateKey = triggerInsertedTable.SurrogateKey)

END


GO






INSERT INTO dbo.Names (Name,UpdateTS)
select 'John' , CURRENT_TIMESTAMP
UNION ALL select 'Mary' , CURRENT_TIMESTAMP
UNION ALL select 'Paul' , CURRENT_TIMESTAMP

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Update dbo.Names Set Name = Name , UpdateTS = '03/03/2003' /* notice that even though I set it to 2003, the trigger takes over */

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

How do I get elapsed time in milliseconds in Ruby?

To get time in milliseconds, it's better to add .round(3), so it will be more accurate in some cases:

puts Time.now.to_f # => 1453402722.577573

(Time.now.to_f.round(3)*1000).to_i  # => 1453402722578

How do I format XML in Notepad++?

UniversalIndentGUI did the job for me, once configured properly as described above.

TextFX would not install and run correctly on an old PC I have running Windows XP. There are instructions above for manual installation of various DLL files, but I'd rather avoid any manual installation.

UniversalIndentGUI formatted some lines like this:

        <ClockStatus>1
        </ClockStatus>

And I would have preferred:

        <ClockStatus>1</ClockStatus>

But the output is still much better than one long line!

Click event on select option element in chrome

Since $(this) isn't correct anymore with ES6 arrow function which don't have have the same this than function() {}, you shouldn't use $( this ) if you use ES6 syntax.
Besides according to the official jQuery's anwser, there's a simpler way to do that what the top answer says.
The best way to get the html of a selected option is to use

$('#yourSelect option:selected').html();

You can replace html() by text() or anything else you want (but html() was in the original question).
Just add the event listener change, with the jQuery's shorthand method change(), to trigger your code when the selected option change.

 $ ('#yourSelect' ).change(() => {
    process($('#yourSelect option:selected').html());
  });

If you just want to know the value of the option:selected (the option that the user has chosen) you can just use $('#yourSelect').val()

How to apply an XSLT Stylesheet in C#

This might help you

public static string TransformDocument(string doc, string stylesheetPath)
{
    Func<string,XmlDocument> GetXmlDocument = (xmlContent) =>
     {
         XmlDocument xmlDocument = new XmlDocument();
         xmlDocument.LoadXml(xmlContent);
         return xmlDocument;
     };

    try
    {
        var document = GetXmlDocument(doc);
        var style = GetXmlDocument(File.ReadAllText(stylesheetPath));

        System.Xml.Xsl.XslCompiledTransform transform = new System.Xml.Xsl.XslCompiledTransform();
        transform.Load(style); // compiled stylesheet
        System.IO.StringWriter writer = new System.IO.StringWriter();
        XmlReader xmlReadB = new XmlTextReader(new StringReader(document.DocumentElement.OuterXml));
        transform.Transform(xmlReadB, null, writer);
        return writer.ToString();
    }
    catch (Exception ex)
    {
        throw ex;
    }

}   

Make absolute positioned div expand parent div height

Absolute views position themselves against the nearest ancestor that isn't statically positioned (position: static), therefore if you want an absolute view positioned against a given parent, set the parent position to relative and the child to position to absolute

@font-face not working

I'm also facing this type of problem. After trying all solutions I got final solution on this problem. Reasons for this type of problem is per-defined global fonts. Use !important keyword for each line in @font-face is the solution for this problem.

Full description and example for Solution of this problem is here :- http://answerdone.blogspot.com/2017/06/font-face-not-working-solution.html

What is a file with extension .a?

.a files are created with the ar utility, and they are libraries. To use it with gcc, collect all .a files in a lib/ folder and then link with -L lib/ and -l<name of specific library>.

Collection of all .a files into lib/ is optional. Doing so makes for better looking directories with nice separation of code and libraries, IMHO.

How can I reload .emacs after changing it?

You can set key-binding for emacs like this

;; reload emacs configuration
(defun reload-init-file ()
  (interactive)
  (load-file "~/.emacs"))

(global-set-key (kbd "C-c r") 'reload-init-file) 

Hope this will help!

How to extract or unpack an .ab file (Android Backup file)

I have had to unpack a .ab-file, too and found this post while looking for an answer. My suggested solution is Android Backup Extractor, a free Java tool for Windows, Linux and Mac OS.

Make sure to take a look at the README, if you encounter a problem. You might have to download further files, if your .ab-file is password-protected.

Usage:
java -jar abe.jar [-debug] [-useenv=yourenv] unpack <backup.ab> <backup.tar> [password]

Example:

Let's say, you've got a file test.ab, which is not password-protected, you're using Windows and want the resulting .tar-Archive to be called test.tar. Then your command should be:

java.exe -jar abe.jar unpack test.ab test.tar ""

MySQL: Check if the user exists and drop it

This worked for me:

GRANT USAGE ON *.* TO 'username'@'localhost';
DROP USER 'username'@'localhost';

This creates the user if it doesn't already exist (and grants it a harmless privilege), then deletes it either way. Found solution here: http://bugs.mysql.com/bug.php?id=19166

Updates: @Hao recommends adding IDENTIFIED BY; @andreb (in comments) suggests disabling NO_AUTO_CREATE_USER.

Android on-screen keyboard auto popping up

If you are using fragments, you need to call hideKeyboard every time in onResume and onCreate if you want to hide the keyboard.

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "SectionMyFragment onResume");
        hideKeyboard();
    }

private void hideKeyboard() {
    if (getActivity() != null) {
        InputMethodManager inputMethodManager = (InputMethodManager)
                getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);

        if (inputMethodManager != null) {
            if (getActivity().getCurrentFocus() != null) {
                Log.d(TAG, "hideSoftInputFromWindow 1");
                inputMethodManager.hideSoftInputFromWindow((getActivity().getCurrentFocus()).getWindowToken(), 0);
            }
        }
    }
}

Can´t run .bat file under windows 10

There is no inherent reason that a simple batch file would run in XP but not Windows 10. It is possible you are referencing a command or a 3rd party utility that no longer exists. To know more about what is actually happening, you will need to do one of the following:

  • Add a pause to the batch file so that you can see what is happening before it exits.
    1. Right click on one of the .bat files and select "edit". This will open the file in notepad.
    2. Go to the very end of the file and add a new line by pressing "enter".
    3. type pause.
    4. Save the file.
    5. Run the file again using the same method you did before.

- OR -

  • Run the batch file from a static command prompt so the window does not close.
    1. In the folder where the .bat files are located, hold down the "shift" key and right click in the white space.
    2. Select "Open Command Window Here".
    3. You will now see a new command prompt. Type in the name of the batch file and press enter.

Once you have done this, I recommend creating a new question with the output you see after using one of the methods above.

Generate a UUID on iOS from Swift

Try this one:

let uuid = NSUUID().uuidString
print(uuid)

Swift 3/4/5

let uuid = UUID().uuidString
print(uuid)

Difference between malloc and calloc?

Difference 1:

malloc() usually allocates the memory block and it is initialized memory segment.

calloc() allocates the memory block and initialize all the memory block to 0.

Difference 2:

If you consider malloc() syntax, it will take only 1 argument. Consider the following example below:

data_type ptr = (cast_type *)malloc( sizeof(data_type)*no_of_blocks );

Ex: If you want to allocate 10 block of memory for int type,

int *ptr = (int *) malloc(sizeof(int) * 10 );

If you consider calloc() syntax, it will take 2 arguments. Consider the following example below:

data_type ptr = (cast_type *)calloc(no_of_blocks, (sizeof(data_type)));

Ex: if you want to allocate 10 blocks of memory for int type and Initialize all that to ZERO,

int *ptr = (int *) calloc(10, (sizeof(int)));

Similarity:

Both malloc() and calloc() will return void* by default if they are not type casted .!

How do I specify different Layouts in the ASP.NET MVC 3 razor ViewStart file?

One more method is to Define the Layout inside the View:

   @{
    Layout = "~/Views/Shared/_MyAdminLayout.cshtml";
    }

More Ways to do, can be found here, hope this helps someone.

How to check if div element is empty

var empty = $("#cartContent").html().trim().length == 0;

Interpreting "condition has length > 1" warning from `if` function

Just adding a point to the whole discussion as to why this warning comes up (It wasn't clear to me before). The reason one gets this is as mentioned before is because 'a' in this case is a vector and the inequality 'a>0' produces another vector of TRUE and FALSE (where 'a' is >0 or not).

If you would like to instead test if any value of 'a>0', you can use functions - 'any' or 'all'

Best

Sass and combined child selector

Without the combined child selector you would probably do something similar to this:

foo {
  bar {
    baz {
      color: red;
    }
  }
}

If you want to reproduce the same syntax with >, you could to this:

foo {
  > bar {
    > baz {
      color: red;
    }
  }
}

This compiles to this:

foo > bar > baz {
  color: red;
}

Or in sass:

foo
  > bar
    > baz
      color: red

Get the index of the object inside an array, matching a condition

As of 2016, you're supposed to use Array.findIndex (an ES2015/ES6 standard) for this:

_x000D_
_x000D_
a = [_x000D_
  {prop1:"abc",prop2:"qwe"},_x000D_
  {prop1:"bnmb",prop2:"yutu"},_x000D_
  {prop1:"zxvz",prop2:"qwrq"}];_x000D_
    _x000D_
index = a.findIndex(x => x.prop2 ==="yutu");_x000D_
_x000D_
console.log(index);
_x000D_
_x000D_
_x000D_

It's supported in Google Chrome, Firefox and Edge. For Internet Explorer, there's a polyfill on the linked page.

Performance note

Function calls are expensive, therefore with really big arrays a simple loop will perform much better than findIndex:

_x000D_
_x000D_
let test = [];_x000D_
_x000D_
for (let i = 0; i < 1e6; i++)_x000D_
    test.push({prop: i});_x000D_
_x000D_
_x000D_
let search = test.length - 1;_x000D_
let count = 100;_x000D_
_x000D_
console.time('findIndex/predefined function');_x000D_
    let fn = obj => obj.prop === search;_x000D_
_x000D_
    for (let i = 0; i < count; i++)_x000D_
        test.findIndex(fn);_x000D_
console.timeEnd('findIndex/predefined function');_x000D_
_x000D_
_x000D_
console.time('findIndex/dynamic function');_x000D_
    for (let i = 0; i < count; i++)_x000D_
        test.findIndex(obj => obj.prop === search);_x000D_
console.timeEnd('findIndex/dynamic function');_x000D_
_x000D_
_x000D_
console.time('loop');_x000D_
    for (let i = 0; i < count; i++) {_x000D_
        for (let index = 0; index < test.length; index++) {_x000D_
            if (test[index].prop === search) {_x000D_
                break;_x000D_
            }_x000D_
        }_x000D_
    }_x000D_
console.timeEnd('loop');
_x000D_
_x000D_
_x000D_

As with most optimizations, this should be applied with care and only when actually needed.

Excel: Can I create a Conditional Formula based on the Color of a Cell?

You can use this function (I found it here: http://excelribbon.tips.net/T010780_Colors_in_an_IF_Function.html):

Function GetFillColor(Rng As Range) As Long
    GetFillColor = Rng.Interior.ColorIndex
End Function

Here is an explanation, how to create user-defined functions: http://www.wikihow.com/Create-a-User-Defined-Function-in-Microsoft-Excel

In your worksheet, you can use the following: =GetFillColor(B5)

Better solution without exluding fields from Binding

You should not use your domain models in your views. ViewModels are the correct way to do it.

You need to map your domain model's necessary fields to viewmodel and then use this viewmodel in your controllers. This way you will have the necessery abstraction in your application.

If you never heard of viewmodels, take a look at this.

convert string to specific datetime format?

No need to apply anything. Just add this code at the end of variable to which date is assigned. For example

   @todaydate = "2011-05-19 10:30:14"
   @todaytime.to_time.strftime('%a %b %d %H:%M:%S %Z %Y')

You will get proper format as you like. You can check this at Rails Console

Loading development environment (Rails 3.0.4)
ruby-1.9.2-p136 :001 > todaytime = "2011-05-19 10:30:14"
 => "2011-05-19 10:30:14" 
ruby-1.9.2-p136 :002 > todaytime
 => "2011-05-19 10:30:14" 
ruby-1.9.2-p136 :003 > todaytime.to_time
 => 2011-05-19 10:30:14 UTC
ruby-1.9.2-p136 :008 > todaytime.to_time.strftime('%a %b %d %H:%M:%S %Z %Y')
 => "Thu May 19 10:30:14 UTC 2011"

Try 'date_format' gem to show date in different format.

Invalid column name sql error

Your issue seems to be the Name keyword. Rather use FullName or firstName and lastName, always try and remember to use CamelCase too.

Running Node.js in apache?

While doing my own server side JS experimentation I ended up using teajs. It conforms to common.js, is based on V8 AND is the only project that I know of that provides 'mod_teajs' apache server module.

In my opinion Node.js server is not production ready and lacks too many features - Apache is battle tested and the right way to do SSJS.

The name does not exist in the namespace error in XAML

In my case it was because of other compile errors. When other errors have been solved this seemingly related error was also removed from the list. Specially the errors at the bottom of the errors list and on pages you have recently changed.

So do not pay attention to this error directly and focus on other errors at first.

Failed to resolve: com.google.android.gms:play-services in IntelliJ Idea with gradle

In my case I was using version 17.0.1 .It was showing error.

implementation "com.google.android.gms:play-services-location:17.0.1"

After changing version to 17.0.0, it worked

implementation "com.google.android.gms:play-services-location:17.0.0"

Reason might be I was using maps dependency of version 17.0.0 & location version as 17.0.1.It might have thrown error.So,try to maintain consistency in version numbers.

Laravel redirect back to original destination after login

For Laravel 5.3 and above

Check Scott's answer below.

For Laravel 5 up to 5.2

Simply put,

On auth middleware:

// redirect the user to "/login"
// and stores the url being accessed on session
if (Auth::guest()) {
    return redirect()->guest('login');
}
return $next($request);

On login action:

// redirect the user back to the intended page
// or defaultpage if there isn't one
if (Auth::attempt(['email' => $email, 'password' => $password])) {
    return redirect()->intended('defaultpage');
}

For Laravel 4 (old answer)

At the time of this answer there was no official support from the framework itself. Nowadays you can use the method pointed out by bgdrl below this method: (I've tried updating his answer, but it seems he won't accept)

On auth filter:

// redirect the user to "/login"
// and stores the url being accessed on session
Route::filter('auth', function() {
    if (Auth::guest()) {
        return Redirect::guest('login');
    }
});

On login action:

// redirect the user back to the intended page
// or defaultpage if there isn't one
if (Auth::attempt(['email' => $email, 'password' => $password])) {
    return Redirect::intended('defaultpage');
}

For Laravel 3 (even older answer)

You could implement it like this:

Route::filter('auth', function() {
    // If there's no user authenticated session
    if (Auth::guest()) {
        // Stores current url on session and redirect to login page
        Session::put('redirect', URL::full());
        return Redirect::to('/login');
    }
    if ($redirect = Session::get('redirect')) {
        Session::forget('redirect');
        return Redirect::to($redirect);
    }
});
// on controller
public function get_login()
{
    $this->layout->nest('content', 'auth.login'); 
}

public function post_login()
{
    $credentials = [
        'username' => Input::get('email'),
        'password' => Input::get('password')
    ];

    if (Auth::attempt($credentials)) {
        return Redirect::to('logged_in_homepage_here');
    }

    return Redirect::to('login')->with_input();
}

Storing the redirection on Session has the benefit of persisting it even if the user miss typed his credentials or he doesn't have an account and has to signup.

This also allows for anything else besides Auth to set a redirect on session and it will work magically.

How to auto resize and adjust Form controls with change in resolution

sorry I saw the question late, Here is an easy programmatically solution that works well on me,

Create those global variables:

 float firstWidth;
 float firstHeight;

after on load, fill those variables;

 firstWidth = this.Size.Width;
 firstHeight = this.Size.Height;

then select your form and put these code to your form's SizeChange event;

 private void AnaMenu_SizeChanged(object sender, EventArgs e)
    {
        

        float size1 = this.Size.Width /  firstWidth;
        float size2 = this.Size.Height / firstHeight;

            SizeF scale = new SizeF(size1, size2);
        firstWidth = this.Size.Width;
        firstHeight = this.Size.Height;

        foreach (Control control in this.Controls)
        {
                
            control.Font = new Font(control.Font.FontFamily, control.Font.Size* ((size1+ size2)/2));
            
            control.Scale(scale);
                

        }


    }

I hope this helps, it works perfect on my projects.

How to find the operating system version using JavaScript?

Hey for a quick solution you can consider the following library : UAPARSER - https://www.npmjs.com/package/ua-parser-js

example :

<script type="text/javascript" src="ua-parser.min.js"></script>
<script type="text/javascript">

var parser = new UAParser();
console.log(parser.getOS()) // will log  {name: "", version:""}

you can also install the library via npm, and import it like this:

import { UAParser } from 'ua-parser-js';
let parser = new UAParser();
parser.getOS();

the library is a JS based user agent string parser (window.navigator.userAgent is the user agent on browser) , so you can get with it other details aswell such as Browser,device,engines etc..and it can work with node js as well.

if you need typing for the library : https://www.npmjs.com/package/@types/ua-parser-js

Can I run HTML files directly from GitHub, instead of just viewing their source?

You can do this easily by Modifying Response Headers which can be done with Chrome and Firefox extension like Requestly.

In Chrome and Firefox:

  1. Install Requestly for Chrome and Requestly for Firefox

  2. Add the following Headers Modification Rules:

    enter image description here

    a) Content-Type:

    • Modify
    • Response
    • Header: Content-Type
    • Value: text/html
    • Source Url Matches: /raw\.githubusercontent\.com/.*\.html/


    b) Content-Security-Policy:

    • Modify
    • Response
    • Header: Content-Security-Policy
    • Value: default-src 'none'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; script-src * 'unsafe-eval';
    • Source Url Matches: /raw\.githubusercontent\.com/.*\.html/

Python: Binding Socket: "Address already in use"

another solution, in development environment of course, is killing process using it, for example

def serve():
    server = HTTPServer(('', PORT_NUMBER), BaseHTTPRequestHandler)
    print 'Started httpserver on port ' , PORT_NUMBER
    server.serve_forever()
try:
    serve()
except Exception, e:
    print "probably port is used. killing processes using given port %d, %s"%(PORT_NUMBER,e)
    os.system("xterm -e 'sudo fuser -kuv %d/tcp'" % PORT_NUMBER)
    serve()
    raise e

Use Device Login on Smart TV / Console

Implement Login for Devices

Facebook Login for Devices is for devices that directly make HTTP calls over the internet. The following are the API calls and responses your device can make.

1. Enable Login for Devices

Change Settings > Advanced > OAuth Settings > Login from Devices to 'Yes'.

2. Generate a Code which is required for facebook device identification

When the person clicks Log in with Facebook, you device should make an HTTP POST to:

POST https://graph.facebook.com/oauth/device?
       type=device_code
       &amp;client_id=<YOUR_APP_ID>
       &amp;scope=<COMMA_SEPARATED_PERMISSION_NAMES> // e.g.public_profile,user_likes

The response comes in this form:

{
  "code": "92a2b2e351f2b0b3503b2de251132f47",
  "user_code": "A1NWZ9",
  "verification_uri": "https://www.facebook.com/device",
  "expires_in": 420,
  "interval": 5
}

This response means:

  • Display the string “A1NWZ9” on your device
  • Tell the person to go to “facebook.com/device” and enter this code
  • The code expires in 420 seconds. You should cancel the login flow after that time if you do not receive an access token
  • Your device should poll the Device Login API every 5 seconds to see if the authorization has been successful

3. Display the Code

Your device should display the user_code and tell people to visit the verification_uri such as facebook.com/device on their PC or smartphone. See the Design Guidelines.

4. Poll for Authorization

Your device should poll the Device Login API to see if the person successfully authorized your application. You should do this at the interval in the response to your call in Step 1, which is every 5 seconds. Your device should poll to:

POST https://graph.facebook.com/oauth/device?
       type=device_token
       &amp;client_id=<YOUR_APP_ID> 
       &amp;code=<LONG_CODE_FROM_STEP_1> //e.g."92a2b2e351f2b0b3503b2de251132f47"

You will get 200 HTTP code i.e User has successfully authorized the device. The device can now use the access_token value to make authenticated API calls.

5. Confirm Successful Login

Your device should display their name and if available, a profile picture until they click Continue. To get the person's name and profile picture, your device should make a standard Graph API call:

GET https://graph.facebook.com/v2.3/me?
      fields=name,picture&amp;
      access_token=<USER_ACCESS_TOKEN>

Response:

{
  "name": "John Doe", 
  "picture": {
    "data": {
      "is_silhouette": false, 
      "url": "https://fbcdn.akamaihd.net/hmac...ile.jpg"
    }
  }, 
  "id": "2023462875238472"
}

6. Store Access Tokens

Your device should persist the access token to make other requests to the Graph API.

Device Login access tokens may be valid for up to 60 days but may be invalided in a number of scenarios. For example when a person changes their Facebook password their access token is invalidated.

If the token is invalid, your device should delete the token from its memory. The person using your device needs to perform the Device Login flow again from Step 1 to retrieve a new, valid token.

Matlab: Running an m-file from command-line

I think that one important point that was not mentioned in the previous answers is that, if not explicitly indicated, the matlab interpreter will remain open. Therefore, to the answer of @hkBattousai I will add the exit command:

"C:\<a long path here>\matlab.exe" -nodisplay -nosplash -nodesktop -r "run('C:\<a long path here>\mfile.m');exit;"

How can building a heap be O(n) time complexity?

Your analysis is correct. However, it is not tight.

It is not really easy to explain why building a heap is a linear operation, you should better read it.

A great analysis of the algorithm can be seen here.


The main idea is that in the build_heap algorithm the actual heapify cost is not O(log n)for all elements.

When heapify is called, the running time depends on how far an element might move down in tree before the process terminates. In other words, it depends on the height of the element in the heap. In the worst case, the element might go down all the way to the leaf level.

Let us count the work done level by level.

At the bottommost level, there are 2^(h)nodes, but we do not call heapify on any of these, so the work is 0. At the next to level there are 2^(h - 1) nodes, and each might move down by 1 level. At the 3rd level from the bottom, there are 2^(h - 2) nodes, and each might move down by 2 levels.

As you can see not all heapify operations are O(log n), this is why you are getting O(n).

How to convert string into float in JavaScript?

Try

_x000D_
_x000D_
let str ="554,20";_x000D_
let float = +str.replace(',','.');_x000D_
let int = str.split(',').map(x=>+x);_x000D_
_x000D_
console.log({float,int});
_x000D_
_x000D_
_x000D_

Animation CSS3: display + opacity

display: is not transitionable. You'll probably need to use jQuery to do what you want to do.

How to determine SSL cert expiration date from a PEM encoded certificate?

One line checking on true/false if cert of domain will be expired in some time later(ex. 15 days):

openssl x509 -checkend $(( 24*3600*15 )) -noout -in <(openssl s_client -showcerts -connect my.domain.com:443 </dev/null 2>/dev/null | openssl x509 -outform PEM)
if [ $? -eq 0 ]; then
  echo 'good'
else
  echo 'bad'
fi

Split string with delimiters in C

Explode & implode - initial string remains intact, dynamic memory allocation

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

typedef struct
{
    uintptr_t   ptr;
    int         size;
} token_t;

int explode(char *str, int slen, const char *delimiter, token_t **tokens)
{
    int i = 0, c1 = 0, c2 = 0;

    for(i = 0; i <= slen; i++)
    {
            if(str[i] == *delimiter)
            {
                c1++;
            }
    }

    if(c1 == 0)
    {
            return -1;
    }

    *tokens = (token_t*)calloc((c1 + 1), sizeof(token_t));
    ((*tokens)[c2]).ptr = (uintptr_t)str;

    i = 0; 
    while(i <= slen)
    {
        if((str[i] == *delimiter) || (i == slen))
        {
                ((*tokens)[c2]).size = (int)((uintptr_t)&(str[i]) - (uintptr_t)(((*tokens)[c2]).ptr));
                if(i < slen)
                {
                    c2++;
                    ((*tokens)[c2]).ptr = (uintptr_t)&(str[i + 1]);
                }
        }
        i++;
    }
    return (c1 + 1);
}

char* implode(token_t *tokens, int size, const char *delimiter)
{
    int     i, len = 0;
    char    *str;

    for(i = 0; i < len; i++)
    {
        len += tokens[i].size + 1;
    }

    str = (char*)calloc(len, sizeof(char));

    len = 0;
    for(i = 0; i < size; i++)
    {
        memcpy((void*)&str[len], (void*)tokens[i].ptr, tokens[i].size);
        len += tokens[i].size;
        str[(len++)] = *delimiter;
    }

    str[len - 1] = '\0';

    return str;
}

Usage:

int main(int argc, char **argv)
{
    int         i, c;
    char        *exp = "JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC";
    token_t     *tokens;
    char        *imp;

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

    if((c = explode(exp, strlen(exp), ",", &tokens)) > 0)
    {
        imp = implode(tokens, c, ",");
        printf("%s\n", imp);

        for(i = 0; i < c; i++)
        {
            printf("%.*s, %d\n", tokens[i].size, (char*)tokens[i].ptr, tokens[i].size);
        }
    }

    free((void*)tokens);
    free((void*)imp);
    return 0;
}

Passing in class names to react components

For anyone interested, I ran into this same issue when using css modules and react css modules.

Most components have an associated css module style, and in this example my Button has its own css file, as does the Promo parent component. But I want to pass some additional styles to Button from Promo

So the styleable Button looks like this:

Button.js

import React, { Component } from 'react'
import CSSModules from 'react-css-modules'
import styles from './Button.css'

class Button extends Component {

  render() {

    let button = null,
        className = ''

    if(this.props.className !== undefined){
        className = this.props.className
    }

    button = (
      <button className={className} styleName='button'>
        {this.props.children}
      </button>
    )

    return (
        button
    );
  }
};

export default CSSModules(Button, styles, {allowMultiple: true} )

In the above Button component the Button.css styles handle the common button styles. In this example just a .button class

Then in my component where I want to use the Button, and I also want to modify things like the position of the button, I can set extra styles in Promo.css and pass through as the className prop. In this example again called .button class. I could have called it anything e.g. promoButton.

Of course with css modules this class will be .Promo__button___2MVMD whereas the button one will be something like .Button__button___3972N

Promo.js

import React, { Component } from 'react';
import CSSModules from 'react-css-modules';
import styles from './Promo.css';

import Button from './Button/Button'

class Promo extends Component {

  render() {

    return (
        <div styleName='promo' >
          <h1>Testing the button</h1>
          <Button className={styles.button} >
            <span>Hello button</span>
          </Button>
        </div>
      </Block>
    );
  }
};

export default CSSModules(Promo, styles, {allowMultiple: true} );

How to check undefined in Typescript

In Typescript 2 you can use Undefined type to check for undefined values. So if you declare a variable as:

let uemail : string | undefined;

Then you can check if the variable z is undefined as:

if(uemail === undefined)
{

}

MySQL Data - Best way to implement paging?

For 500 records efficiency is probably not an issue, but if you have millions of records then it can be advantageous to use a WHERE clause to select the next page:

SELECT *
FROM yourtable
WHERE id > 234374
ORDER BY id
LIMIT 20

The "234374" here is the id of the last record from the prevous page you viewed.

This will enable an index on id to be used to find the first record. If you use LIMIT offset, 20 you could find that it gets slower and slower as you page towards the end. As I said, it probably won't matter if you have only 200 records, but it can make a difference with larger result sets.

Another advantage of this approach is that if the data changes between the calls you won't miss records or get a repeated record. This is because adding or removing a row means that the offset of all the rows after it changes. In your case it's probably not important - I guess your pool of adverts doesn't change too often and anyway no-one would notice if they get the same ad twice in a row - but if you're looking for the "best way" then this is another thing to keep in mind when choosing which approach to use.

If you do wish to use LIMIT with an offset (and this is necessary if a user navigates directly to page 10000 instead of paging through pages one by one) then you could read this article about late row lookups to improve performance of LIMIT with a large offset.

"CAUTION: provisional headers are shown" in Chrome debugger

Another possible scenario I've seen - the exact same request is being sent again just after few milliseconds (most likely due to a bug in the client side).
In that case you'll also see that the status of the first request is "canceled" and that the latency is only several milliseconds.

start MySQL server from command line on Mac OS Lion

If it's installed with homebrew try just typing down mysql.server in terminal and that should be it. AFAIK it executable will be under /usr/local/bin/mysql.server.

If not you can always run following "locate mysql.server" which will tell you where to find such file.

Change priorityQueue to max priorityqueue

I just ran a Monte-Carlo simulation on both comparators on double heap sort min max and they both came to the same result:

These are the max comparators I have used:

(A) Collections built-in comparator

 PriorityQueue<Integer> heapLow = new PriorityQueue<Integer>(Collections.reverseOrder());

(B) Custom comparator

PriorityQueue<Integer> heapLow = new PriorityQueue<Integer>(new Comparator<Integer>() {
    int compare(Integer lhs, Integer rhs) {
        if (rhs > lhs) return +1;
        if (rhs < lhs) return -1;
        return 0;
    }
});

subquery in FROM must have an alias

In the case of nested tables, some DBMS require to use an alias like MySQL and Oracle but others do not have such a strict requirement, but still allow to add them to substitute the result of the inner query.

Scala check if element is present in a list

Just use contains

myFunction(strings.contains(myString))

How does #include <bits/stdc++.h> work in C++?

That header file is not part of the C++ standard, is therefore non-portable, and should be avoided.

Moreover, even if there were some catch-all header in the standard, you would want to avoid it in lieu of specific headers, since the compiler has to actually read in and parse every included header (including recursively included headers) every single time that translation unit is compiled.

Simplest way to download and unzip files in Node.js cross-platform?

I tried a few of the nodejs unzip libraries including adm-zip and unzip, then settled on extract-zip which is a wrapper around yauzl. Seemed the simplest to implement.

https://www.npmjs.com/package/extract-zip

var extract = require('extract-zip')
extract(zipfile, { dir: outputPath }, function (err) {
   // handle err
})

How to compare two dates to find time difference in SQL Server 2005, date manipulation

Declare the Start and End date DECLARE @SDATE AS DATETIME

TART_DATE  AS DATETIME
DECLARE @END_-- Set Start and End date
SET @START_DATE = GETDATE()
SET @END_DATE    = DATEADD(SECOND, 3910, GETDATE())

-- Get the Result in HH:MI:SS:MMM(24H) format SELECT CONVERT(VARCHAR(12), DATEADD(MS, DATEDIFF(MS, @START_DATE, @END_DATE), 0), 114) AS TimeDiff

How to hide UINavigationBar 1px bottom line

Here is an way to do it without using any images, this is the only way that worked for me:

self.navigationController.navigationBar.layer.shadowOpacity = 0;

Unfortunately, you need to do this on every file where you want the line not to appear. There's no way to do it this way in appDelegate.

Edit:

Setting the shadowColor to nil isn't needed, this is the only line that you'll need.

SQL query, store result of SELECT in local variable

I came here with a similar question/problem, but I only needed a single value to be stored from the query, not an array/table of results as in the orig post. I was able to use the table method above for a single value, however I have stumbled upon an easier way to store a single value.

declare @myVal int; set @myVal = isnull((select a from table1), 0);

Make sure to default the value in the isnull statement to a valid type for your variable, in my example the value in table1 that we're storing is an int.

What is a singleton in C#?

A Singleton (and this isn't tied to C#, it's an OO design pattern) is when you want to allow only ONE instance of a class to be created throughout your application. Useages would typically include global resources, although I will say from personal experience, they're very often the source of great pain.

Where is the web server root directory in WAMP?

To check what is your root directory go to httpd.conf file of apache and search for "DocumentRoot".The location following it is your root directory

How to dismiss keyboard iOS programmatically when pressing return

Add Delegate : UITextFieldDelegate

@interface ViewController : UIViewController <UITextFieldDelegate>

and then add this delegate method

// This should work perfectly

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

PHP date() with timezone?

If I understood correct,You need to set time zone first like:

date_default_timezone_set('UTC');

And than you can use date function:

// Prints something like: Monday 8th of August 2005 03:12:46 PM
echo date('l jS \of F Y h:i:s A');

Reference to non-static member function must be called

You may want to have a look at https://isocpp.org/wiki/faq/pointers-to-members#fnptr-vs-memfnptr-types, especially [33.1] Is the type of "pointer-to-member-function" different from "pointer-to-function"?