Programs & Examples On #Jdialog

The main Java Swing class for creating a dialog window.

Java - How to create a custom dialog box?

If you don't need much in the way of custom behavior, JOptionPane is a good time saver. It takes care of the placement and localization of OK / Cancel options, and is a quick-and-dirty way to show a custom dialog without needing to define your own classes. Most of the time the "message" parameter in JOptionPane is a String, but you can pass in a JComponent or array of JComponents as well.

Example:

JTextField firstName = new JTextField();
JTextField lastName = new JTextField();
JPasswordField password = new JPasswordField();
final JComponent[] inputs = new JComponent[] {
        new JLabel("First"),
        firstName,
        new JLabel("Last"),
        lastName,
        new JLabel("Password"),
        password
};
int result = JOptionPane.showConfirmDialog(null, inputs, "My custom dialog", JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
    System.out.println("You entered " +
            firstName.getText() + ", " +
            lastName.getText() + ", " +
            password.getText());
} else {
    System.out.println("User canceled / closed the dialog, result = " + result);
}

background-size in shorthand background property (CSS3)

You will have to use vendor prefixes to support different browsers and therefore can't use it in shorthand.

body { 
        background: url(images/bg.jpg) no-repeat center center fixed; 
        -webkit-background-size: cover;
        -moz-background-size: cover;
        -o-background-size: cover;
        background-size: cover;
}

Best way to get user GPS location in background in Android

You have to create service.That service should implement LocationListener. Then You have to use AlarmManager for calling service repeatedly with certain time limit.

I hope this one will help to you :)

wordpress contactform7 textarea cols and rows change in smaller screens

Add it after Placeholder attribute.

[textarea* message id:message class:form-control 40x7 placeholder "Message"]

How to find out which JavaScript events fired?

Regarding Chrome, checkout the monitorEvents() via the command line API.

  • Open the console via Menu > Tools > JavaScript Console.

  • Enter monitorEvents(window);

  • View the console flooded with events

     ...
     mousemove MouseEvent {dataTransfer: ...}
     mouseout MouseEvent {dataTransfer: ...}
     mouseover MouseEvent {dataTransfer: ...}
     change Event {clipboardData: ...}
     ...
    

There are other examples in the documentation. I'm guessing this feature was added after the previous answer.

How to git clone a specific tag

Use the command

git clone --help

to see whether your git supports the command

git clone --branch tag_name

If not, just do the following:

git clone repo_url 
cd repo
git checkout tag_name

How to change font size in html?

If you want to do this without adding classes...

p:first-child {
    font-size: 16px;
}

p:last-child {
    font-size: 12px;
}

or

p:nth-child(1) {
    font-size: 16px;
}

p:nth-child(2) {
    font-size: 12px;
}

sql use statement with variable

If SQLCMD is an option, it supports scripting variables above and beyond what straight T-SQL can do. For example: http://msdn.microsoft.com/en-us/library/ms188714.aspx

Installing ADB on macOS

Option 3 - Using MacPorts

Analoguously to the two options (homebrew / manual) posted by @brismuth, here's the MacPorts way:

  1. Install the Android SDK:

    sudo port install android
    
  2. Run the SDK manager:

    sh /opt/local/share/java/android-sdk-macosx/tools/android
    
  3. As @brismuth suggested, uncheck everything but Android SDK Platform-tools (optional)

  4. Install the packages, accepting licenses. Close the SDK Manager.

  5. Add platform-tools to your path; in MacPorts, they're in /opt/local/share/java/android-sdk-macosx/platform-tools. E.g., for bash:

    echo 'export PATH=$PATH:/opt/local/share/java/android-sdk-macosx/platform-tools' >> ~/.bash_profile
    
  6. Refresh your bash profile (or restart your terminal/shell):

    source ~/.bash_profile
    
  7. Start using adb:

    adb devices
    

SELECT * FROM multiple tables. MySQL

In order to get rid of duplicates, you can group by drinks.id. But that way you'll get only one photo for each drinks.id (which photo you'll get depends on database internal implementation).

Though it is not documented, in case of MySQL, you'll get the photo with lowest id (in my experience I've never seen other behavior).

SELECT name, price, photo 
FROM drinks, drinks_photos 
WHERE drinks.id = drinks_id
GROUP BY drinks.id

Clang vs GCC - which produces faster binaries?

There is very little overall difference between GCC 4.8 and clang 3.3 in terms of speed of the resulting binary. In most cases code generated by both compilers performs similarly. Neither of these two compilers dominates the other one.

Benchmarks telling that there is a significant performance gap between GCC and clang are coincidental.

Program performance is affected by the choice of the compiler. If a developer or a group of developers is exclusively using GCC then the program can be expected to run slightly faster with GCC than with clang, and vice versa.

From developer viewpoint, a notable difference between GCC 4.8+ and clang 3.3 is that GCC has the -Og command line option. This option enables optimizations that do not interfere with debugging, so for example it is always possible to get accurate stack traces. The absence of this option in clang makes clang harder to use as an optimizing compiler for some developers.

Bash array with spaces in elements

Escaping works.

#!/bin/bash

FILES=(2011-09-04\ 21.43.02.jpg
2011-09-05\ 10.23.14.jpg
2011-09-09\ 12.31.16.jpg
2011-09-11\ 08.43.12.jpg)

echo ${FILES[0]}
echo ${FILES[1]}
echo ${FILES[2]}
echo ${FILES[3]}

Output:

$ ./test.sh
2011-09-04 21.43.02.jpg
2011-09-05 10.23.14.jpg
2011-09-09 12.31.16.jpg
2011-09-11 08.43.12.jpg

Quoting the strings also produces the same output.

How to set text color in submit button?

<input type = "button" style ="background-color:green"/>

Get current URL from IFRAME

If you are in the iframe context,

you could do

const currentIframeHref = new URL(document.location.href);
const urlOrigin = currentIframeHref.origin;
const urlFilePath = decodeURIComponent(currentIframeHref.pathname);

If you are in the parent window/frame, then you can use https://stackoverflow.com/a/938195/2305243 's answer, which is

document.getElementById("iframe_id").contentWindow.location.href

Get String in YYYYMMDD format from JS date object?

this post helped me to write this helper, so I share it in case some one is looking for this solution, it supports all variations of yyyy, mm, dd

Date.prototype.formattedDate = function (pattern) {
    formattedDate = pattern.replace('yyyy', this.getFullYear().toString());
    var mm = (this.getMonth() + 1).toString(); // getMonth() is zero-based
    mm = mm.length > 1 ? mm : '0' + mm;
    formattedDate = formattedDate.replace('mm', mm);
    var dd = this.getDate().toString();
    dd = dd.length > 1 ? dd : '0' + dd;
    formattedDate = formattedDate.replace('dd', dd);
    return formattedDate;
};

d = new Date();
pattern = 'yyyymmdd';  // 20150813
d.formattedDate(pattern);

pattern = 'yyyy-mm-dd';
d.formattedDate(pattern); // 2015-08-13

json.net has key method?

JObject implements IDictionary<string, JToken>, so you can use:

IDictionary<string, JToken> dictionary = x;
if (dictionary.ContainsKey("error_msg"))

... or you could use TryGetValue. It implements both methods using explicit interface implementation, so you can't use them without first converting to IDictionary<string, JToken> though.

What does the construct x = x || y mean?

And I have to add one more thing: This bit of shorthand is an abomination. It misuses an accidental interpreter optimization (not bothering with the second operation if the first is truthy) to control an assignment. That use has nothing to do with the purpose of the operator. I do not believe it should ever be used.

I prefer the ternary operator for initialization, eg,

var title = title?title:'Error';

This uses a one-line conditional operation for its correct purpose. It still plays unsightly games with truthiness but, that's Javascript for you.

What is {this.props.children} and when you should use it?

props.children represents the content between the opening and the closing tags when invoking/rendering a component:

const Foo = props => (
  <div>
    <p>I'm {Foo.name}</p>
    <p>abc is: {props.abc}</p>

    <p>I have {props.children.length} children.</p>
    <p>They are: {props.children}.</p>
    <p>{Array.isArray(props.children) ? 'My kids are an array.' : ''}</p>
  </div>
);

const Baz = () => <span>{Baz.name} and</span>;
const Bar = () => <span> {Bar.name}</span>;

invoke/call/render Foo:

<Foo abc={123}>
  <Baz />
  <Bar />
</Foo>

props and props.children

How to subtract one month using moment.js?

For substracting in moment.js:

moment().subtract(1, 'months').format('MMM YYYY');

Documentation:

http://momentjs.com/docs/#/manipulating/subtract/

Before version 2.8.0, the moment#subtract(String, Number) syntax was also supported. It has been deprecated in favor of moment#subtract(Number, String).

  moment().subtract('seconds', 1); // Deprecated in 2.8.0
  moment().subtract(1, 'seconds');

As of 2.12.0 when decimal values are passed for days and months, they are rounded to the nearest integer. Weeks, quarters, and years are converted to days or months, and then rounded to the nearest integer.

  moment().subtract(1.5, 'months') == moment().subtract(2, 'months')
  moment().subtract(.7, 'years') == moment().subtract(8, 'months') //.7*12 = 8.4, rounded to 8

What is the meaning of the prefix N in T-SQL statements and when should I use it?

It's declaring the string as nvarchar data type, rather than varchar

You may have seen Transact-SQL code that passes strings around using an N prefix. This denotes that the subsequent string is in Unicode (the N actually stands for National language character set). Which means that you are passing an NCHAR, NVARCHAR or NTEXT value, as opposed to CHAR, VARCHAR or TEXT.

To quote from Microsoft:

Prefix Unicode character string constants with the letter N. Without the N prefix, the string is converted to the default code page of the database. This default code page may not recognize certain characters.


If you want to know the difference between these two data types, see this SO post:

What is the difference between varchar and nvarchar?

How do I import the javax.servlet API in my Eclipse project?

you can simply copy the servlet-api.jar and copy that jar files into lib folder, which is in WEB-INF. then just clean and built your project, your errors will be solved.

  **OR**

you can directly add jar files to library by using following steps.

  1. Right click on project.
  2. Go To Properties.
  3. Go to Java Build Path.
  4. Select Add Library option from tabs.
  5. Add Jar Files
  6. give path of your servlet-api.jar file.
  7. Clean and build your project.

How to iterate (keys, values) in JavaScript?

tl;dr

  1. In ECMAScript 5, it is not possible.
  2. In ECMAScript 2015, it is possible with Maps.
  3. In ECMAScript 2017, it would be readily available.

ECMAScript 5:

No, its not possible with objects.

You should either iterate with for..in, or Object.keys, like this

for (var key in dictionary) {
    // check if the property/key is defined in the object itself, not in parent
    if (dictionary.hasOwnProperty(key)) {           
        console.log(key, dictionary[key]);
    }
}

Note: The if condition above is necessary, only if you want to iterate the properties which are dictionary object's very own. Because for..in will iterate through all the inherited enumerable properties.

Or

Object.keys(dictionary).forEach(function(key) {
    console.log(key, dictionary[key]);
});

ECMAScript 2015

In ECMAScript 2015, you can use Map objects and iterate them with Map.prototype.entries. Quoting example from that page,

var myMap = new Map();
myMap.set("0", "foo");
myMap.set(1, "bar");
myMap.set({}, "baz");

var mapIter = myMap.entries();

console.log(mapIter.next().value); // ["0", "foo"]
console.log(mapIter.next().value); // [1, "bar"]
console.log(mapIter.next().value); // [Object, "baz"]

Or iterate with for..of, like this

'use strict';

var myMap = new Map();
myMap.set("0", "foo");
myMap.set(1, "bar");
myMap.set({}, "baz");

for (const entry of myMap.entries()) {
  console.log(entry);
}

Output

[ '0', 'foo' ]
[ 1, 'bar' ]
[ {}, 'baz' ]

Or

for (const [key, value] of myMap.entries()) {
  console.log(key, value);
}

Output

0 foo
1 bar
{} baz

ECMAScript 2017

ECMAScript 2017 would introduce a new function Object.entries. You can use this to iterate the object as you wanted.

'use strict';

const object = {'a': 1, 'b': 2, 'c' : 3};
for (const [key, value] of Object.entries(object)) {
  console.log(key, value);
}

Output

a 1
b 2
c 3

How can I create an error 404 in PHP?

The up-to-date answer (as of PHP 5.4 or newer) for generating 404 pages is to use http_response_code:

<?php
http_response_code(404);
include('my_404.php'); // provide your own HTML for the error page
die();

die() is not strictly necessary, but it makes sure that you don't continue the normal execution.

How do I programmatically click a link with javascript?

Instead of clicking, can you forward to the URL that the click would go to using Javascript?

Maybe you could put something in the body onLoad to go where you want.

What does 'killed' mean when a processing of a huge CSV with Python, which suddenly stops?

There are two storage areas involved: the stack and the heap.The stack is where the current state of a method call is kept (ie local variables and references), and the heap is where objects are stored. recursion and memory

I gues there are too many keys in the counter dict that will consume too much memory of the heap region, so the Python runtime will raise a OutOfMemory exception.

To save it, don't create a giant object, e.g. the counter.

1.StackOverflow

a program that create too many local variables.

Python 2.7.9 (default, Mar  1 2015, 12:57:24) 
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open('stack_overflow.py','w')
>>> f.write('def foo():\n')
>>> for x in xrange(10000000):
...   f.write('\tx%d = %d\n' % (x, x))
... 
>>> f.write('foo()')
>>> f.close()
>>> execfile('stack_overflow.py')
Killed

2.OutOfMemory

a program that creats a giant dict includes too many keys.

>>> f = open('out_of_memory.py','w')
>>> f.write('def foo():\n')
>>> f.write('\tcounter = {}\n')
>>> for x in xrange(10000000):
...   f.write('counter[%d] = %d\n' % (x, x))
... 
>>> f.write('foo()\n')
>>> f.close()
>>> execfile('out_of_memory.py')
Killed

References

How to change option menu icon in the action bar?

This works properly in my case:

Drawable drawable = ContextCompat.getDrawable(getApplicationContext(),
                                              R.drawable.change_pass);
toolbar.setOverflowIcon(drawable);

Inserting one list into another list in java?

no... Once u have executed the statement anotherList.addAll(list) and after that if u change some list data it does not carry to another list

Deep copy, shallow copy, clone

The term "clone" is ambiguous (though the Java class library includes a Cloneable interface) and can refer to a deep copy or a shallow copy. Deep/shallow copies are not specifically tied to Java but are a general concept relating to making a copy of an object, and refers to how members of an object are also copied.

As an example, let's say you have a person class:

class Person {
    String name;
    List<String> emailAddresses
}

How do you clone objects of this class? If you are performing a shallow copy, you might copy name and put a reference to emailAddresses in the new object. But if you modified the contents of the emailAddresses list, you would be modifying the list in both copies (since that's how object references work).

A deep copy would mean that you recursively copy every member, so you would need to create a new List for the new Person, and then copy the contents from the old to the new object.

Although the above example is trivial, the differences between deep and shallow copies are significant and have a major impact on any application, especially if you are trying to devise a generic clone method in advance, without knowing how someone might use it later. There are times when you need deep or shallow semantics, or some hybrid where you deep copy some members but not others.

How do I escape a string inside JavaScript code inside an onClick handler?

First, it would be simpler if the onclick handler was set this way:

<a id="someLinkId"href="#">Select</a>
<script type="text/javascript">
  document.getElementById("someLinkId").onClick = 
   function() {
      SelectSurveyItem('<%itemid%>', '<%itemname%>'); return false;
    };

</script>

Then itemid and itemname need to be escaped for JavaScript (that is, " becomes \", etc.).

If you are using Java on the server side, you might take a look at the class StringEscapeUtils from jakarta's common-lang. Otherwise, it should not take too long to write your own 'escapeJavascript' method.

Given an RGB value, how do I create a tint (or shade)?

Some definitions

  • A shade is produced by "darkening" a hue or "adding black"
  • A tint is produced by "ligthening" a hue or "adding white"

Creating a tint or a shade

Depending on your Color Model, there are different methods to create a darker (shaded) or lighter (tinted) color:

  • RGB:

    • To shade:

      newR = currentR * (1 - shade_factor)
      newG = currentG * (1 - shade_factor)
      newB = currentB * (1 - shade_factor)
      
    • To tint:

      newR = currentR + (255 - currentR) * tint_factor
      newG = currentG + (255 - currentG) * tint_factor
      newB = currentB + (255 - currentB) * tint_factor
      
    • More generally, the color resulting in layering a color RGB(currentR,currentG,currentB) with a color RGBA(aR,aG,aB,alpha) is:

      newR = currentR + (aR - currentR) * alpha
      newG = currentG + (aG - currentG) * alpha
      newB = currentB + (aB - currentB) * alpha
      

    where (aR,aG,aB) = black = (0,0,0) for shading, and (aR,aG,aB) = white = (255,255,255) for tinting

  • HSV or HSB:

    • To shade: lower the Value / Brightness or increase the Saturation
    • To tint: lower the Saturation or increase the Value / Brightness
  • HSL:
    • To shade: lower the Lightness
    • To tint: increase the Lightness

There exists formulas to convert from one color model to another. As per your initial question, if you are in RGB and want to use the HSV model to shade for example, you can just convert to HSV, do the shading and convert back to RGB. Formula to convert are not trivial but can be found on the internet. Depending on your language, it might also be available as a core function :

Comparing the models

  • RGB has the advantage of being really simple to implement, but:
    • you can only shade or tint your color relatively
    • you have no idea if your color is already tinted or shaded
  • HSV or HSB is kind of complex because you need to play with two parameters to get what you want (Saturation & Value / Brightness)
  • HSL is the best from my point of view:
    • supported by CSS3 (for webapp)
    • simple and accurate:
      • 50% means an unaltered Hue
      • >50% means the Hue is lighter (tint)
      • <50% means the Hue is darker (shade)
    • given a color you can determine if it is already tinted or shaded
    • you can tint or shade a color relatively or absolutely (by just replacing the Lightness part)

Get cart item name, quantity all details woocommerce

Try this :

<?php
    global $woocommerce;
    $items = $woocommerce->cart->get_cart();

        foreach($items as $item => $values) { 
            $_product =  wc_get_product( $values['data']->get_id()); 
            echo "<b>".$_product->get_title().'</b>  <br> Quantity: '.$values['quantity'].'<br>'; 
            $price = get_post_meta($values['product_id'] , '_price', true);
            echo "  Price: ".$price."<br>";
        } 
?>

To get Product Image and Regular & Sale Price:

<?php
    global $woocommerce;
    $items = $woocommerce->cart->get_cart();

        foreach($items as $item => $values) { 
            $_product =  wc_get_product( $values['data']->get_id() );
            //product image
            $getProductDetail = wc_get_product( $values['product_id'] );
            echo $getProductDetail->get_image(); // accepts 2 arguments ( size, attr )

            echo "<b>".$_product->get_title() .'</b>  <br> Quantity: '.$values['quantity'].'<br>'; 
            $price = get_post_meta($values['product_id'] , '_price', true);
            echo "  Price: ".$price."<br>";
            /*Regular Price and Sale Price*/
            echo "Regular Price: ".get_post_meta($values['product_id'] , '_regular_price', true)."<br>";
            echo "Sale Price: ".get_post_meta($values['product_id'] , '_sale_price', true)."<br>";
        }
?>

Making macOS Installer Packages which are Developer ID ready

Here is a build script which creates a signed installer package out of a build root.

#!/bin/bash
# TRIMCheck build script
# Copyright Doug Richardson 2015
# Usage: build.sh
#
# The result is a disk image that contains the TRIMCheck installer.
#

DSTROOT=/tmp/trimcheck.dst
SRCROOT=/tmp/trimcheck.src

INSTALLER_PATH=/tmp/trimcheck
INSTALLER_PKG="TRIMCheck.pkg"
INSTALLER="$INSTALLER_PATH/$INSTALLER_PKG"

#
# Clean out anything that doesn't belong.
#
echo Going to clean out build directories
rm -rf build $DSTROOT $SRCROOT $INSTALLER_PATH
echo Build directories cleaned out


#
# Build
#
echo ------------------
echo Installing Sources
echo ------------------
xcodebuild -project TRIMCheck.xcodeproj installsrc SRCROOT=$SRCROOT || exit 1

echo ----------------
echo Building Project
echo ----------------
pushd $SRCROOT
xcodebuild -project TRIMCheck.xcodeproj -target trimcheck -configuration Release install || exit 1
popd

echo ------------------
echo Building Installer
echo ------------------
mkdir -p "$INSTALLER_PATH" || exit 1

echo "Runing pkgbuild. Note you must be connected to Internet for this to work as it"
echo "has to contact a time server in order to generate a trusted timestamp. See"
echo "man pkgbuild for more info under SIGNED PACKAGES."
pkgbuild --identifier "com.delicioussafari.TRIMCheck" \
    --sign "Developer ID Installer: Douglas Richardson (4L84QT8KA9)" \
    --root "$DSTROOT" \
    "$INSTALLER" || exit 1


echo Successfully built TRIMCheck
open "$INSTALLER_PATH"

exit 0

Difference between checkout and export in SVN

Additional musings. You said insmod crashes. Insmod loads modules. The modules are built in another compile operation from building the kernel. Kernel and modules have to be built from the same headers and so forth. Are all the modules built during the kernel build, or are they "existing"?

The other idea, and something I know little about, is svn externals, which (if used) can affect what is checked out to your project. Look and see if this is any different when exporting.

Pass a simple string from controller to a view MVC3

@Steve Hobbs' answer is probably the best, but some of your other solutions could have worked. For example, @Html.Label(ViewBag.CurrentPath); will probably work with an explicit cast, like @Html.Label((string)ViewBag.CurrentPath);. Also, your reference to currentPath in @Html.Label(ViewData["CurrentPath"].ToString()); is capitalized, wherein your other code it is not, which is probably why you were getting null reference exceptions.

XPath selecting a node with some attribute value equals to some other node's attribute value

I think this is what you want:

/grand/parent/child[@id="#grand"]

How to run sql script using SQL Server Management Studio?

This website has a concise tutorial on how to use SQL Server Management Studio. As you will see you can open a "Query Window", paste your script and run it. It does not allow you to execute scripts by using the file path. However, you can do this easily by using the command line (cmd.exe):

sqlcmd -S .\SQLExpress -i SqlScript.sql

Where SqlScript.sql is the script file name located at the current directory. See this Microsoft page for more examples

Add data dynamically to an Array

You should use method array_push to add value or array to array exists

$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);

/** GENERATED OUTPUT
Array
(
    [0] => orange
    [1] => banana
    [2] => apple
    [3] => raspberry
)
*/

How do I get the number of elements in a list?

And for completeness (primarily educational), it is possible without using the len() function. I would not condone this as a good option DO NOT PROGRAM LIKE THIS IN PYTHON, but it serves a purpose for learning algorithms.

def count(list):
    item_count = 0
    for item in list[:]:
        item_count += 1
    return item_count

count([1,2,3,4,5])

(The colon in list[:] is implicit and is therefore also optional.)

The lesson here for new programmers is: You can’t get the number of items in a list without counting them at some point. The question becomes: when is a good time to count them? For example, high-performance code like the connect system call for sockets (written in C) connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen);, does not calculate the length of elements (giving that responsibility to the calling code). Notice that the length of the address is passed along to save the step of counting the length first? Another option: computationally, it might make sense to keep track of the number of items as you add them within the object that you pass. Mind that this takes up more space in memory. See Naftuli Kay‘s answer.

Example of keeping track of the length to improve performance while taking up more space in memory. Note that I never use the len() function because the length is tracked:

class MyList(object):
    def __init__(self):
        self._data = []
        self.length = 0 # length tracker that takes up memory but makes length op O(1) time


        # the implicit iterator in a list class
    def __iter__(self):
        for elem in self._data:
            yield elem

    def add(self, elem):
        self._data.append(elem)
        self.length += 1

    def remove(self, elem):
        self._data.remove(elem)
        self.length -= 1

mylist = MyList()
mylist.add(1)
mylist.add(2)
mylist.add(3)
print(mylist.length) # 3
mylist.remove(3)
print(mylist.length) # 2

npx command not found

check versions of node, npm, npx as given below. if npx is not installed then use npm i -g npx

node -v
npm -v
npx -v

How can I quickly sum all numbers in a file?

Perl 6

say sum lines
~$ perl6 -e '.say for 0..1000000' > test.in

~$ perl6 -e 'say sum lines' < test.in
500000500000

How to update record using Entity Framework 6?

Try It....

UpdateModel(book);

var book = new Model.Book
{
    BookNumber =  _book.BookNumber,
    BookName = _book.BookName,
    BookTitle = _book.BookTitle,
};
using (var db = new MyContextDB())
{
    var result = db.Books.SingleOrDefault(b => b.BookNumber == bookNumber);
    if (result != null)
    {
        try
        {
            UpdateModel(book);
            db.Books.Attach(book);
            db.Entry(book).State = EntityState.Modified;
            db.SaveChanges();
        }
        catch (Exception ex)
        {
            throw;
        }
    }
}

c# Image resizing to different size while preserving aspect ratio

I'm going to add my code here too. This code will allow you resize an image with or without the aspect ratio being enforced or to resize with padding. This is a modified version of egrunin's code.

using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;

namespace ConsoleApplication1
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var path = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
            ResizeImage(path, "large.jpg", path, "new.jpg", 100, 100, true, true);
        }

        /// <summary>Resizes an image to a new width and height.</summary>
        /// <param name="originalPath">The folder which holds the original image.</param>
        /// <param name="originalFileName">The file name of the original image.</param>
        /// <param name="newPath">The folder which will hold the resized image.</param>
        /// <param name="newFileName">The file name of the resized image.</param>
        /// <param name="maximumWidth">When resizing the image, this is the maximum width to resize the image to.</param>
        /// <param name="maximumHeight">When resizing the image, this is the maximum height to resize the image to.</param>
        /// <param name="enforceRatio">Indicates whether to keep the width/height ratio aspect or not. If set to false, images with an unequal width and height will be distorted and padding is disregarded. If set to true, the width/height ratio aspect is maintained and distortion does not occur.</param>
        /// <param name="addPadding">Indicates whether fill the smaller dimension of the image with a white background. If set to true, the white padding fills the smaller dimension until it reach the specified max width or height. This is used for maintaining a 1:1 ratio if the max width and height are the same.</param>
        private static void ResizeImage(string originalPath, string originalFileName, string newPath, string newFileName, int maximumWidth, int maximumHeight, bool enforceRatio, bool addPadding)
        {
            var image = Image.FromFile(originalPath + "\\" + originalFileName);
            var imageEncoders = ImageCodecInfo.GetImageEncoders();
            EncoderParameters encoderParameters = new EncoderParameters(1);
            encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
            var canvasWidth = maximumWidth;
            var canvasHeight = maximumHeight;
            var newImageWidth = maximumWidth;
            var newImageHeight = maximumHeight;
            var xPosition = 0;
            var yPosition = 0;


            if (enforceRatio)
            {
                var ratioX = maximumWidth / (double)image.Width;
                var ratioY = maximumHeight / (double)image.Height;
                var ratio = ratioX < ratioY ? ratioX : ratioY;
                newImageHeight = (int)(image.Height * ratio);
                newImageWidth = (int)(image.Width * ratio);

                if (addPadding)
                {
                    xPosition = (int)((maximumWidth - (image.Width * ratio)) / 2);
                    yPosition = (int)((maximumHeight - (image.Height * ratio)) / 2);
                }
                else
                {
                    canvasWidth = newImageWidth;
                    canvasHeight = newImageHeight;                  
                }
            }

            var thumbnail = new Bitmap(canvasWidth, canvasHeight);
            var graphic = Graphics.FromImage(thumbnail);

            if (enforceRatio && addPadding)
            {
                graphic.Clear(Color.White);
            }

            graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
            graphic.SmoothingMode = SmoothingMode.HighQuality;
            graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
            graphic.CompositingQuality = CompositingQuality.HighQuality;
            graphic.DrawImage(image, xPosition, yPosition, newImageWidth, newImageHeight);

            thumbnail.Save(newPath + "\\" + newFileName, imageEncoders[1], encoderParameters);
        }
    }
}

Assigning variables with dynamic names in Java

Dynamic Variable Names in Java
There is no such thing.

In your case you can use array:

int[] n = new int[3];
for() {
 n[i] = 5;
}

For more general (name, value) pairs, use Map<>

How to get the file ID so I can perform a download of a file from Google Drive API on Android?

Well the first option I could think of is that you could send a list request with search parameters for your file, like title="File_1.xml" and fileExtension="xml". It will either return an empty list of files (there isn't one matching the serach criteria), or return a list with at least one file. If it's only one - it's easy. But if there are more - you'll have to select one of them based on some other fields. Remember that in gdrive you could have more than 1 file with the same name. So the more search parameters you provide, the better.

How do I rename a column in a database table using SQL?

Specifically for SQL Server, use sp_rename

USE AdventureWorks;
GO
EXEC sp_rename 'Sales.SalesTerritory.TerritoryID', 'TerrID', 'COLUMN';
GO

How to subscribe to an event on a service in Angular2?

Update: I have found a better/proper way to solve this problem using a BehaviorSubject or an Observable rather than an EventEmitter. Please see this answer: https://stackoverflow.com/a/35568924/215945

Also, the Angular docs now have a cookbook example that uses a Subject.


Original/outdated/wrong answer: again, don't use an EventEmitter in a service. That is an anti-pattern.

Using beta.1... NavService contains the EventEmiter. Component Navigation emits events via the service, and component ObservingComponent subscribes to the events.

nav.service.ts

import {EventEmitter} from 'angular2/core';
export class NavService {
  navchange: EventEmitter<number> = new EventEmitter();
  constructor() {}
  emitNavChangeEvent(number) {
    this.navchange.emit(number);
  }
  getNavChangeEmitter() {
    return this.navchange;
  }
}

components.ts

import {Component} from 'angular2/core';
import {NavService} from '../services/NavService';

@Component({
  selector: 'obs-comp',
  template: `obs component, item: {{item}}`
})
export class ObservingComponent {
  item: number = 0;
  subscription: any;
  constructor(private navService:NavService) {}
  ngOnInit() {
    this.subscription = this.navService.getNavChangeEmitter()
      .subscribe(item => this.selectedNavItem(item));
  }
  selectedNavItem(item: number) {
    this.item = item;
  }
  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

@Component({
  selector: 'my-nav',
  template:`
    <div class="nav-item" (click)="selectedNavItem(1)">nav 1 (click me)</div>
    <div class="nav-item" (click)="selectedNavItem(2)">nav 2 (click me)</div>
  `,
})
export class Navigation {
  item = 1;
  constructor(private navService:NavService) {}
  selectedNavItem(item: number) {
    console.log('selected nav item ' + item);
    this.navService.emitNavChangeEvent(item);
  }
}

Plunker

how to concatenate two dictionaries to create a new one in Python?

  1. Slowest and doesn't work in Python3: concatenate the items and call dict on the resulting list:

    $ python -mtimeit -s'd1={1:2,3:4}; d2={5:6,7:9}; d3={10:8,13:22}' \
    'd4 = dict(d1.items() + d2.items() + d3.items())'
    
    100000 loops, best of 3: 4.93 usec per loop
    
  2. Fastest: exploit the dict constructor to the hilt, then one update:

    $ python -mtimeit -s'd1={1:2,3:4}; d2={5:6,7:9}; d3={10:8,13:22}' \
    'd4 = dict(d1, **d2); d4.update(d3)'
    
    1000000 loops, best of 3: 1.88 usec per loop
    
  3. Middling: a loop of update calls on an initially-empty dict:

    $ python -mtimeit -s'd1={1:2,3:4}; d2={5:6,7:9}; d3={10:8,13:22}' \
    'd4 = {}' 'for d in (d1, d2, d3): d4.update(d)'
    
    100000 loops, best of 3: 2.67 usec per loop
    
  4. Or, equivalently, one copy-ctor and two updates:

    $ python -mtimeit -s'd1={1:2,3:4}; d2={5:6,7:9}; d3={10:8,13:22}' \
    'd4 = dict(d1)' 'for d in (d2, d3): d4.update(d)'
    
    100000 loops, best of 3: 2.65 usec per loop
    

I recommend approach (2), and I particularly recommend avoiding (1) (which also takes up O(N) extra auxiliary memory for the concatenated list of items temporary data structure).

show and hide divs based on radio button click

The hide selector was incorrect. I hid the blocks at page load and showed the selected value. I also changed the car div id's to make it easier to append the radio button value and create the proper id selector.

<div id="myRadioGroup">
  2 Cars<input type="radio" name="cars" checked="checked" value="2"  />
  3 Cars<input type="radio" name="cars" value="3" />
  <div id="car-2">
  2 Cars
  </div>
  <div id="car-3">
  3 Cars
  </div>
</div>

<script type="text/javascript">
$(document).ready(function(){ 
  $("div div").hide();
  $("#car-2").show();
  $("input[name$='cars']").click(function() {
      var test = $(this).val();
      $("div div").hide();
      $("#car-"+test).show();
  }); 
});
</script>

How do I change the default index page in Apache?

You can also set DirectoryIndex in apache's httpd.conf file.

CentOS keeps this file in /etc/httpd/conf/httpd.conf Debian: /etc/apache2/apache2.conf

Open the file in your text editor and find the line starting with DirectoryIndex

To load landing.html as a default (but index.html if that's not found) change this line to read:

DirectoryIndex  landing.html index.html

Could not open a connection to your authentication agent

Use parameter -A when you connect to server, example:

ssh -A root@myhost

from man page :

-A Enables forwarding of the authentication agent connection.  
   This can also be specified on a per-host basis in a configuration file.

   Agent forwarding should be enabled with caution.  Users with the ability to bypass file permissions on the remote host (for the agent's
   UNIX-domain socket) can access the local agent through the forwarded 
   connection.  An attacker cannot obtain key material from the agent,
   however they can perform operations on the keys that enable them to
   authenticate using the identities loaded into the agent.

Android - Start service on boot

Following should work. I have verified. May be your problem is somewhere else.

Receiver:

public class MyReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        if (Intent.ACTION_BOOT_COMPLETED.equals(arg1.getAction())) {
            Log.d("TAG", "MyReceiver");
            Intent serviceIntent = new Intent(context, Test1Service.class);
            context.startService(serviceIntent);
        }
    }
}

Service:

public class Test1Service extends Service {
    /** Called when the activity is first created. */
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("TAG", "Service created.");
    }
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("TAG", "Service started.");
        return super.onStartCommand(intent, flags, startId);
    }
    
    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        Log.d("TAG", "Service started.");
    }
    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
}

Manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.test"
      android:versionCode="1"
      android:versionName="1.0"
      android:installLocation="internalOnly">
    <uses-sdk android:minSdkVersion="8" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
    
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.BATTERY_STATS" 
    />
<!--        <activity android:name=".MyActivity">
            <intent-filter>  
                <action android:name="android.intent.action.MAIN" /> 
                <category android:name="android.intent.category.LAUNCHER"></category> 
            </intent-filter>
       </activity> -->
        <service android:name=".Test1Service" 
                  android:label="@string/app_name"
                  >
        </service>
        <receiver android:name=".MyReceiver">  
            <intent-filter>  
                <action android:name="android.intent.action.BOOT_COMPLETED" /> 
            </intent-filter>  
        </receiver> 
    </application>
</manifest>

How to recover MySQL database from .myd, .myi, .frm files

I think .myi you can repair from inside mysql.

If you see these type of error messages from MySQL: Database failed to execute query (query) 1016: Can't open file: 'sometable.MYI'. (errno: 145) Error Msg: 1034: Incorrect key file for table: 'sometable'. Try to repair it thenb you probably have a crashed or corrupt table.

You can check and repair the table from a mysql prompt like this:

check table sometable;
+------------------+-------+----------+----------------------------+
| Table | Op | Msg_type | Msg_text | 
+------------------+-------+----------+----------------------------+ 
| yourdb.sometable | check | warning | Table is marked as crashed | 
| yourdb.sometable | check | status | OK | 
+------------------+-------+----------+----------------------------+ 

repair table sometable;
+------------------+--------+----------+----------+ 
| Table | Op | Msg_type | Msg_text | 
+------------------+--------+----------+----------+ 
| yourdb.sometable | repair | status | OK | 
+------------------+--------+----------+----------+

and now your table should be fine:

check table sometable;
+------------------+-------+----------+----------+ 
| Table | Op | Msg_type | Msg_text |
+------------------+-------+----------+----------+ 
| yourdb.sometable | check | status | OK |
+------------------+-------+----------+----------+

How to add line break for UILabel?

NSCharacterSet *charSet = NSCharacterSet.newlineCharacterSet;
NSString *formatted = [[unformatted componentsSeparatedByCharactersInSet:charSet] componentsJoinedByString:@"\n"];

How to make a text box have rounded corners?

You could use CSS to do that, but it wouldn't be supported in IE8-. You can use some site like http://borderradius.com to come up with actual CSS you'd use, which would look something like this (again, depending on how many browsers you're trying to support):

-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;

Regex to match only uppercase "words" with some exceptions

I'm not a regex guru by any means. But try:

<[A-Z0-9][A-Z0-9]+>

<           start of word
[A-Z0-9]    one character
[A-Z0-9]+   and one or more of them
>           end of word

I won't try for the bonus points of the whole upper case sentence. hehe

SQL SELECT multi-columns INTO multi-variable

SELECT @var = col1,
       @var2 = col2
FROM   Table

Here is some interesting information about SET / SELECT

  • SET is the ANSI standard for variable assignment, SELECT is not.
  • SET can only assign one variable at a time, SELECT can make multiple assignments at once.
  • If assigning from a query, SET can only assign a scalar value. If the query returns multiple values/rows then SET will raise an error. SELECT will assign one of the values to the variable and hide the fact that multiple values were returned (so you'd likely never know why something was going wrong elsewhere - have fun troubleshooting that one)
  • When assigning from a query if there is no value returned then SET will assign NULL, where SELECT will not make the assignment at all (so the variable will not be changed from it's previous value)
  • As far as speed differences - there are no direct differences between SET and SELECT. However SELECT's ability to make multiple assignments in one shot does give it a slight speed advantage over SET.

How to install Android app on LG smart TV?

LG, VIZIO, SAMSUNG and PANASONIC TVs are not android based, and you cannot run APKs off of them... You should just buy a fire stick and call it a day. The only TVs that are android-based, and you can install APKs are: SONY, PHILIPS and SHARP.
#FACTS.

How to create a inner border for a box in html?

  1. Use dashed border style for outline.
  2. Draw background-color with :before or :after pseudo element.

Note: This method will allow you to have maximum browser support.

Output Image:

Output Image

_x000D_
_x000D_
* {box-sizing: border-box;}_x000D_
_x000D_
.box {_x000D_
  border: 1px dashed #fff;_x000D_
  position: relative;_x000D_
  height: 160px;_x000D_
  width: 350px;_x000D_
  margin: 20px;_x000D_
}_x000D_
_x000D_
.box:before {_x000D_
  position: absolute;_x000D_
  background: black;_x000D_
  content: '';_x000D_
  bottom: -10px;_x000D_
  right: -10px;_x000D_
  left: -10px;_x000D_
  top: -10px;_x000D_
  z-index: -1;_x000D_
}
_x000D_
<div class="box">_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I escape ampersands in batch files?

The command

echo this ^& that

works as expected, outputing

this & that

The command

echo this ^& that > tmp

also works, writing the string to file "tmp". However, before a pipe

echo this ^& that | clip

the ^ is interpreted completely differently. It tries to write the output of the two commands "echo this" and "that" to the pipe. The echo will work then "that" will give an error. Saying

echo this ^& echo that | clip

will put the strings "this" and "that" on the clipboard.

Without the ^:

echo this & echo that | clip

the first echo will write to the console and only the second echo's output will be piped to clip (similarly for "> tmp" redirection). So, when output is being redirected, the ^ does not quote the & but instead causes it to be applied before the redirection rather than after.

To pipe an &, you have to quote it twice

echo this ^^^& that | clip

If you put the string in a variable

set m=this ^& that

then

set m

will output

m=this & that

but the obvious

echo %m%

fails because, after Windows substitutes the variable, resulting in

echo this & that

it parses this as a new command and tries to execute "that".

In a batch file, you can use delayed expansion:

setlocal enableDelayedExpansion
echo !m!

To output to a pipe, we have to replace all &s in the variable value with ^&, which we can do with the %VAR:FROM=TO% syntax:

echo !m:^&=^^^&! | clip

On the command line, "cmd /v" enables delayed expansion:

cmd /v /c echo !m!

This works even when writing to a pipe

cmd /v /c echo !m! | clip

Simple.

Fastest method to replace all instances of a character in a string

The easiest would be to use a regular expression with g flag to replace all instances:

str.replace(/foo/g, "bar")

This will replace all occurrences of foo with bar in the string str. If you just have a string, you can convert it to a RegExp object like this:

var pattern = "foobar",
    re = new RegExp(pattern, "g");

How to make a deep copy of Java ArrayList

public class Person{

    String s;
    Date d;
    ...

    public Person clone(){
        Person p = new Person();
        p.s = this.s.clone();
        p.d = this.d.clone();
        ...
        return p;
    }
}

In your executing code:

ArrayList<Person> clone = new ArrayList<Person>();
for(Person p : originalList)
    clone.add(p.clone());

How can I convert an Integer to localized month name in Java?

import java.text.DateFormatSymbols;
public String getMonth(int month) {
    return new DateFormatSymbols().getMonths()[month-1];
}

Best Regular Expression for Email Validation in C#

Updated answer for 2019.

Regex object is thread-safe for Matching functions. Knowing that and there are some performance options or cultural / language issues, I propose this simple solution.

public static Regex _regex = new Regex(
    @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",
    RegexOptions.CultureInvariant | RegexOptions.Singleline);

public static bool IsValidEmailFormat(string emailInput)
{
    return _regex.IsMatch(emailInput);
}

Alternative Configuration for Regex:

public static Regex _regex = new Regex(
    @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",
    RegexOptions.CultureInvariant | RegexOptions.Compiled);

I find that compiled is only faster on big string matches, like book parsing for example. Simple email matching is faster just letting Regex interpret.

Thread Safety And Regex
Regex Best Practices

Do we need to execute Commit statement after Update in SQL Server

The SQL Server Management Studio has implicit commit turned on, so all statements that are executed are implicitly commited.

This might be a scary thing if you come from an Oracle background where the default is to not have commands commited automatically, but it's not that much of a problem.

If you still want to use ad-hoc transactions, you can always execute

BEGIN TRANSACTION

within SSMS, and than the system waits for you to commit the data.

If you want to replicate the Oracle behaviour, and start an implicit transaction, whenever some DML/DDL is issued, you can set the SET IMPLICIT_TRANSACTIONS checkbox in

Tools -> Options -> Query Execution -> SQL Server -> ANSI

Plotting in a non-blocking way with Matplotlib

I figured out that the plt.pause(0.001) command is the only thing needed and nothing else.

plt.show() and plt.draw() are unnecessary and / or blocking in one way or the other. So here is a code that draws and updates a figure and keeps going. Essentially plt.pause(0.001) seems to be the closest equivalent to matlab's drawnow.

Unfortunately those plots will not be interactive (they freeze), except you insert an input() command, but then the code will stop.

The documentation of the plt.pause(interval) command states:

If there is an active figure, it will be updated and displayed before the pause...... This can be used for crude animation.

and this is pretty much exactly what we want. Try this code:

import numpy as np
from matplotlib import pyplot as plt

x = np.arange(0, 51)               # x coordinates  
         
for z in range(10, 50):

    y = np.power(x, z/10)          # y coordinates of plot for animation

    plt.cla()                      # delete previous plot
    plt.axis([-50, 50, 0, 10000])  # set axis limits, to avoid rescaling
    plt.plot(x, y)                 # generate new plot
    plt.pause(0.1)                 # pause 0.1 sec, to force a plot redraw

Undefined reference to vtable

So I was using Qt with Windows XP and MinGW compiler and this thing was driving me crazy.

Basically the moc_xxx.cpp was generated empty even when I was added

Q_OBJECT

Deleting everything making functions virtual, explicit and whatever you guess doesn't worked. Finally I started removing line by line and it turned out that I had

#ifdef something

Around the file. Even when the #ifdef was true moc file was not generated.

So removing all #ifdefs fixed the problem.

This thing was not happening with Windows and VS 2013.

How to set the height and the width of a textfield in Java?

package myguo;
import javax.swing.*;

public class MyGuo {

    JFrame f;
    JButton bt1 , bt2 ;
    JTextField t1,t2;
    JLabel l1,l2;

    MyGuo(){

        f=new JFrame("LOG IN FORM");
        f.setLocation(500,300);
        f.setSize(600,500);
        f.setLayout(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        l1=new JLabel("NAME");
        l1.setBounds(50,70,80,30);

        l2=new JLabel("PASSWORD");
        l2.setBounds(50,100,80,30);

        t1=new JTextField();
        t1.setBounds(140, 70, 200,30);

         t2=new JTextField();
        t2.setBounds(140, 110, 200,30);

        bt1 =new JButton("LOG IN");
        bt1.setBounds(150,150,80,30);

        bt2 =new JButton("CLEAR");
        bt2.setBounds(235,150,80,30);

         f.add(l1);
        f.add(l2);
         f.add(t1);
         f.add(t2);
         f.add(bt1);
         f.add(bt2);

    f.setVisible(true);

    }
    public static void main(String[] args) {
        MyGuo myGuo = new MyGuo();
}
}

Converting an int or String to a char array on Arduino

You can convert it to char* if you don't need a modifiable string by using:

(char*) yourString.c_str();

This would be very useful when you want to publish a String variable via MQTT in arduino.

Exit a while loop in VBS/VBA

Incredibly old question, but bearing in mind that the OP said he does not want to use Do While and that none of the other solutions really work... Here's something that does exactly the same as a Exit Loop:

This never runs anything if the status is already at "Fail"...

While (i < 20 And Not bShouldStop)
    If (Status = "Fail") Then
        bShouldStop = True
    Else
        i = i + 1
        '
        ' Do Something
        '
    End If  
Wend

Whereas this one always processes something first (and increment the loop variable) before deciding whether it should loop once more or not.

While (i < 20 And Not bShouldStop)
    i = i + 1
    '
    ' Do Something
    '

    If (Status = "Fail") Then
        bShouldStop = True
    End If  
Wend

Ultimately, if the variable Status is being modified inside the While (and assuming you don't need i outside the while, it makes no difference really, but just wanted to present multiple options...

Linq to SQL how to do "where [column] in (list of values)"

You could also use:

List<int> codes = new List<int>();

codes.add(1);
codes.add(2);

var foo = from codeData in channel.AsQueryable<CodeData>()
          where codes.Any(code => codeData.CodeID.Equals(code))
          select codeData;

Android Camera Preview Stretched

@Hesam 's answer is correct, CameraPreview will work in all portrait devices, but if the device is in landscape mode or in multi-window mode, this code is working perfect, just replace onMeasure()

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec);
    int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec);
    setMeasuredDimension(width, height);

    int rotation = ((Activity) mContext).getWindowManager().getDefaultDisplay().getRotation();
    if ((Surface.ROTATION_0 == rotation || Surface.ROTATION_180 == rotation)) {//portrait
        mPreviewSize = getOptimalPreviewSize(mSupportedPreviewSizes, height, width);
    } else
        mPreviewSize = getOptimalPreviewSize(mSupportedPreviewSizes, width, height);//landscape

    if (mPreviewSize == null) return;
    float ratio;
    if (mPreviewSize.height >= mPreviewSize.width) {
        ratio = (float) mPreviewSize.height / (float) mPreviewSize.width;
    } else ratio = (float) mPreviewSize.width / (float) mPreviewSize.height;


    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && ((Activity) mContext).isInMultiWindowMode()) {
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT ||
                !(Surface.ROTATION_0 == rotation || Surface.ROTATION_180 == rotation)) {
            setMeasuredDimension(width, (int) (width / ratio));
        } else {
            setMeasuredDimension((int) (height / ratio), height);
        }
    } else {
        if ((Surface.ROTATION_0 == rotation || Surface.ROTATION_180 == rotation)) {
            Log.e("---", "onMeasure: " + height + " - " + width * ratio);
            //2264 - 2400.0 pix c -- yes
            //2240 - 2560.0 samsung -- yes
            //1582 - 1440.0 pix 2 -- no
            //1864 - 2048.0 sam tab -- yes
            //848 - 789.4737 iball -- no
            //1640 - 1600.0 nexus 7 -- no
            //1093 - 1066.6667 lenovo -- no
            //if width * ratio is > height, need to minus toolbar height
           if ((width * ratio) < height)
                setMeasuredDimension(width, (int) (width * ratio));
            else
                setMeasuredDimension(width, (int) (width * ratio) - toolbarHeight);
        } else {
            setMeasuredDimension((int) (height * ratio), height);
        }
    }
    requestLayout();
}

Read Excel sheet in Powershell

This was extremely helpful for me when trying to automate Cisco SIP phone configuration using an Excel spreadsheet as the source. My only issue was when I tried to make an array and populate it using $array | Add-Member ... as I needed to use it later on to generate the config file. Just defining an array and making it the for loop allowed it to store correctly.

$lastCell = 11 
$startRow, $model, $mac, $nOF, $ext = 1, 1, 5, 6, 7

$excel = New-Object -ComObject excel.application
$wb = $excel.workbooks.open("H:\Strike Network\Phones\phones.xlsx")
$sh = $wb.Sheets.Item(1)
$endRow = $sh.UsedRange.SpecialCells($lastCell).Row

$phoneData = for ($i=1; $i -le $endRow; $i++)
            {
                $pModel = $sh.Cells.Item($startRow,$model).Value2
                $pMAC = $sh.Cells.Item($startRow,$mac).Value2
                $nameOnPhone = $sh.Cells.Item($startRow,$nOF).Value2
                $extension = $sh.Cells.Item($startRow,$ext).Value2
                New-Object PSObject -Property @{ Model = $pModel; MAC = $pMAC; NameOnPhone = $nameOnPhone; Extension = $extension }
                $startRow++
            }

I used to have no issues adding information to an array with Add-Member but that was back in PSv2/3, and I've been away from it a while. Though the simple solution saved me manually configuring 100+ phones and extensions - which nobody wants to do.

'Use of Unresolved Identifier' in Swift

I got this error for Mantle Framework in my Objective-Swift Project. What i tried is ,

  1. Check if import is there in Bridging-Header.h file
  2. Change the Target Membership for Framework in Mantle.h file as shown in below screenshot.

Toggle between Private Membership first build the project , end up with errors. Then build the project with Public Membership for all the frameworks appeared for Mantle.h file, you must get success.

It is just a bug of building with multiple framework in Objective-C Swift project.

enter image description here

Remove spaces from a string in VB.NET

This will remove spaces only, matches the SQL functionality of rtrim(ltrim(myString))

Dim charstotrim() As Char = {" "c}
myString = myString .Trim(charstotrim) 

How to convert a time string to seconds?

To get the timedelta(), you should subtract 1900-01-01:

>>> from datetime import datetime
>>> datetime.strptime('01:01:09,000', '%H:%M:%S,%f')
datetime.datetime(1900, 1, 1, 1, 1, 9)
>>> td = datetime.strptime('01:01:09,000', '%H:%M:%S,%f') - datetime(1900,1,1)
>>> td
datetime.timedelta(0, 3669)
>>> td.total_seconds() # 2.7+
3669.0

%H above implies the input is less than a day, to support the time difference more than a day:

>>> import re
>>> from datetime import timedelta
>>> td = timedelta(**dict(zip("hours minutes seconds milliseconds".split(),
...                           map(int, re.findall('\d+', '31:01:09,000')))))
>>> td
datetime.timedelta(1, 25269)
>>> td.total_seconds()
111669.0

To emulate .total_seconds() on Python 2.6:

>>> from __future__ import division
>>> ((td.days * 86400 + td.seconds) * 10**6 + td.microseconds) / 10**6
111669.0

Response Content type as CSV

Try one of these other mime-types (from here: http://filext.com/file-extension/CSV )

  • text/comma-separated-values
  • text/csv
  • application/csv
  • application/excel
  • application/vnd.ms-excel
  • application/vnd.msexcel

Also, the mime-type might be case sensitive...

Move the most recent commit(s) to a new branch with Git

You can do this is just 3 simple step that i used.

1) make new branch where you want to commit you recent update.

git branch <branch name>

2) Find Recent Commit Id for commit on new branch.

git log

3) Copy that commit id note that Most Recent commit list take place on top. so you can find your commit. you also find this via message.

git cherry-pick d34bcef232f6c...

you can also provide some rang of commit id.

git cherry-pick d34bcef...86d2aec

Now your job done. If you picked correct id and correct branch then you will success. So before do this be careful. else another problem can occur.

Now you can push your code

git push

Could not find a version that satisfies the requirement tensorflow

Uninstalling Python and then reinstalling solved my issue and I was able to successfully install TensorFlow.

How to use querySelectorAll only for elements that have a specific attribute set?

You can use querySelectorAll() like this:

var test = document.querySelectorAll('input[value][type="checkbox"]:not([value=""])');

This translates to:

get all inputs with the attribute "value" and has the attribute "value" that is not blank.

In this demo, it disables the checkbox with a non-blank value.

@Cacheable key on multiple method arguments

You can use Spring SimpleKey class

@Cacheable(value = "bookCache", key = "new org.springframework.cache.interceptor.SimpleKey(#isbn, #checkWarehouse)")

Simplest way to wait some asynchronous tasks complete, in Javascript?

The way to do it is to pass the tasks a callback that updates a shared counter. When the shared counter reaches zero you know that all tasks have finished so you can continue with your normal flow.

var ntasks_left_to_go = 4;

var callback = function(){
    ntasks_left_to_go -= 1;
    if(ntasks_left_to_go <= 0){
         console.log('All tasks have completed. Do your stuff');
    }
}

task1(callback);
task2(callback);
task3(callback);
task4(callback);

Of course, there are many ways to make this kind of code more generic or reusable and any of the many async programing libraries out there should have at least one function to do this kind of thing.

How to debug an apache virtual host configuration?

I recently had some issues with a VirtualHost. I used a2ensite to enable a host but before running a restart (which would kill the server on fail) I ran

apache2ctl -S

Which gives you some info about what's going on with your virtual hosts. It's not perfect, but it helps.

Android overlay a view ontop of everything?

You can use bringToFront:

    View view=findViewById(R.id.btnStartGame);
    view.bringToFront();

Docker-compose: node_modules not present in a volume after npm install succeeds

This happens because you have added your worker directory as a volume to your docker-compose.yml, as the volume is not mounted during the build.

When docker builds the image, the node_modules directory is created within the worker directory, and all the dependencies are installed there. Then on runtime the worker directory from outside docker is mounted into the docker instance (which does not have the installed node_modules), hiding the node_modules you just installed. You can verify this by removing the mounted volume from your docker-compose.yml.

A workaround is to use a data volume to store all the node_modules, as data volumes copy in the data from the built docker image before the worker directory is mounted. This can be done in the docker-compose.yml like this:

redis:
    image: redis
worker:
    build: ./worker
    command: npm start
    ports:
        - "9730:9730"
    volumes:
        - ./worker/:/worker/
        - /worker/node_modules
    links:
        - redis

I'm not entirely certain whether this imposes any issues for the portability of the image, but as it seems you are primarily using docker to provide a runtime environment, this should not be an issue.

If you want to read more about volumes, there is a nice user guide available here: https://docs.docker.com/userguide/dockervolumes/

EDIT: Docker has since changed it's syntax to require a leading ./ for mounting in files relative to the docker-compose.yml file.

Create an array of strings

Another option:

names = repmat({'Sample Text'}, 10, 1)

display: inline-block extra margin

Can you post a link to the HTML in question?

Ultimately you should be able to do:

div {
    margin:0;
    padding: 0;
}

to remove the spacing. Is this just in one particular browser or all of them?

How do I find the last column with data?

Lots of ways to do this. The most reliable is find.

Dim rLastCell As Range

Set rLastCell = ws.Cells.Find(What:="*", After:=ws.Cells(1, 1), LookIn:=xlFormulas, LookAt:= _
xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious, MatchCase:=False)

MsgBox ("The last used column is: " & rLastCell.Column)

If you want to find the last column used in a particular row you can use:

Dim lColumn As Long

lColumn = ws.Cells(1, Columns.Count).End(xlToLeft).Column

Using used range (less reliable):

Dim lColumn As Long

lColumn = ws.UsedRange.Columns.Count

Using used range wont work if you have no data in column A. See here for another issue with used range:

See Here regarding resetting used range.

What is an IIS application pool?

Assume scenario where swimmers swim in swimming pool in the areas reserved for them.what happens if swimmers swim other than the areas reserved for them,the whole thing would become mess.similarly iis uses application pools to seperate one process from another.

JavaScript: Create and save file

For latest browser, like Chrome, you can use the File API as in this tutorial:

window.requestFileSystem  = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(window.PERSISTENT, 5*1024*1024 /*5MB*/, saveFile, errorHandler);

How to configure Fiddler to listen to localhost?

Replace localhost with 127.0.0.1 If it doesn't work change the run configuration to support your ip address.

Properly close mongoose's connection once you're done

You can close the connection with

mongoose.connection.close()

C# Clear Session

The other big difference is Abandon does not remove items immediately, but when it does then cleanup it does a loop over session items to check for STA COM objects it needs to handle specially. And this can be a problem.

Under high load it's possible for two (or more) requests to make it to the server for the same session (that is two requests with the same session cookie). Their execution will be serialized, but since Abandon doesn't clear out the items synchronously but rather sets a flag it's possible for both requests to run, and both requests to schedule a work item to clear out session "later". Both these work items can then run at the same time, and both are checking the session objects, and both are clearing out the array of objects, and what happens when you have two things iterating over a list and changing it?? Boom! And since this happens in a queueuserworkitem callback and is NOT done in a try/catch (thanks MS), it will bring down your entire app domain. Been there.

C# - How to convert string to char?

Your question is a bit unclear, but I think you want (requires using System.Linq;):

var result = yourArrayOfStrings.SelectMany(s => s).ToArray();

Another solution is:

var result = string.Concat(yourArrayOfStrings).ToCharArray();

CSS Selector "(A or B) and C"?

If you have this:

<div class="a x">Foo</div>
<div class="b x">Bar</div>
<div class="c x">Baz</div>

And you only want to select the elements which have .x and (.a or .b), you could write:

.x:not(.c) { ... }

but that's convenient only when you have three "sub-classes" and you want to select two of them.

Selecting only one sub-class (for instance .a): .a.x

Selecting two sub-classes (for instance .a and .b): .x:not(.c)

Selecting all three sub-classes: .x

How can I create a blank/hardcoded column in a sql query?

For varchars, you may need to do something like this:

select convert(varchar(25), NULL) as abc_column into xyz_table

If you try

select '' as abc_column into xyz_table

you may get errors related to truncation, or an issue with null values, once you populate.

Short IF - ELSE statement

You can do it as simple as this, I did it in react hooks :

 (myNumber == 12) ? "true" : "false"

it was equal to this long if function below :

if (myNumber == 12) {
  "true"
} else {
  "false"
}

Hope it helps ^_^

How to add bootstrap in angular 6 project?

npm install --save bootstrap

afterwards, inside angular.json (previously .angular-cli.json) inside the project's root folder, find styles and add the bootstrap css file like this:

for angular 6

"styles": [
          "../node_modules/bootstrap/dist/css/bootstrap.min.css",
          "styles.css"
],

for angular 7

"styles": [
          "node_modules/bootstrap/dist/css/bootstrap.min.css",
          "src/styles.css"
],

How to give a pandas/matplotlib bar graph custom colors

For a more detailed answer on creating your own colormaps, I highly suggest visiting this page

If that answer is too much work, you can quickly make your own list of colors and pass them to the color parameter. All the colormaps are in the cm matplotlib module. Let's get a list of 30 RGB (plus alpha) color values from the reversed inferno colormap. To do so, first get the colormap and then pass it a sequence of values between 0 and 1. Here, we use np.linspace to create 30 equally-spaced values between .4 and .8 that represent that portion of the colormap.

from matplotlib import cm
color = cm.inferno_r(np.linspace(.4, .8, 30))
color

array([[ 0.865006,  0.316822,  0.226055,  1.      ],
       [ 0.851384,  0.30226 ,  0.239636,  1.      ],
       [ 0.832299,  0.283913,  0.257383,  1.      ],
       [ 0.817341,  0.270954,  0.27039 ,  1.      ],
       [ 0.796607,  0.254728,  0.287264,  1.      ],
       [ 0.775059,  0.239667,  0.303526,  1.      ],
       [ 0.758422,  0.229097,  0.315266,  1.      ],
       [ 0.735683,  0.215906,  0.330245,  1.      ],
       .....

Then we can use this to plot, using the data from the original post:

import random
x = [{i: random.randint(1, 5)} for i in range(30)]
df = pd.DataFrame(x)
df.plot(kind='bar', stacked=True, color=color, legend=False, figsize=(12, 4))

enter image description here

Redirecting Output from within Batch file

if you want both out and err streams redirected

dir >> a.txt 2>&1

How do I make a delay in Java?

If you want to pause then use java.util.concurrent.TimeUnit:

TimeUnit.SECONDS.sleep(1);

To sleep for one second or

TimeUnit.MINUTES.sleep(1);

To sleep for a minute.

As this is a loop, this presents an inherent problem - drift. Every time you run code and then sleep you will be drifting a little bit from running, say, every second. If this is an issue then don't use sleep.

Further, sleep isn't very flexible when it comes to control.

For running a task every second or at a one second delay I would strongly recommend a ScheduledExecutorService and either scheduleAtFixedRate or scheduleWithFixedDelay.

For example, to run the method myTask every second (Java 8):

public static void main(String[] args) {
    final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
    executorService.scheduleAtFixedRate(App::myTask, 0, 1, TimeUnit.SECONDS);
}

private static void myTask() {
    System.out.println("Running");
}

And in Java 7:

public static void main(String[] args) {
    final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
    executorService.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            myTask();
        }
    }, 0, 1, TimeUnit.SECONDS);
}

private static void myTask() {
    System.out.println("Running");
}

Add custom header in HttpWebRequest

You use the Headers property with a string index:

request.Headers["X-My-Custom-Header"] = "the-value";

According to MSDN, this has been available since:

  • Universal Windows Platform 4.5
  • .NET Framework 1.1
  • Portable Class Library
  • Silverlight 2.0
  • Windows Phone Silverlight 7.0
  • Windows Phone 8.1

https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.headers(v=vs.110).aspx

How do I make a https post in Node Js without any third party module?

For example, like this:

const querystring = require('querystring');
const https = require('https');

var postData = querystring.stringify({
    'msg' : 'Hello World!'
});

var options = {
  hostname: 'posttestserver.com',
  port: 443,
  path: '/post.php',
  method: 'POST',
  headers: {
       'Content-Type': 'application/x-www-form-urlencoded',
       'Content-Length': postData.length
     }
};

var req = https.request(options, (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

  res.on('data', (d) => {
    process.stdout.write(d);
  });
});

req.on('error', (e) => {
  console.error(e);
});

req.write(postData);
req.end();

WPF ListView turn off selection

Okay, little late to the game, but none of these solutions quite did what I was trying to do. These solutions have a couple problems

  1. Disable the ListViewItem, which screws up the styles and disables all the children controls
  2. Remove from the hit-test stack, i.e. children controls never get a mouse-over or click
  3. Make it not focusable, this just plain didn't work for me?

I wanted a ListView with the grouping headers, and each ListViewItem should just be 'informational' without selection or hover over, but the ListViewItem has a button in it that I want to be click-able and have hover-over.

So, really what I want is the ListViewItem to not be a ListViewItem at all, So, I over rode the ListViewItem's ControlTemplate and just made it a simple ContentControl.

<ListView.ItemContainerStyle>
    <Style TargetType="ListViewItem">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate>
                    <ContentControl Content="{Binding Content, RelativeSource={RelativeSource TemplatedParent}}"/>
                </ControlTemplate>
            </Setter.Value>
         </Setter>
     </Style>
</ListView.ItemContainerStyle>

What is CDATA in HTML?

From http://en.wikipedia.org/wiki/CDATA:

Since it is useful to be able to use less-than signs (<) and ampersands (&) in web page scripts, and to a lesser extent styles, without having to remember to escape them, it is common to use CDATA markers around the text of inline and elements in XHTML documents. But so that the document can also be parsed by HTML parsers, which do not recognise the CDATA markers, the CDATA markers are usually commented-out, as in this JavaScript example:

<script type="text/javascript">
//<![CDATA[
document.write("<");
//]]>
</script>

Read/write to file using jQuery

Yes it is possible.

The technique is described below

http://jquery.tiddlywiki.org/twFile.html

Allow anything through CORS Policy

Try configuration at /config/application.rb:

config.middleware.insert_before 0, "Rack::Cors" do
  allow do
    origins '*'
    resource '*', :headers => :any, :methods => [:get, :post, :options, :delete, :put, :patch], credentials: true
  end
end

Using JQuery to open a popup window and print

You should put the print function in your view-details.php file and call it once the file is loaded, by either using

<body onload="window.print()"> 

or

$(document).ready(function () { 
  window.print(); 
});

Error message: "'chromedriver' executable needs to be available in the path"

Could try to restart computer if it doesn't work after you are quite sure that PATH is set correctly.

In my case on windows 7, I always got the error on WebDriverException: Message: for chromedriver, gecodriver, IEDriverServer. I am pretty sure that i have correct path. Restart computer, all work

What ports does RabbitMQ use?

What ports is RabbitMQ using?

Default: 5672, the manual has the answer. It's defined in the RABBITMQ_NODE_PORT variable.

https://www.rabbitmq.com/configure.html#define-environment-variables

The number might be differently if changed by someone in the rabbitmq configuration file:

vi /etc/rabbitmq/rabbitmq-env.conf

Ask the computer to tell you:

sudo nmap -p 1-65535 localhost

Starting Nmap 5.51 ( http://nmap.org ) at 2014-09-19 13:50 EDT
Nmap scan report for localhost (127.0.0.1)
Host is up (0.00041s latency).
PORT      STATE         SERVICE
443/tcp   open          https
5672/tcp  open          amqp
15672/tcp open  unknown
35102/tcp open  unknown
59440/tcp open  unknown

Oh look, 5672, and 15672

Use netstat:

netstat -lntu
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address               Foreign Address             State
tcp        0      0 0.0.0.0:15672               0.0.0.0:*                   LISTEN
tcp        0      0 0.0.0.0:55672               0.0.0.0:*                   LISTEN
tcp        0      0 :::5672                     :::*                        LISTEN

Oh look 5672.

use lsof:

eric@dev ~$ sudo lsof -i | grep beam
beam.smp  21216    rabbitmq   17u  IPv4 33148214      0t0  TCP *:55672 (LISTEN)
beam.smp  21216    rabbitmq   18u  IPv4 33148219      0t0  TCP *:15672 (LISTEN)

use nmap from a different machine, find out if 5672 is open:

sudo nmap -p 5672 10.0.1.71
Starting Nmap 5.51 ( http://nmap.org ) at 2014-09-19 13:19 EDT
Nmap scan report for 10.0.1.71
Host is up (0.00011s latency).
PORT     STATE SERVICE
5672/tcp open  amqp
MAC Address: 0A:40:0E:8C:75:6C (Unknown)    
Nmap done: 1 IP address (1 host up) scanned in 0.13 seconds

Try to connect to a port manually with telnet, 5671 is CLOSED:

telnet localhost 5671
Trying 127.0.0.1...
telnet: connect to address 127.0.0.1: Connection refused

Try to connect to a port manually with telnet, 5672 is OPEN:

telnet localhost 5672
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.

Check your firewall:

sudo cat /etc/sysconfig/iptables  

It should tell you what ports are made open:

-A INPUT -p tcp -m tcp --dport 5672 -j ACCEPT

Reapply your firewall:

sudo service iptables restart
iptables: Setting chains to policy ACCEPT: filter          [  OK  ]
iptables: Flushing firewall rules:                         [  OK  ]
iptables: Unloading modules:                               [  OK  ]
iptables: Applying firewall rules:                         [  OK  ]

"Can't find Project or Library" for standard VBA functions

I have experienced this exact problem and found, on the users machine, one of the libraries I depended on was marked as "MISSING" in the references dialog. In that case it was some office font library that was available in my version of Office 2007, but not on the client desktop.

The error you get is a complete red herring (as pointed out by divo).

Fortunately I wasn't using anything from the library, so I was able to remove it from the XLA references entirely. I guess, an extension of divo' suggested best practice would be for testing to check the XLA on all the target Office versions (not a bad idea in any case).

How can I get the last day of the month in C#?

public static class DateTimeExtensions
{
    public static DateTime LastDayOfMonth(this DateTime date)
    {
        return date.AddDays(1-(date.Day)).AddMonths(1).AddDays(-1);
    }
}

Timeout for python requests.get entire response

Try this request with timeout & error handling:

import requests
try: 
    url = "http://google.com"
    r = requests.get(url, timeout=10)
except requests.exceptions.Timeout as e: 
    print e

django no such table:

You can try this!

python manage.py migrate --run-syncdb

I have the same problem with Django 1.9 and 1.10. This code works!

How do you display JavaScript datetime in 12 hour AM/PM format?

It will return the following format like

09:56 AM

appending zero in start for the hours as well if it is less than 10

Here it is using ES6 syntax

_x000D_
_x000D_
const getTimeAMPMFormat = (date) => {
  let hours = date.getHours();
  let minutes = date.getMinutes();
  const ampm = hours >= 12 ? 'PM' : 'AM';
  hours = hours % 12;
  hours = hours ? hours : 12; // the hour '0' should be '12'
  hours = hours < 10 ? '0' + hours : hours;
  // appending zero in the start if hours less than 10
  minutes = minutes < 10 ? '0' + minutes : minutes;
  return hours + ':' + minutes + ' ' + ampm;
};
console.log(getTimeAMPMFormat(new Date)); // 09:59 AM
_x000D_
_x000D_
_x000D_

Fill username and password using selenium in python

Use WebElement.send_keys method to simulate key typing.

name in the code (Username, Password) does not match actual name of the elements (username, password).


username = browser.find_element_by_name('username')
username.send_keys('user1')

password = browser.find_element_by_name('password')
password.send_keys('secret')

form = browser.find_element_by_id('loginForm')
form.submit()

# OR  browser.find_element_by_id('submit').click()

uncaught syntaxerror unexpected token U JSON

The parameter for the JSON.parse may be returning nothing (i.e. the value given for the JSON.parse is undefined)!

It happened to me while I was parsing the Compiled solidity code from an xyz.sol file.

import web3 from './web3';
import xyz from './build/xyz.json';

const i = new web3.eth.Contract(
  JSON.parse(xyz.interface),
  '0x99Fd6eFd4257645a34093E657f69150FEFf7CdF5'
);

export default i;

which was misspelled as

JSON.parse(xyz.intereface)

which was returning nothing!

Resource from src/main/resources not found after building with maven

FileReader reads from files on the file system.

Perhaps you intended to use something like this to load a file from the class path

// this will look in src/main/resources before building and myjar.jar! after building.
InputStream is = MyClass.class.getClassloader()
                     .getResourceAsStream("config.txt");

Or you could extract the file from the jar before reading it.

Convert named list to vector with values only

This can be done by using unlist before as.vector. The result is the same as using the parameter use.names=FALSE.

as.vector(unlist(myList))

Custom fonts and XML layouts (Android)

If you only have one typeface you would like to add, and want less code to write, you can create a dedicated TextView for your specific font. See code below.

package com.yourpackage;
import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;

public class FontTextView extends TextView {
    public static Typeface FONT_NAME;


    public FontTextView(Context context) {
        super(context);
        if(FONT_NAME == null) FONT_NAME = Typeface.createFromAsset(context.getAssets(), "fonts/FontName.otf");
        this.setTypeface(FONT_NAME);
    }
    public FontTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        if(FONT_NAME == null) FONT_NAME = Typeface.createFromAsset(context.getAssets(), "fonts/FontName.otf");
        this.setTypeface(FONT_NAME);
    }
    public FontTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        if(FONT_NAME == null) FONT_NAME = Typeface.createFromAsset(context.getAssets(), "fonts/FontName.otf");
        this.setTypeface(FONT_NAME);
    }
}

In main.xml, you can now add your textView like this:

<com.yourpackage.FontTextView
    android:id="@+id/tvTimer"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="" />

How might I convert a double to the nearest integer value?

Use Math.round(), possibly in conjunction with MidpointRounding.AwayFromZero

eg:

Math.Round(1.2) ==> 1
Math.Round(1.5) ==> 2
Math.Round(2.5) ==> 2
Math.Round(2.5, MidpointRounding.AwayFromZero) ==> 3

Line break in SSRS expression

Use the vbcrlf for new line in SSSR. e.g.

= First(Fields!SAPName.Value, "DataSet1") & vbcrlf & First(Fields!SAPStreet.Value, "DataSet1") & vbcrlf & First(Fields!SAPCityPostal.Value, "DataSet1") & vbcrlf & First(Fields!SAPCountry.Value, "DataSet1") 

SDK Manager.exe doesn't work

What I did was:

set a new environment variable in the top user section.

VARIABLE NAME: JAVA_HOME VARIABLE VALUE: set it to the installation directory of your most recent JDK.

For me it was, C:\Program Files\Java\jdk1.7.0_13 . Run SDK Manager as administrator at least once. I use windows 7. This method worked for me after a lot of research.

What I dont understand is when using 'where java' in the command prompt it still references C:\Windows\System32\java.exe. My SDK Manager now opens when I need it so I solved my problem.

How to switch to the new browser window, which opens after click on the button?

If you have more then one browser (using java 8)

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class TestLink {

  private static Set<String> windows;

  public static void main(String[] args) {

    WebDriver driver = new FirefoxDriver();
    driver.get("file:///C:/Users/radler/Desktop/myLink.html");
    setWindows(driver);
    driver.findElement(By.xpath("//body/a")).click();
    // get new window
    String newWindow = getWindow(driver);
    driver.switchTo().window(newWindow);

    // Perform the actions on new window
    String text = driver.findElement(By.cssSelector(".active")).getText();
    System.out.println(text);

    driver.close();
    // Switch back
    driver.switchTo().window(windows.iterator().next());


    driver.findElement(By.xpath("//body/a")).click();

  }

  private static void setWindows(WebDriver driver) {
    windows = new HashSet<String>();
    driver.getWindowHandles().stream().forEach(n -> windows.add(n));
  }

  private static String getWindow(WebDriver driver) {
    List<String> newWindow = driver.getWindowHandles().stream()
        .filter(n -> windows.contains(n) == false).collect(Collectors.toList());
    System.out.println(newWindow.get(0));
    return newWindow.get(0);
  }

}

How to get HttpClient returning status code and response body?

Fluent facade API:

Response response = Request.Get(uri)
        .connectTimeout(MILLIS_ONE_SECOND)
        .socketTimeout(MILLIS_ONE_SECOND)
        .execute();
HttpResponse httpResponse = response.returnResponse();
StatusLine statusLine = httpResponse.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
    // ??????????(???????)
    String responseContent = EntityUtils.toString(
            httpResponse.getEntity(), StandardCharsets.UTF_8.name());
}

External VS2013 build error "error MSB4019: The imported project <path> was not found"

I was using an external build utility. Think of something like Ants, if I understand the product correctly, just a commercial version. I had to contact the manufacturer for the answer.

As it turns out, there is a global macro in the project, DEVSTUDIO_NET_DIR. I had to change the path to .Net there. They list various visual studio versions as "Actions", which through me off, but all roads lead back to that one global variable behind the scenes. I would list that as a defect against the product, if I had my way, unless I am missing something in my understanding. Correcting the path there fixed the build problem.

How to set JAVA_HOME environment variable on Mac OS X 10.9?

It is recommended to check default terminal shell before set JAVA_HOME environment variable, via following commands:

$ echo $SHELL
/bin/bash

If your default terminal is /bin/bash (Bash), then you should use @Adrian Petrescu method.

If your default terminal is /bin/zsh (Z Shell), then you should set these environment variable in ~/.zshenv file with following contents:

export JAVA_HOME="$(/usr/libexec/java_home)"

Similarly, any other terminal type not mentioned above, you should set environment variable in its respective terminal env file.

My Routes are Returning a 404, How can I Fix Them?

Routes

Use them to define specific routes that aren't managed by controllers.

Controllers

Use them when you want to use traditional MVC architecture

Solution to your problem

You don't register controllers as routes unless you want a specific 'named' route for a controller action.

Rather than create a route for your controllers actions, just register your controller:

Route::controller('user');

Now your controller is registered, you can navigate to http://localhost/mysite/public/user and your get_index will be run.

You can also register all controllers in one go:

Route::controller(Controller::detect());

Get the size of the screen, current web page and browser window

Full 2020

I am surprised that question have about 10 years and it looks like so far nobody has given a full answer (with 10 values) yet. So I carefully analyse OP question (especially picture) and have some remarks

  • center of coordinate system (0,0) is in the viewport (browser window without bars and main borders) top left corner and axes are directed to right and down (what was marked on OP picture) so the values of pageX, pageY, screenX, screenY must be negative (or zero if page is small or not scrolled)
  • for screenHeight/Width OP wants to count screen height/width including system menu bar (eg. in MacOs) - this is why we NOT use .availWidth/Height (which not count it)
  • for windowWidth/Height OP don't want to count size of scroll bars so we use .clientWidth/Height
  • the screenY - in below solution we add to position of top left browser corner (window.screenY) the height of its menu/tabls/url bar). But it is difficult to calculate that value if download-bottom bar appears in browser and/or if developer console is open on page bottom - in that case this value will be increased of size of that bar/console height in below solution. Probably it is impossible to read value of bar/console height to make correction (without some trick like asking user to close that bar/console before measurements...)
  • pageWidth - in case when pageWidth is smaller than windowWidth we need to manually calculate size of <body> children elements to get this value (we do example calculation in contentWidth in below solution - but in general this can be difficult for that case)
  • for simplicity I assume that <body> margin=0 - if not then you should consider this values when calculate pageWidth/Height and pageX/Y

_x000D_
_x000D_
function sizes() {
  let contentWidth = [...document.body.children].reduce( 
    (a, el) => Math.max(a, el.getBoundingClientRect().right), 0) 
    - document.body.getBoundingClientRect().x;

  return {
    windowWidth:  document.documentElement.clientWidth,
    windowHeight: document.documentElement.clientHeight,
    pageWidth:    Math.min(document.body.scrollWidth, contentWidth),
    pageHeight:   document.body.scrollHeight,
    screenWidth:  window.screen.width,
    screenHeight: window.screen.height,
    pageX:        document.body.getBoundingClientRect().x,
    pageY:        document.body.getBoundingClientRect().y,
    screenX:     -window.screenX,
    screenY:     -window.screenY - (window.outerHeight-window.innerHeight),
  }
}



// TEST

function show() {
  console.log(sizes());
}
_x000D_
body { margin: 0 }
.box { width: 3000px; height: 4000px; background: red; }
_x000D_
<div class="box">
  CAUTION: stackoverflow snippet gives wrong values for screenX-Y, 
  but if you copy this code to your page directly the values will be right<br>
  <button onclick="show()" style="">CALC</button>
</div>
_x000D_
_x000D_
_x000D_

I test it on Chrome 83.0, Safari 13.1, Firefox 77.0 and Edge 83.0 on MacOs High Sierra

How do I get and set Environment variables in C#?

Get and Set

Get

string getEnv = Environment.GetEnvironmentVariable("envVar");

Set

string setEnv = Environment.SetEnvironmentVariable("envvar", varEnv);

How to make the web page height to fit screen height

As another guy described here, all you need to do is add

height: 100vh;

to the style of whatever you need to fill the screen

JavaScript TypeError: Cannot read property 'style' of null

Your missing a ' after night. right here getElementById('Night

Return multiple values from a SQL Server function

Erland Sommarskog has an exhaustive post about passing data in SQL Server located here:

http://www.sommarskog.se/share_data.html

He covers SQL Server 2000, 2005, and 2008, and it should probably be read in its full detail as there is ample coverage of each method's advantages and drawbacks. However, here are the highlights of the article (frozen in time as of July 2015) for the sake of providing search terms that can be used to look greater details:

This article tackles two related questions:

  • How can I use the result set from one stored procedure in another, also expressed as How can I use the result set from a stored
    procedure in a SELECT statement?
  • How can I pass a table data in a parameter from one stored procedure to another?

OUTPUT Parameters

  • Not generally applicable, but sometimes overlooked.

Table-valued Functions

  • Often the best choice for output-only, but there are several restrictions.
  • Examples:
    • Inline Functions: Use this to reuse a single SELECT.
    • Multi-statement Functions: When you need to encapsulate more complex logic.

Using a Table

  • The most general solution. My favoured choice for input/output scenarios.
  • Examples:
    • Sharing a Temp Table: Mainly for a single pair of caller/callee.
    • Process-keyed Table: Best choice for many callers to the same callee.
    • Global Temp Tables: A variation of process-keyed.

Table-valued Parameters

  • Req. Version: SQL 2008
  • Mainly useful when passing data from a client.

INSERT-EXEC

  • Deceivingly appealing, but should be used sparingly.

Using the CLR

  • Req. Version: SQL 2005
  • Complex, but useful as a last resort when INSERT-EXEC does not work.

OPENQUERY

  • Tricky with many pitfalls. Discouraged.

Using XML

  • Req. Version: SQL 2005
  • A bit of a kludge, but not without advantages.

Using Cursor Variables

  • Not recommendable.

How can I get city name from a latitude and longitude point?

Same as @Sanchit Gupta.

in this part

if (results[0]) {
 var add= results[0].formatted_address ;
 var  value=add.split(",");
 count=value.length;
 country=value[count-1];
 state=value[count-2];
 city=value[count-3];
 x.innerHTML = "city name is: " + city;
}

just console the results array

if (results[0]) {
 console.log(results[0]);
 // choose from console whatever you need.
 var city = results[0].address_components[3].short_name;
 x.innerHTML = "city name is: " + city;
}

Clearfix with twitter bootstrap

clearfix should contain the floating elements but in your html you have added clearfix only after floating right that is your pull-right so you should do like this:

<div class="clearfix">
  <div id="sidebar">
    <ul>
      <li>A</li>
      <li>A</li>
      <li>C</li>
      <li>D</li>
      <li>E</li>
      <li>F</li>
      <li>...</li>
      <li>Z</li>
    </ul>
  </div>
  <div id="main">
    <div>
      <div class="pull-right">
        <a>RIGHT</a>
      </div>
    </div>
  <div>MOVED BELOW Z</div>
</div>

see this demo


Happy to know you solved the problem by setting overflow properties. However this is also good idea to clear the float. Where you have floated your elements you could add overflow: hidden; as you have done in your main.

ipython notebook clear cell output in code

You can use the IPython.display.clear_output to clear the output as mentioned in cel's answer. I would add that for me the best solution was to use this combination of parameters to print without any "shakiness" of the notebook:

from IPython.display import clear_output

for i in range(10):
    clear_output(wait=True)
    print(i, flush=True)

How do I create a foreign key in SQL Server?

And if you just want to create the constraint on its own, you can use ALTER TABLE

alter table MyTable
add constraint MyTable_MyColumn_FK FOREIGN KEY ( MyColumn ) references MyOtherTable(PKColumn)

I wouldn't recommend the syntax mentioned by Sara Chipps for inline creation, just because I would rather name my own constraints.

Use stored procedure to insert some data into a table

If you are trying to return back the ID within the scope, using the SCOPE_IDENTITY() would be a better approach. I would not advice to use @@IDENTITY, as this can return any ID.

CREATE PROC [dbo].[sp_Test] (
  @myID int output,
  @myFirstName nvarchar(50),
  @myLastName nvarchar(50),
  @myAddress nvarchar(50),
  @myPort int
) AS
BEGIN
    INSERT INTO Dvds (myFirstName, myLastName, myAddress, myPort)
    VALUES (@myFirstName, @myLastName, @myAddress, @myPort);

    SET @myID = SCOPE_IDENTITY();
END
GO

adb not finding my device / phone (MacOS X)

In my case, it was because the USB cable.

I discovered there are two types of USB cables:

  • Those that only supply power
  • Those that supply power and can transfer data

And it's hard to know what type is a USB cable. Now I make a notch on my cables with data transfer.

How to get input textfield values when enter key is pressed in react js?

Adding onKeyPress will work onChange in Text Field.

<TextField
  onKeyPress={(ev) => {
    console.log(`Pressed keyCode ${ev.key}`);
    if (ev.key === 'Enter') {
      // Do code here
      ev.preventDefault();
    }
  }}
/>

How to run shell script file using nodejs?

you can go:

var cp = require('child_process');

and then:

cp.exec('./myScript.sh', function(err, stdout, stderr) {
  // handle err, stdout, stderr
});

to run a command in your $SHELL.
Or go

cp.spawn('./myScript.sh', [args], function(err, stdout, stderr) {
  // handle err, stdout, stderr
});

to run a file WITHOUT a shell.
Or go

cp.execFile();

which is the same as cp.exec() but doesn't look in the $PATH.

You can also go

cp.fork('myJS.js', function(err, stdout, stderr) {
  // handle err, stdout, stderr
});

to run a javascript file with node.js, but in a child process (for big programs).

EDIT

You might also have to access stdin and stdout with event listeners. e.g.:

var child = cp.spawn('./myScript.sh', [args]);
child.stdout.on('data', function(data) {
  // handle stdout as `data`
});

How to clear Tkinter Canvas?

Items drawn to the canvas are persistent. create_rectangle returns an item id that you need to keep track of. If you don't remove old items your program will eventually slow down.

From Fredrik Lundh's An Introduction to Tkinter:

Note that items added to the canvas are kept until you remove them. If you want to change the drawing, you can either use methods like coords, itemconfig, and move to modify the items, or use delete to remove them.

Java String to SHA1

Convert byte array to hex string.

public static String toSHA1(byte[] convertme) {
    final char[] HEX_CHARS = "0123456789ABCDEF".toCharArray();
    MessageDigest md = null;
    try {
        md = MessageDigest.getInstance("SHA-1");
    }
    catch(NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    byte[] buf = md.digest(convertme);
    char[] chars = new char[2 * buf.length];
    for (int i = 0; i < buf.length; ++i) {
        chars[2 * i] = HEX_CHARS[(buf[i] & 0xF0) >>> 4];
        chars[2 * i + 1] = HEX_CHARS[buf[i] & 0x0F];
    }
    return new String(chars);
}

SVG drop shadow using css3

Easiest way I've found is with feDropShadow.

<filter id="shadow" x="0" y="0" width="200%" height="200%">
  <feDropShadow dx="40" dy="40" stdDeviation="35" flood-color="#ff0000" flood-opacity="1" />
</filter>

On the element:

<path d="..." filter="url(#shadow)"/>

How do I compare two strings in Perl?

See perldoc perlop. Use lt, gt, eq, ne, and cmp as appropriate for string comparisons:

Binary eq returns true if the left argument is stringwise equal to the right argument.

Binary ne returns true if the left argument is stringwise not equal to the right argument.

Binary cmp returns -1, 0, or 1 depending on whether the left argument is stringwise less than, equal to, or greater than the right argument.

Binary ~~ does a smartmatch between its arguments. ...

lt, le, ge, gt and cmp use the collation (sort) order specified by the current locale if a legacy use locale (but not use locale ':not_characters') is in effect. See perllocale. Do not mix these with Unicode, only with legacy binary encodings. The standard Unicode::Collate and Unicode::Collate::Locale modules offer much more powerful solutions to collation issues.

Multiple actions were found that match the request in Web Api

This is the answer for everyone who knows everything is correct and has checked 50 times.....

Make sure you are not repeatedly looking at RouteConfig.cs.

The file you want to edit is named WebApiConfig.cs

Also, it should probably look exactly like this:

using System.Web.Http;

namespace My.Epic.Website
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
          config.MapHttpAttributeRoutes();

          // api/Country/WithStates
          config.Routes.MapHttpRoute(
            name: "ControllerAndActionOnly",
            routeTemplate: "api/{controller}/{action}",
            defaults: new { },
            constraints: new { action = @"^[a-zA-Z]+([\s][a-zA-Z]+)*$" });

          config.Routes.MapHttpRoute(
            name: "DefaultActionApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
          );
    }
    }
}

I could have saved myself about 3 hours.

mysql datatype for telephone number and address

I usually store phone numbers as a BIGINT in E164 format.

E164 never start with a 0, with the first few digits being the country code.

+441234567890
+44 (0)1234 567890
01234 567890

etc. would be stored as 441234567890.

VBA equivalent to Excel's mod function

The top answer is actually wrong.

The suggested equation: a - (b * (a \ b))

Will solve to: a - a

Which is of course 0 in all cases.

The correct equation is:

a - (b * INT(a \ b))

Or, if the number (a) can be negative, use this:

a - (b * FIX(a \ b))

ImportError in importing from sklearn: cannot import name check_build

I had problems importing SKLEARN after installing a new 64bit version of Python 3.4 from python.org.

Turns out that it was the SCIPY module that was broken, and alos failed when I tried to "import scipy".

Solution was to uninstall scipy and reinstall it with pip3:

C:\> pip uninstall scipy

[lots of reporting messages deleted]

Proceed (y/n)? y
  Successfully uninstalled scipy-1.0.0

C:\Users\>pip3 install scipy

Collecting scipy
  Downloading scipy-1.0.0-cp36-none-win_amd64.whl (30.8MB)
    100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 30.8MB 33kB/s
Requirement already satisfied: numpy>=1.8.2 in c:\users\johnmccurdy\appdata\loca
l\programs\python\python36\lib\site-packages (from scipy)
Installing collected packages: scipy
Successfully installed scipy-1.0.0

C:\Users>python
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:54:40) [MSC v.1900 64 bit (AMD64)]
 on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import scipy
>>>
>>> import sklearn
>>>

Why does Eclipse Java Package Explorer show question mark on some classes?

In a enabled project the small question mark (?) indicates that your file is not yet added to the SVN repository.

The small orange rectangle is an indication that your file is committed in the repository.

An asterisk (*) indicates a local change.

500 internal server error at GetResponse()

looking at your error message first of all I would suggest you to recompile your whole application, make sure all the required dlls are there in bin folder when you recompile it.

How to do 3 table JOIN in UPDATE query?

For PostgreSQL example:

UPDATE TableA AS a
SET param_from_table_a=FALSE -- param FROM TableA
FROM TableB AS b
WHERE b.id=a.param_id AND a.amount <> 0; 

How to change the application launcher icon on Flutter?

Follow these steps:-

1. Add dependencies of flutter_luncher_icons in pubspec.yaml file.You can find this plugin from here.

2. Add your required images in asstes folder and pubspec.yaml file as below .

pubspec.yaml

name: NewsApi.org
description: A new Flutter application.

# The following line prevents the package from being accidentally published to
# pub.dev using `pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1

environment:
  sdk: ">=2.7.0 <3.0.0"

dependencies:
  flutter:
      sdk: flutter


  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.1
  fluttertoast: ^7.1.6
  toast: ^0.1.5
  flutter_launcher_icons: ^0.8.0




dev_dependencies:
  flutter_test:
    sdk: flutter

flutter_icons:
  image_path: "assets/icon/newsicon.png"
  android: true
  ios: false

# The following section is specific to Flutter.
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true
  assets:
    - assets/images/dropbox.png



  fonts:
    - family: LangerReguler
      fonts:
        - asset: assets/langer_reguler.ttf




  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.dev/custom-fonts/#from-packages

3. Then run the command in terminal flutter pub get and then flutter_luncher_icon.This is what I get the result after the successfully run the command . And luncher icon is also generated successfully.

My Terminal

[E:\AndroidStudioProjects\FlutterProject\NewsFlutter\news_flutter>flutter pub get
Running "flutter pub get" in news_flutter...                       881ms

E:\AndroidStudioProjects\FlutterProject\NewsFlutter\news_flutter>flutter pub run flutter_launcher_icons:main
  --------------------------------------------
     FLUTTER LAUNCHER ICONS (v0.8.0)
  --------------------------------------------

• Creating default icons Android
• Overwriting the default Android launcher icon with a new icon

? Successfully generated launcher icons

python pandas: apply a function with arguments to a series

You can pass any number of arguments to the function that apply is calling through either unnamed arguments, passed as a tuple to the args parameter, or through other keyword arguments internally captured as a dictionary by the kwds parameter.

For instance, let's build a function that returns True for values between 3 and 6, and False otherwise.

s = pd.Series(np.random.randint(0,10, 10))
s

0    5
1    3
2    1
3    1
4    6
5    0
6    3
7    4
8    9
9    6
dtype: int64

s.apply(lambda x: x >= 3 and x <= 6)

0     True
1     True
2    False
3    False
4     True
5    False
6     True
7     True
8    False
9     True
dtype: bool

This anonymous function isn't very flexible. Let's create a normal function with two arguments to control the min and max values we want in our Series.

def between(x, low, high):
    return x >= low and x =< high

We can replicate the output of the first function by passing unnamed arguments to args:

s.apply(between, args=(3,6))

Or we can use the named arguments

s.apply(between, low=3, high=6)

Or even a combination of both

s.apply(between, args=(3,), high=6)

How do I get the last word in each line with bash

tldr;

$ awk '{print $NF}' file.txt | paste -sd, | sed 's/,/, /g'

For a file like this

$ cat file.txt
The quick brown fox
jumps over
the lazy dog.

the given command will print

fox, over, dog.

How it works:

  • awk '{print $NF}' : prints the last field of every line
  • paste -sd, : reads stdin serially (-s, one file at a time) and writes fields comma-delimited (-d,)
  • sed 's/,/, /g' : substitutes "," with ", " globally (for all instances)

References:

Git 'fatal: Unable to write new index file'

I had ACL (somehow) attached to all files in the .git folder.

Check it with ls -le in the .git folder.

You can remove the ACL with chmod -N (for a folder/file) or chmod -RN (recursive)

What is the best way to generate a unique and short file name in Java

This works for me:

String generateUniqueFileName() {
    String filename = "";
    long millis = System.currentTimeMillis();
    String datetime = new Date().toGMTString();
    datetime = datetime.replace(" ", "");
    datetime = datetime.replace(":", "");
    String rndchars = RandomStringUtils.randomAlphanumeric(16);
    filename = rndchars + "_" + datetime + "_" + millis;
    return filename;
}

// USE:

String newFile;
do{
newFile=generateUniqueFileName() + "." + FileExt;
}
while(new File(basePath+newFile).exists());

Output filenames should look like :

2OoBwH8OwYGKW2QE_4Sep2013061732GMT_1378275452253.Ext

How to strip all whitespace from string

The simplest is to use replace:

"foo bar\t".replace(" ", "").replace("\t", "")

Alternatively, use a regular expression:

import re
re.sub(r"\s", "", "foo bar\t")

How to compile and run C in sublime text 3?

Instruction is base on the "icemelon" post. Link to the post:

how-do-i-compile-and-run-a-c-program-in-sublime-text-2

Use the link below to find out how to setup enviroment variable on your OS:

c_environment_setup

The instruction below was tested on the Windows 8.1 system and Sublime Text 3 - build 3065.

1) Install MinGW. 2) Add path to the "MinGW\bin" in the "PATH environment variable".

"System Properties -> Advanced -> Environment" variables and there update "PATH' variable.

3) Then check your PATH environment variable by the command below in the "Command Prompt":

echo %path%

4) Add new Build System to the Sublime Text.

My version of the code below ("C.sublime-build").

link to the code:

C.sublime-build

// Put this file here:
// "C:\Users\[User Name]\AppData\Roaming\Sublime Text 3\Packages\User"
// Use "Ctrl+B" to Build and "Crtl+Shift+B" to Run the project.
// OR use "Tools -> Build System -> New Build System..." and put the code there.

{
    "cmd" : ["gcc", "$file_name", "-o", "${file_base_name}.exe"],

    // Doesn't work, sublime text 3, Windows 8.1    
    // "cmd" : ["gcc $file_name -o ${file_base_name}"],

    "selector" : "source.c",
    "shell": true,
    "working_dir" : "$file_path",

    // You could add path to your gcc compiler this and don't add path to your "PATH environment variable"
    // "path" : "C:\\MinGW\\bin"

    "variants" : [

        { "name": "Run",
          "cmd" : ["${file_base_name}.exe"]
        }
    ]
}

C++ Remove new line from multiline string

#include <algorithm>
#include <string>

std::string str;

str.erase(std::remove(str.begin(), str.end(), '\n'), str.end());

The behavior of std::remove may not quite be what you'd expect. See an explanation of it here.

Using FolderBrowserDialog in WPF application

If I'm not mistaken you're looking for the FolderBrowserDialog (hence the naming):

var dialog = new System.Windows.Forms.FolderBrowserDialog();
System.Windows.Forms.DialogResult result = dialog.ShowDialog();

Also see this SO thread: Open directory dialog

read complete file without using loop in java

You can try using Scanner if you are using JDK5 or higher.

Scanner scan = new Scanner(file);  
scan.useDelimiter("\\Z");  
String content = scan.next(); 

Or you can also use Guava

String data = Files.toString(new File("path.txt"), Charsets.UTF8);

How to call a method with a separate thread in Java?

Another quicker option to call things (like DialogBoxes and MessageBoxes and creating separate threads for not-thread safe methods) would be to use the Lamba Expression

  new Thread(() -> {
                      "code here"
            }).start();

Ruby get object keys as array

An alternative way if you need something more (besides using the keys method):

hash = {"apple" => "fruit", "carrot" => "vegetable"}
array = hash.collect {|key,value| key }

obviously you would only do that if you want to manipulate the array while retrieving it..

length and length() in Java

Let me first highlight three different ways for similar purpose.

length -- arrays (int[], double[], String[]) -- to know the length of the arrays

length() -- String related Object (String, StringBuilder, etc) -- to know the length of the String

size() -- Collection Object (ArrayList, Set, etc) -- to know the size of the Collection

Now forget about length() consider just length and size().

length is not a method, so it completely makes sense that it will not work on objects. It only works on arrays.
size() its name describes it better and as it is a method, it will be used in the case of those objects who work with collection (collection frameworks) as I said up there.

Now come to length():
String is not a primitive array (so we can't use .length) and also not a Collection (so we cant use .size()) that's why we also need a different one which is length() (keep the differences and serve the purpose).

As answer to Why?
I find it useful, easy to remember and use and friendly.

What are MVP and MVC and what is the difference?

MVP: the view is in charge.

The view, in most cases, creates its presenter. The presenter will interact with the model and manipulate the view through an interface. The view will sometimes interact with the presenter, usually through some interface. This comes down to implementation; do you want the view to call methods on the presenter or do you want the view to have events the presenter listens to? It boils down to this: The view knows about the presenter. The view delegates to the presenter.

MVC: the controller is in charge.

The controller is created or accessed based on some event/request. The controller then creates the appropriate view and interacts with the model to further configure the view. It boils down to: the controller creates and manages the view; the view is slave to the controller. The view does not know about the controller.

change the date format in laravel view page

There are 3 ways that you can do:

1) Using Laravel Model

$user = \App\User::find(1);

$newDateFormat = $user->created_at->format('d/m/Y');

dd($newDateFormat);

2) Using PHP strtotime

$user = \App\User::find(1);

$newDateFormat2 = date('d/m/Y', strtotime($user->created_at));

dd($newDateFormat2);

3) Using Carbon

$user = \App\User::find(1);

$newDateFormat3 = \Carbon\Carbon::parse($user->created_at)->format('d/m/Y');

dd($newDateFormat3);

Trim a string in C

Here's my implementation, behaving like the built-in string functions in libc (that is, it expects a c-string, it modifies it and returns it to the caller).

It trims leading spaces & shifts the remaining chars to the left, as it parses the string from left to right. It then marks a new end of string and starts parsing it backwards, replacing trailing spaces with '\0's until it finds either a non-space char or the start of the string. I believe those are the minimum possible iterations for this particular task.

// ----------------------------------------------------------------------------
// trim leading & trailing spaces from string s (return modified string s)
// alg:
// - skip leading spaces, via cp1
// - shift remaining *cp1's to the left, via cp2
// - mark a new end of string
// - replace trailing spaces with '\0', via cp2
// - return the trimmed s
//
char *s_trim(char *s)
{
    char *cp1;                              // for parsing the whole s
    char *cp2;                              // for shifting & padding

    // skip leading spaces, shift remaining chars
    for (cp1=s; isspace(*cp1); cp1++ )      // skip leading spaces, via cp1
        ;
    for (cp2=s; *cp1; cp1++, cp2++)         // shift left remaining chars, via cp2
        *cp2 = *cp1;
    *cp2-- = 0;                             // mark new end of string for s

    // replace trailing spaces with '\0'
    while ( cp2 > s && isspace(*cp2) )
        *cp2-- = 0;                         // pad with '\0's

    return s;
}

RecyclerView - How to smooth scroll to top of item on a certain position?

You can reverse your list by list.reverse() and finaly call RecylerView.scrollToPosition(0)

    list.reverse()
    layout = LinearLayoutManager(this,LinearLayoutManager.VERTICAL,true)  
    RecylerView.scrollToPosition(0)

Combining CSS Pseudo-elements, ":after" the ":last-child"

Just To mention, in CSS 3

:after

should be used like this

::after

From https://developer.mozilla.org/de/docs/Web/CSS/::after :

The ::after notation was introduced in CSS 3 in order to establish a discrimination between pseudo-classes and pseudo-elements. Browsers also accept the notation :after introduced in CSS 2.

So it should be:

li { display: inline; list-style-type: none; }
li::after { content: ", "; }
li:last-child::before { content: "and "; }
li:last-child::after { content: "."; }

Remove files from Git commit

Existing answers are all talking about removing the unwanted files from the last commit.

If you want to remove unwanted files from an old commit (even pushed) and don't want to create a new commit, which is unnecessary, because of the action:

1.

Find the commit that you want the file to conform to.

git checkout <commit_id> <path_to_file>

you can do this multiple times if you want to remove many files.

2.

git commit -am "remove unwanted files"

3.

Find the commit_id of the commit on which the files were added mistakenly, let's say "35c23c2" here

git rebase 35c23c2~1 -i  // notice: "~1" is necessary

This command opens the editor according to your settings. The default one is vim.

Move the last commit, which should be "remove unwanted files", to the next line of the incorrect commit("35c23c2" in our case), and set the command as fixup:

pick 35c23c2 the first commit
fixup 0d78b28 remove unwanted files

You should be good after saving the file.

To finish :

git push -f

If you unfortunately get conflicts, you have to solve them manually.

Jackson Vs. Gson

Adding to other answers already given above. If case insensivity is of any importance to you, then use Jackson. Gson does not support case insensitivity for key names, while jackson does.

Here are two related links

(No) Case sensitivity support in Gson : GSON: How to get a case insensitive element from Json?

Case sensitivity support in Jackson https://gist.github.com/electrum/1260489

jquery, domain, get URL

You don't need jQuery for this, as simple javascript will suffice:

alert(document.domain);

See it in action:

_x000D_
_x000D_
console.log("Output;");  _x000D_
console.log(location.hostname);_x000D_
console.log(document.domain);_x000D_
alert(window.location.hostname)_x000D_
_x000D_
console.log("document.URL : "+document.URL);_x000D_
console.log("document.location.href : "+document.location.href);_x000D_
console.log("document.location.origin : "+document.location.origin);_x000D_
console.log("document.location.hostname : "+document.location.hostname);_x000D_
console.log("document.location.host : "+document.location.host);_x000D_
console.log("document.location.pathname : "+document.location.pathname);
_x000D_
_x000D_
_x000D_

For further domain-related values, check out the properties of window.location online. You may find that location.host is a better option, as its content could differ from document.domain. For instance, the url http://192.168.1.80:8080 will have only the ipaddress in document.domain, but both the ipaddress and port number in location.host.

TypeLoadException says 'no implementation', but it is implemented

I encountered this when I renamed a project (and the assembly name), which was depended upon by an ASP.NET project. Types in the web project implemented interfaces in the dependent assembly. Despite executing Clean Solution from the Build menu, the assembly with the previous name remained in the bin folder, and when my web project executed

var types = AppDomain.CurrentDomain.
   GetAssemblies().
   ToList().
   SelectMany( s => s.GetTypes() /* exception thrown in this call */ )
;

the above exception was thrown, complaining that interface methods in the implementing web types were not actually implemented. Manually deleting the assembly in the web project's bin folder resolved the problem.

Converting a string to JSON object

var Data=[{"id": "name2", "label": "Quantity"}]

Pass the string variable into Json parse :

Objdata= Json.parse(Data);

Programmatically navigate to another view controller/scene

I think you are looking for something like this:

let signUpViewController = SignUpViewController()
present(signUpViewController, animated: true, completion: nil)

If you want full screen of the new page:

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

Hope this helps :)

How can I set the focus (and display the keyboard) on my EditText programmatically

I recommend using a LifecycleObserver which is part of the Handling Lifecycles with Lifecycle-Aware Components of Android Jetpack.

I want to open and close the Keyboard when the Fragment/Activity appears. Firstly, define two extension functions for the EditText. You can put them anywhere in your project:

fun EditText.showKeyboard() {
    requestFocus()
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
}

fun EditText.hideKeyboard() {
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(this.windowToken, 0)
}

Then define a LifecycleObserver which opens and closes the keyboard when the Activity/Fragment reaches onResume() or onPause:

class EditTextKeyboardLifecycleObserver(private val editText: WeakReference<EditText>) :
    LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun openKeyboard() {
        editText.get()?.postDelayed({ editText.get()?.showKeyboard() }, 100)
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    fun closeKeyboard() {
        editText.get()?.hideKeyboard()
    }
}

Then add the following line to any of your Fragments/Activities, you can reuse the LifecycleObserver any times. E.g. for a Fragment:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

    // inflate the Fragment layout

    lifecycle.addObserver(EditTextKeyboardLifecycleObserver(WeakReference(myEditText)))

    // do other stuff and return the view

}

The Definitive C Book Guide and List

Beginner

Introductory, no previous programming experience

  • C++ Primer * (Stanley Lippman, Josée Lajoie, and Barbara E. Moo) (updated for C++11) Coming at 1k pages, this is a very thorough introduction into C++ that covers just about everything in the language in a very accessible format and in great detail. The fifth edition (released August 16, 2012) covers C++11. [Review]

    * Not to be confused with C++ Primer Plus (Stephen Prata), with a significantly less favorable review.

  • Programming: Principles and Practice Using C++ (Bjarne Stroustrup, 2nd Edition - May 25, 2014) (updated for C++11/C++14) An introduction to programming using C++ by the creator of the language. A good read, that assumes no previous programming experience, but is not only for beginners.

Introductory, with previous programming experience

  • A Tour of C++ (Bjarne Stroustrup) (2nd edition for C++17) The “tour” is a quick (about 180 pages and 14 chapters) tutorial overview of all of standard C++ (language and standard library, and using C++11) at a moderately high level for people who already know C++ or at least are experienced programmers. This book is an extended version of the material that constitutes Chapters 2-5 of The C++ Programming Language, 4th edition.

  • Accelerated C++ (Andrew Koenig and Barbara Moo, 1st Edition - August 24, 2000) This basically covers the same ground as the C++ Primer, but does so on a fourth of its space. This is largely because it does not attempt to be an introduction to programming, but an introduction to C++ for people who've previously programmed in some other language. It has a steeper learning curve, but, for those who can cope with this, it is a very compact introduction to the language. (Historically, it broke new ground by being the first beginner's book to use a modern approach to teaching the language.) Despite this, the C++ it teaches is purely C++98. [Review]

Best practices

  • Effective C++ (Scott Meyers, 3rd Edition - May 22, 2005) This was written with the aim of being the best second book C++ programmers should read, and it succeeded. Earlier editions were aimed at programmers coming from C, the third edition changes this and targets programmers coming from languages like Java. It presents ~50 easy-to-remember rules of thumb along with their rationale in a very accessible (and enjoyable) style. For C++11 and C++14 the examples and a few issues are outdated and Effective Modern C++ should be preferred. [Review]

  • Effective Modern C++ (Scott Meyers) This is basically the new version of Effective C++, aimed at C++ programmers making the transition from C++03 to C++11 and C++14.

  • Effective STL (Scott Meyers) This aims to do the same to the part of the standard library coming from the STL what Effective C++ did to the language as a whole: It presents rules of thumb along with their rationale. [Review]


Intermediate

  • More Effective C++ (Scott Meyers) Even more rules of thumb than Effective C++. Not as important as the ones in the first book, but still good to know.

  • Exceptional C++ (Herb Sutter) Presented as a set of puzzles, this has one of the best and thorough discussions of the proper resource management and exception safety in C++ through Resource Acquisition is Initialization (RAII) in addition to in-depth coverage of a variety of other topics including the pimpl idiom, name lookup, good class design, and the C++ memory model. [Review]

  • More Exceptional C++ (Herb Sutter) Covers additional exception safety topics not covered in Exceptional C++, in addition to discussion of effective object-oriented programming in C++ and correct use of the STL. [Review]

  • Exceptional C++ Style (Herb Sutter) Discusses generic programming, optimization, and resource management; this book also has an excellent exposition of how to write modular code in C++ by using non-member functions and the single responsibility principle. [Review]

  • C++ Coding Standards (Herb Sutter and Andrei Alexandrescu) “Coding standards” here doesn't mean “how many spaces should I indent my code?” This book contains 101 best practices, idioms, and common pitfalls that can help you to write correct, understandable, and efficient C++ code. [Review]

  • C++ Templates: The Complete Guide (David Vandevoorde and Nicolai M. Josuttis) This is the book about templates as they existed before C++11. It covers everything from the very basics to some of the most advanced template metaprogramming and explains every detail of how templates work (both conceptually and at how they are implemented) and discusses many common pitfalls. Has excellent summaries of the One Definition Rule (ODR) and overload resolution in the appendices. A second edition covering C++11, C++14 and C++17 has been already published. [Review]

  • C++ 17 - The Complete Guide (Nicolai M. Josuttis) This book describes all the new features introduced in the C++17 Standard covering everything from the simple ones like 'Inline Variables', 'constexpr if' all the way up to 'Polymorphic Memory Resources' and 'New and Delete with overaligned Data'. [Review]

  • C++ in Action (Bartosz Milewski). This book explains C++ and its features by building an application from ground up. [Review]

  • Functional Programming in C++ (Ivan Cukic). This book introduces functional programming techniques to modern C++ (C++11 and later). A very nice read for those who want to apply functional programming paradigms to C++.

  • Professional C++ (Marc Gregoire, 5th Edition - Feb 2021) Provides a comprehensive and detailed tour of the C++ language implementation replete with professional tips and concise but informative in-text examples, emphasizing C++20 features. Uses C++20 features, such as modules and std::format throughout all examples.


Advanced

  • Modern C++ Design (Andrei Alexandrescu) A groundbreaking book on advanced generic programming techniques. Introduces policy-based design, type lists, and fundamental generic programming idioms then explains how many useful design patterns (including small object allocators, functors, factories, visitors, and multi-methods) can be implemented efficiently, modularly, and cleanly using generic programming. [Review]

  • C++ Template Metaprogramming (David Abrahams and Aleksey Gurtovoy)

  • C++ Concurrency In Action (Anthony Williams) A book covering C++11 concurrency support including the thread library, the atomics library, the C++ memory model, locks and mutexes, as well as issues of designing and debugging multithreaded applications. A second edition covering C++14 and C++17 has been already published. [Review]

  • Advanced C++ Metaprogramming (Davide Di Gennaro) A pre-C++11 manual of TMP techniques, focused more on practice than theory. There are a ton of snippets in this book, some of which are made obsolete by type traits, but the techniques, are nonetheless useful to know. If you can put up with the quirky formatting/editing, it is easier to read than Alexandrescu, and arguably, more rewarding. For more experienced developers, there is a good chance that you may pick up something about a dark corner of C++ (a quirk) that usually only comes about through extensive experience.


Reference Style - All Levels

  • The C++ Programming Language (Bjarne Stroustrup) (updated for C++11) The classic introduction to C++ by its creator. Written to parallel the classic K&R, this indeed reads very much like it and covers just about everything from the core language to the standard library, to programming paradigms to the language's philosophy. [Review] Note: All releases of the C++ standard are tracked in the question "Where do I find the current C or C++ standard documents?".

  • C++ Standard Library Tutorial and Reference (Nicolai Josuttis) (updated for C++11) The introduction and reference for the C++ Standard Library. The second edition (released on April 9, 2012) covers C++11. [Review]

  • The C++ IO Streams and Locales (Angelika Langer and Klaus Kreft) There's very little to say about this book except that, if you want to know anything about streams and locales, then this is the one place to find definitive answers. [Review]

C++11/14/17/… References:

  • The C++11/14/17 Standard (INCITS/ISO/IEC 14882:2011/2014/2017) This, of course, is the final arbiter of all that is or isn't C++. Be aware, however, that it is intended purely as a reference for experienced users willing to devote considerable time and effort to its understanding. The C++17 standard is released in electronic form for 198 Swiss Francs.

  • The C++17 standard is available, but seemingly not in an economical form – directly from the ISO it costs 198 Swiss Francs (about $200 US). For most people, the final draft before standardization is more than adequate (and free). Many will prefer an even newer draft, documenting new features that are likely to be included in C++20.

  • Overview of the New C++ (C++11/14) (PDF only) (Scott Meyers) (updated for C++14) These are the presentation materials (slides and some lecture notes) of a three-day training course offered by Scott Meyers, who's a highly respected author on C++. Even though the list of items is short, the quality is high.

  • The C++ Core Guidelines (C++11/14/17/…) (edited by Bjarne Stroustrup and Herb Sutter) is an evolving online document consisting of a set of guidelines for using modern C++ well. The guidelines are focused on relatively higher-level issues, such as interfaces, resource management, memory management and concurrency affecting application architecture and library design. The project was announced at CppCon'15 by Bjarne Stroustrup and others and welcomes contributions from the community. Most guidelines are supplemented with a rationale and examples as well as discussions of possible tool support. Many rules are designed specifically to be automatically checkable by static analysis tools.

  • The C++ Super-FAQ (Marshall Cline, Bjarne Stroustrup and others) is an effort by the Standard C++ Foundation to unify the C++ FAQs previously maintained individually by Marshall Cline and Bjarne Stroustrup and also incorporating new contributions. The items mostly address issues at an intermediate level and are often written with a humorous tone. Not all items might be fully up to date with the latest edition of the C++ standard yet.

  • cppreference.com (C++03/11/14/17/…) (initiated by Nate Kohl) is a wiki that summarizes the basic core-language features and has extensive documentation of the C++ standard library. The documentation is very precise but is easier to read than the official standard document and provides better navigation due to its wiki nature. The project documents all versions of the C++ standard and the site allows filtering the display for a specific version. The project was presented by Nate Kohl at CppCon'14.


Classics / Older

Note: Some information contained within these books may not be up-to-date or no longer considered best practice.

  • The Design and Evolution of C++ (Bjarne Stroustrup) If you want to know why the language is the way it is, this book is where you find answers. This covers everything before the standardization of C++.

  • Ruminations on C++ - (Andrew Koenig and Barbara Moo) [Review]

  • Advanced C++ Programming Styles and Idioms (James Coplien) A predecessor of the pattern movement, it describes many C++-specific “idioms”. It's certainly a very good book and might still be worth a read if you can spare the time, but quite old and not up-to-date with current C++.

  • Large Scale C++ Software Design (John Lakos) Lakos explains techniques to manage very big C++ software projects. Certainly, a good read, if it only was up to date. It was written long before C++ 98 and misses on many features (e.g. namespaces) important for large-scale projects. If you need to work in a big C++ software project, you might want to read it, although you need to take more than a grain of salt with it. The first volume of a new edition is released in 2019.

  • Inside the C++ Object Model (Stanley Lippman) If you want to know how virtual member functions are commonly implemented and how base objects are commonly laid out in memory in a multi-inheritance scenario, and how all this affects performance, this is where you will find thorough discussions of such topics.

  • The Annotated C++ Reference Manual (Bjarne Stroustrup, Margaret A. Ellis) This book is quite outdated in the fact that it explores the 1989 C++ 2.0 version - Templates, exceptions, namespaces and new casts were not yet introduced. Saying that however, this book goes through the entire C++ standard of the time explaining the rationale, the possible implementations, and features of the language. This is not a book to learn programming principles and patterns on C++, but to understand every aspect of the C++ language.

  • Thinking in C++ (Bruce Eckel, 2nd Edition, 2000). Two volumes; is a tutorial style free set of intro level books. Downloads: vol 1, vol 2. Unfortunately they're marred by a number of trivial errors (e.g. maintaining that temporaries are automatically const), with no official errata list. A partial 3rd party errata list is available at http://www.computersciencelab.com/Eckel.htm, but it is apparently not maintained.

  • Scientific and Engineering C++: An Introduction to Advanced Techniques and Examples (John Barton and Lee Nackman) It is a comprehensive and very detailed book that tried to explain and make use of all the features available in C++, in the context of numerical methods. It introduced at the time several new techniques, such as the Curiously Recurring Template Pattern (CRTP, also called Barton-Nackman trick). It pioneered several techniques such as dimensional analysis and automatic differentiation. It came with a lot of compilable and useful code, ranging from an expression parser to a Lapack wrapper. The code is still available online. Unfortunately, the books have become somewhat outdated in the style and C++ features, however, it was an incredible tour-de-force at the time (1994, pre-STL). The chapters on dynamics inheritance are a bit complicated to understand and not very useful. An updated version of this classic book that includes move semantics and the lessons learned from the STL would be very nice.

How can I position my div at the bottom of its container?

CSS Grid

Since the usage of CSS Grid is increasing, I would like to suggest align-self to the element that is inside a grid container.

align-self can contain any of the values: end, self-end, flex-end for the following example.

_x000D_
_x000D_
#parent {_x000D_
  display: grid;_x000D_
}_x000D_
_x000D_
#child1 {_x000D_
  align-self: end;_x000D_
}_x000D_
_x000D_
/* Extra Styling for Snippet */_x000D_
_x000D_
#parent {_x000D_
  height: 150px;_x000D_
  background: #5548B0;_x000D_
  color: #fff;_x000D_
  padding: 10px;_x000D_
  font-family: sans-serif;_x000D_
}_x000D_
_x000D_
#child1 {_x000D_
  height: 50px;_x000D_
  width: 50px;_x000D_
  background: #6A67CE;_x000D_
  text-align: center;_x000D_
  vertical-align: middle;_x000D_
  line-height: 50px;_x000D_
}
_x000D_
<div id="parent">_x000D_
  <!-- Other elements here -->_x000D_
  <div id="child1">_x000D_
    1_x000D_
  </div>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

'this' vs $scope in AngularJS controllers

I just read a pretty interesting explanation on the difference between the two, and a growing preference to attach models to the controller and alias the controller to bind models to the view. http://toddmotto.com/digging-into-angulars-controller-as-syntax/ is the article.

NOTE: The original link still exists, but changes in formatting have made it hard to read. It's easier to view in the original.

He doesn't mention it but when defining directives, if you need to share something between multiple directives and don't want a service (there are legitimate cases where services are a hassle) then attach the data to the parent directive's controller.

The $scope service provides plenty of useful things, $watch being the most obvious, but if all you need to bind data to the view, using the plain controller and 'controller as' in the template is fine and arguably preferable.

How to check if a "lateinit" variable has been initialized?

If you have a lateinit property in one class and need to check if it is initialized from another class

if(foo::file.isInitialized) // this wouldn't work

The workaround I have found is to create a function to check if the property is initialized and then you can call that function from any other class.

Example:

class Foo() {

    private lateinit var myFile: File

    fun isFileInitialised() = ::file.isInitialized
}

 // in another class
class Bar() {

    val foo = Foo()

    if(foo.isFileInitialised()) // this should work
}

Get file content from URL?

Depending on your PHP configuration, this may be a easy as using:

$jsonData = json_decode(file_get_contents('https://chart.googleapis.com/chart?cht=p3&chs=250x100&chd=t:60,40&chl=Hello|World&chof=json'));

However, if allow_url_fopen isn't enabled on your system, you could read the data via CURL as follows:

<?php
    $curlSession = curl_init();
    curl_setopt($curlSession, CURLOPT_URL, 'https://chart.googleapis.com/chart?cht=p3&chs=250x100&chd=t:60,40&chl=Hello|World&chof=json');
    curl_setopt($curlSession, CURLOPT_BINARYTRANSFER, true);
    curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, true);

    $jsonData = json_decode(curl_exec($curlSession));
    curl_close($curlSession);
?>

Incidentally, if you just want the raw JSON data, then simply remove the json_decode.

How to create a GUID/UUID in Python

Copied from : https://docs.python.org/2/library/uuid.html (Since the links posted were not active and they keep updating)

>>> import uuid

>>> # make a UUID based on the host ID and current time
>>> uuid.uuid1()
UUID('a8098c1a-f86e-11da-bd1a-00112444be1e')

>>> # make a UUID using an MD5 hash of a namespace UUID and a name
>>> uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org')
UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e')

>>> # make a random UUID
>>> uuid.uuid4()
UUID('16fd2706-8baf-433b-82eb-8c7fada847da')

>>> # make a UUID using a SHA-1 hash of a namespace UUID and a name
>>> uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org')
UUID('886313e1-3b8a-5372-9b90-0c9aee199e5d')

>>> # make a UUID from a string of hex digits (braces and hyphens ignored)
>>> x = uuid.UUID('{00010203-0405-0607-0809-0a0b0c0d0e0f}')

>>> # convert a UUID to a string of hex digits in standard form
>>> str(x)
'00010203-0405-0607-0809-0a0b0c0d0e0f'

>>> # get the raw 16 bytes of the UUID
>>> x.bytes
'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f'

>>> # make a UUID from a 16-byte string
>>> uuid.UUID(bytes=x.bytes)
UUID('00010203-0405-0607-0809-0a0b0c0d0e0f')

Best/Most Comprehensive API for Stocks/Financial Data

Yahoo's api provides a CSV dump:

Example: http://finance.yahoo.com/d/quotes.csv?s=msft&f=price

I'm not sure if it is documented or not, but this code sample should showcase all of the features (namely the stat types [parameter f in the query string]. I'm sure you can find documentation (official or not) if you search for it.

http://www.goldb.org/ystockquote.html

Edit

I found some unofficial documentation:

http://ilmusaham.wordpress.com/tag/stock-yahoo-data/

Get startup type of Windows service using PowerShell

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

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

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

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

How do you auto format code in Visual Studio?

Visual Studio Extension - CodeMaid is pretty fine.

Check if starting characters of a string are alphabetical in T-SQL

You don't need to use regex, LIKE is sufficient:

WHERE my_field LIKE '[a-zA-Z][a-zA-Z]%'

Assuming that by "alphabetical" you mean only latin characters, not anything classified as alphabetical in Unicode.

Note - if your collation is case sensitive, it's important to specify the range as [a-zA-Z]. [a-z] may exclude A or Z. [A-Z] may exclude a or z.

Find all files with name containing string

The -maxdepth option should be before the -name option, like below.,

find . -maxdepth 1 -name "string" -print

Telegram Bot - how to get a group chat id?

As of March 2020, simply:

  • Invite @RawDataBot to your group.

Upon joining it will output a JSON file where your chat id will be located at message.chat.id.

"message": {
    "chat": {
        "id": -210987654,
        "title": ...,
        "type": "group",
        ...
    }
    ...
}

Be sure to kick @RawDataBot from your group afterwards.

How to expand/collapse a diff sections in Vimdiff?

set vimdiff to ignore case

Having started vim diff with

 gvim -d main.sql backup.sql &

I find that annoyingly one file has MySQL keywords in lowercase the other uppercase showing differences on practically every other line

:set diffopt+=icase

this updates the screen dynamically & you can just as easily switch it off again

How to remove focus from single editText

<EditText android:layout_height="wrap_content" android:background="@android:color/transparent" android:layout_width="match_parent" 
    android:clickable="false"
     android:focusable="false"
     android:textSize="40dp"
     android:textAlignment="center" 
    android:textStyle="bold"  
    android:textAppearance="@style/Base.Theme.AppCompat.Light.DarkActionBar" 
   android:text="AVIATORS"/>

Android SeekBar setOnSeekBarChangeListener

I hope this will help you:

final TextView t1=new TextView(this); 
t1.setText("Hello Android");        
final SeekBar sk=(SeekBar) findViewById(R.id.seekBar1);     
sk.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {       

    @Override       
    public void onStopTrackingTouch(SeekBar seekBar) {      
        // TODO Auto-generated method stub      
    }       

    @Override       
    public void onStartTrackingTouch(SeekBar seekBar) {     
        // TODO Auto-generated method stub      
    }       

    @Override       
    public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {     
        // TODO Auto-generated method stub      

        t1.setTextSize(progress);
        Toast.makeText(getApplicationContext(), String.valueOf(progress),Toast.LENGTH_LONG).show();

    }       
});             

How can I alias a default import in JavaScript?

defaultMember already is an alias - it doesn't need to be the name of the exported function/thing. Just do

import alias from 'my-module';

Alternatively you can do

import {default as alias} from 'my-module';

but that's rather esoteric.

Ways to eliminate switch in code

Function pointers are one way to replace a huge chunky switch statement, they are especially good in languages where you can capture functions by their names and make stuff with them.

Of course, you ought not force switch statements out of your code, and there always is a chance you are doing it all wrong, which results with stupid redundant pieces of code. (This is unavoidable sometimes, but a good language should allow you to remove redundancy while staying clean.)

This is a great divide&conquer example:

Say you have an interpreter of some sort.

switch(*IP) {
    case OPCODE_ADD:
        ...
        break;
    case OPCODE_NOT_ZERO:
        ...
        break;
    case OPCODE_JUMP:
        ...
        break;
    default:
        fixme(*IP);
}

Instead, you can use this:

opcode_table[*IP](*IP, vm);

... // in somewhere else:
void opcode_add(byte_opcode op, Vm* vm) { ... };
void opcode_not_zero(byte_opcode op, Vm* vm) { ... };
void opcode_jump(byte_opcode op, Vm* vm) { ... };
void opcode_default(byte_opcode op, Vm* vm) { /* fixme */ };

OpcodeFuncPtr opcode_table[256] = {
    ...
    opcode_add,
    opcode_not_zero,
    opcode_jump,
    opcode_default,
    opcode_default,
    ... // etc.
};

Note that I don't know how to remove the redundancy of the opcode_table in C. Perhaps I should make a question about it. :)

Example of AES using Crypto++

Official document of Crypto++ AES is a good start. And from my archive, a basic implementation of AES is as follows:

Please refer here with more explanation, I recommend you first understand the algorithm and then try to understand each line step by step.

#include <iostream>
#include <iomanip>

#include "modes.h"
#include "aes.h"
#include "filters.h"

int main(int argc, char* argv[]) {

    //Key and IV setup
    //AES encryption uses a secret key of a variable length (128-bit, 196-bit or 256-   
    //bit). This key is secretly exchanged between two parties before communication   
    //begins. DEFAULT_KEYLENGTH= 16 bytes
    CryptoPP::byte key[ CryptoPP::AES::DEFAULT_KEYLENGTH ], iv[ CryptoPP::AES::BLOCKSIZE ];
    memset( key, 0x00, CryptoPP::AES::DEFAULT_KEYLENGTH );
    memset( iv, 0x00, CryptoPP::AES::BLOCKSIZE );

    //
    // String and Sink setup
    //
    std::string plaintext = "Now is the time for all good men to come to the aide...";
    std::string ciphertext;
    std::string decryptedtext;

    //
    // Dump Plain Text
    //
    std::cout << "Plain Text (" << plaintext.size() << " bytes)" << std::endl;
    std::cout << plaintext;
    std::cout << std::endl << std::endl;

    //
    // Create Cipher Text
    //
    CryptoPP::AES::Encryption aesEncryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
    CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption( aesEncryption, iv );

    CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink( ciphertext ) );
    stfEncryptor.Put( reinterpret_cast<const unsigned char*>( plaintext.c_str() ), plaintext.length() );
    stfEncryptor.MessageEnd();

    //
    // Dump Cipher Text
    //
    std::cout << "Cipher Text (" << ciphertext.size() << " bytes)" << std::endl;

    for( int i = 0; i < ciphertext.size(); i++ ) {

        std::cout << "0x" << std::hex << (0xFF & static_cast<CryptoPP::byte>(ciphertext[i])) << " ";
    }

    std::cout << std::endl << std::endl;

    //
    // Decrypt
    //
    CryptoPP::AES::Decryption aesDecryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
    CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption( aesDecryption, iv );

    CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( decryptedtext ) );
    stfDecryptor.Put( reinterpret_cast<const unsigned char*>( ciphertext.c_str() ), ciphertext.size() );
    stfDecryptor.MessageEnd();

    //
    // Dump Decrypted Text
    //
    std::cout << "Decrypted Text: " << std::endl;
    std::cout << decryptedtext;
    std::cout << std::endl << std::endl;

    return 0;
}

For installation details :

sudo apt-get install libcrypto++-dev libcrypto++-doc libcrypto++-utils

Get img thumbnails from Vimeo?

From the Vimeo Simple API docs:

Making a Video Request

To get data about a specific video, use the following url:

http://vimeo.com/api/v2/video/video_id.output

video_id The ID of the video you want information for.

output Specify the output type. We currently offer JSON, PHP, and XML formats.

So getting this URL http://vimeo.com/api/v2/video/6271487.xml

    <videos> 
      <video> 
        [skipped]
        <thumbnail_small>http://ts.vimeo.com.s3.amazonaws.com/235/662/23566238_100.jpg</thumbnail_small> 
        <thumbnail_medium>http://ts.vimeo.com.s3.amazonaws.com/235/662/23566238_200.jpg</thumbnail_medium> 
        <thumbnail_large>http://ts.vimeo.com.s3.amazonaws.com/235/662/23566238_640.jpg</thumbnail_large> 
        [skipped]
    </videos>

Parse this for every video to get the thumbnail

Here's approximate code in PHP

<?php

$imgid = 6271487;

$hash = unserialize(file_get_contents("http://vimeo.com/api/v2/video/$imgid.php"));

echo $hash[0]['thumbnail_medium'];  

Using Camera in the Android emulator

Some elaboration, in the hope of clarifying what has already been said:

As stated above, Webcams are supported natively in the current SDK, but only on recent android versions (4.0 and higher)

Webcam detection is automatic where present. In 4.0.3, the camera defaults to the front-facing camera so a lot of applications (especially pre-2.3 applications, which can only fetch the default camera, i.e. the back-facing one) will still show you the old checkerbox-with-moving-square stand-in instead.

I think some more info is available in the following post: Camera on Android Eclipse emulator:

Or at least, that's the most information I've been able to find--aside from the brief, uninformative statements in the release notes for the SDK tools.

PATH issue with pytest 'ImportError: No module named YadaYadaYada'

I got this error as I used relative imports incorrectly. In the OP example, test_app.py should import functions using e.g.

from repo.app import *

However liberally __init__.py files are scattered around the file structure, this does not work and creates the kind of ImportError seen unless the files and test files are in the same directory.

from app import *

Here's an example of what I had to do with one of my projects:

Here’s my project structure:

microbit/
microbit/activity_indicator/activity_indicator.py
microbit/tests/test_activity_indicator.py

To be able to access activity_indicator.py from test_activity_indicator.py I needed to:

  • start test_activity_indicatory.py with the correct relative import:
    from microbit.activity_indicator.activity_indicator import *
  • put __init__.py files throughout the project structure:
    microbit/
    microbit/__init__.py
    microbit/activity_indicator/__init__.py
    microbit/activity_indicator/activity_indicator.py
    microbit/tests/__init__.py
    microbit/tests/test_activity_indicator.py