Programs & Examples On #Non printable

Stripping non printable characters from a string in python

Yet another option in python 3:

re.sub(f'[^{re.escape(string.printable)}]', '', my_string)

CSS3 Transition - Fade out effect

Here is another way to do the same.

fadeIn effect

.visible {
  visibility: visible;
  opacity: 1;
  transition: opacity 2s linear;
}

fadeOut effect

.hidden {
  visibility: hidden;
  opacity: 0;
  transition: visibility 0s 2s, opacity 2s linear;
}

UPDATE 1: I found more up-to-date tutorial CSS3 Transition: fadeIn and fadeOut like effects to hide show elements and Tooltip Example: Show Hide Hint or Help Text using CSS3 Transition here with sample code.

UPDATE 2: (Added details requested by @big-money)

When showing the element (by switching to the visible class), we want the visibility:visible to kick in instantly, so it’s ok to transition only the opacity property. And when hiding the element (by switching to the hidden class), we want to delay the visibility:hidden declaration, so that we can see the fade-out transition first. We’re doing this by declaring a transition on the visibility property, with a 0s duration and a delay. You can see a detailed article here.

I know I am too late to answer but posting this answer to save others time. Hope it helps you!!

How to select Multiple images from UIImagePickerController

You can't use UIImagePickerController, but you can use a custom image picker. I think ELCImagePickerController is the best option, but here are some other libraries you could use:

Objective-C
1. ELCImagePickerController
2. WSAssetPickerController
3. QBImagePickerController
4. ZCImagePickerController
5. CTAssetsPickerController
6. AGImagePickerController
7. UzysAssetsPickerController
8. MWPhotoBrowser
9. TSAssetsPickerController
10. CustomImagePicker
11. InstagramPhotoPicker
12. GMImagePicker
13. DLFPhotosPicker
14. CombinationPickerController
15. AssetPicker
16. BSImagePicker
17. SNImagePicker
18. DoImagePickerController
19. grabKit
20. IQMediaPickerController
21. HySideScrollingImagePicker
22. MultiImageSelector
23. TTImagePicker
24. SelectImages
25. ImageSelectAndSave
26. imagepicker-multi-select
27. MultiSelectImagePickerController
28. YangMingShan(Yahoo like image selector)
29. DBAttachmentPickerController
30. BRImagePicker
31. GLAssetGridViewController
32. CreolePhotoSelection

Swift
1. LimPicker (Similar to WhatsApp's image picker)
2. RMImagePicker
3. DKImagePickerController
4. BSImagePicker
5. Fusuma(Instagram like image selector)
6. YangMingShan(Yahoo like image selector)
7. NohanaImagePicker
8. ImagePicker
9. OpalImagePicker
10. TLPhotoPicker
11. AssetsPickerViewController
12. Alerts-and-pickers/Telegram Picker

Thanx to @androidbloke,
I have added some library that I know for multiple image picker in swift.
Will update list as I find new ones.
Thank You.

Regular expression to match characters at beginning of line only

Not sure how to apply that to your file on your server, but typically, the regex to match the beginning of a string would be :

^CTR


The ^ means beginning of string / line

Reading text files using read.table

From ?read.table: The number of data columns is determined by looking at the first five lines of input (or the whole file if it has less than five lines), or from the length of col.names if it is specified and is longer. This could conceivably be wrong if fill or blank.lines.skip are true, so specify col.names if necessary.

So, perhaps your data file isn't clean. Being more specific will help the data import:

d = read.table("foobar.txt", 
               sep="\t", 
               col.names=c("id", "name"), 
               fill=FALSE, 
               strip.white=TRUE)

will specify exact columns and fill=FALSE will force a two column data frame.

How to check if a file exists in a shell script

Internally, the rm command must test for file existence anyway,
so why add another test? Just issue

rm filename

and it will be gone after that, whether it was there or not.
Use rm -f is you don't want any messages about non-existent files.

If you need to take some action if the file does NOT exist, then you must test for that yourself. Based on your example code, this is not the case in this instance.

Convenient C++ struct initialisation

For versions of C++ prior to C++20 (which introduces the named initialization, making your option A valid in C++), consider the following:

int main()
{
    struct TFoo { int val; };
    struct TBar { float val; };

    struct FooBar {
        TFoo foo;
        TBar bar;
    };

    FooBar mystruct = { TFoo{12}, TBar{3.4} };

    std::cout << "foo = " << mystruct.foo.val << " bar = " << mystruct.bar.val << std::endl;

}

Note that if you try to initialize the struct with FooBar mystruct = { TFoo{12}, TFoo{3.4} }; you will get a compilation error.

The downside is that you have to create one additional struct for each variable inside your main struct, and also you have to use the inner value with mystruct.foo.val. But on the other hand, it`s clean, simple, pure and standard.

Chrome dev tools fails to show response even the content returned has header Content-Type:text/html; charset=UTF-8

"Failed to show response data" can also happen if you are doing crossdomain requests and the remote host is not properly handling the CORS headers. Check your js console for errors.

Convert HTML + CSS to PDF

This question is pretty old already, but haven't seen anyone mentioning CutyCapt so I will :)

CutyCapt

CutyCapt is a small cross-platform command-line utility to capture WebKit's rendering of a web page into a variety of vector and bitmap formats, including SVG, PDF, PS, PNG, JPEG, TIFF, GIF, and BMP

Pandas read_sql with parameters

The read_sql docs say this params argument can be a list, tuple or dict (see docs).

To pass the values in the sql query, there are different syntaxes possible: ?, :1, :name, %s, %(name)s (see PEP249).
But not all of these possibilities are supported by all database drivers, which syntax is supported depends on the driver you are using (psycopg2 in your case I suppose).

In your second case, when using a dict, you are using 'named arguments', and according to the psycopg2 documentation, they support the %(name)s style (and so not the :name I suppose), see http://initd.org/psycopg/docs/usage.html#query-parameters.
So using that style should work:

df = psql.read_sql(('select "Timestamp","Value" from "MyTable" '
                     'where "Timestamp" BETWEEN %(dstart)s AND %(dfinish)s'),
                   db,params={"dstart":datetime(2014,6,24,16,0),"dfinish":datetime(2014,6,24,17,0)},
                   index_col=['Timestamp'])

Docker container not starting (docker start)

What I need is to use Docker with MariaDb on different port /3301/ on my Ubuntu machine because I already had MySql installed and running on 3306.

To do this after half day searching did it using:

docker run -it -d -p 3301:3306 -v ~/mdbdata/mariaDb:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=root --name mariaDb mariadb

This pulls the image with latest MariaDb, creates container called mariaDb, and run mysql on port 3301. All data of which is located in home directory in /mdbdata/mariaDb.

To login in mysql after that can use:

mysql -u root -proot -h 127.0.0.1 -P3301

Used sources are:

The answer of Iarks in this article /using -it -d was the key :) /

how-to-install-and-use-docker-on-ubuntu-16-04

installing-and-using-mariadb-via-docker

mariadb-and-docker-use-cases-part-1

Good luck all!

SOAP-ERROR: Parsing WSDL: Couldn't load from - but works on WAMP

It may be helpful for someone, although there is no precise answer to this question.

My soap url has a non-standard port(9087 for example), and firewall blocked that request and I took each time this error:

ERROR - 2017-12-19 20:44:11 --> Fatal Error - SOAP-ERROR: Parsing WSDL: Couldn't load from 'http://soalurl.test:9087/orawsv?wsdl' : failed to load external entity "http://soalurl.test:9087/orawsv?wsdl"

I allowed port in firewall and solved the error!

Wait for async task to finish

This will never work, because the JS VM has moved on from that async_call and returned the value, which you haven't set yet.

Don't try to fight what is natural and built-in the language behaviour. You should use a callback technique or a promise.

function f(input, callback) {
    var value;

    // Assume the async call always succeed
    async_call(input, function(result) { callback(result) };

}

The other option is to use a promise, have a look at Q. This way you return a promise, and then you attach a then listener to it, which is basically the same as a callback. When the promise resolves, the then will trigger.

How do you make a LinearLayout scrollable?

Here is how I did it by trial and error.

ScrollView - (the outer wrapper).

    LinearLayout (child-1).

        LinearLayout (child-1a).

        LinearLayout (child-1b).

Since ScrollView can have only one child, that child is a linear layout. Then all the other layout types occur in the first linear layout. I haven't tried to include a relative layout yet, but they drive me nuts so I will wait until my sanity returns.

Using python map and other functional tools

Are you familiar with other functional languages? i.e. are you trying to learn how python does functional programming, or are you trying to learn about functional programming and using python as the vehicle?

Also, do you understand list comprehensions?

map(f, sequence)

is directly equivalent (*) to:

[f(x) for x in sequence]

In fact, I think map() was once slated for removal from python 3.0 as being redundant (that didn't happen).

map(f, sequence1, sequence2)

is mostly equivalent to:

[f(x1, x2) for x1, x2 in zip(sequence1, sequence2)]

(there is a difference in how it handles the case where the sequences are of different length. As you saw, map() fills in None when one of the sequences runs out, whereas zip() stops when the shortest sequence stops)

So, to address your specific question, you're trying to produce the result:

foos[0], bars
foos[1], bars
foos[2], bars
# etc.

You could do this by writing a function that takes a single argument and prints it, followed by bars:

def maptest(x):
     print x, bars
map(maptest, foos)

Alternatively, you could create a list that looks like this:

[bars, bars, bars, ] # etc.

and use your original maptest:

def maptest(x, y):
    print x, y

One way to do this would be to explicitely build the list beforehand:

barses = [bars] * len(foos)
map(maptest, foos, barses)

Alternatively, you could pull in the itertools module. itertools contains many clever functions that help you do functional-style lazy-evaluation programming in python. In this case, we want itertools.repeat, which will output its argument indefinitely as you iterate over it. This last fact means that if you do:

map(maptest, foos, itertools.repeat(bars))

you will get endless output, since map() keeps going as long as one of the arguments is still producing output. However, itertools.imap is just like map(), but stops as soon as the shortest iterable stops.

itertools.imap(maptest, foos, itertools.repeat(bars))

Hope this helps :-)

(*) It's a little different in python 3.0. There, map() essentially returns a generator expression.

Converting Select results into Insert script - SQL Server

It's possible to do via Visual Studio SQL Server Object Explorer.

You can click "View Data" from context menu for necessary table, filter results and save result as script.

MS Excel showing the formula in a cell instead of the resulting value

I tried everything I could find but nothing worked. Then I highlighted the formula column and right-clicked and selected 'clear contents'. That worked! Now I see the results, not the formula.

Variably modified array at file scope

The reason for this warning is that const in c doesn't mean constant. It means "read only". So the value is stored at a memory address and could potentially be changed by machine code.

Visual Studio Code always asking for git credentials

Try installing "Git Credential Manager For Windows" (and following instructions for setting up the credential manager).

When required within an app using Git (e.g. VS Code) it will "magically" open the required dialog for Visual Studio Team Services credential input.

iOS how to set app icon and launch images

I use a tool called Prepo to produce all the right image sizes. You simply feed the app you image file and it will spit out each necessary file with an appropriate name.

Once you do this, you can then drag in the appropriate files or simply point to your Prepo exported folder.

Selenium WebDriver: I want to overwrite value in field instead of appending to it with sendKeys using Java

Use the following:

driver.findElement(By.id("id")).sendKeys(Keys.chord(Keys.CONTROL, "a", Keys.DELETE), "Your Value");

Getting the docstring from a function

You can also use inspect.getdoc. It cleans up the __doc__ by normalizing tabs to spaces and left shifting the doc body to remove common leading spaces.

Why is vertical-align:text-top; not working in CSS

The all above not work for me, I have just checked this and its work :

vertical-align: super;

 <div id="lbk_mng_rdooption" style="float: left;">
     <span class="bold" style="vertical-align: super;">View:</span>
 </div>

I know by padding or margin will work, but that is last choise I prefer.

Disposing WPF User Controls

I use the following Interactivity Behavior to provide an unloading event to WPF UserControls. You can include the behavior in the UserControls XAML. So you can have the functionality without placing the logic it in every single UserControl.

XAML declaration:

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"

<i:Interaction.Behaviors>
    <behaviors:UserControlSupportsUnloadingEventBehavior UserControlClosing="UserControlClosingHandler" />
</i:Interaction.Behaviors>

CodeBehind handler:

private void UserControlClosingHandler(object sender, EventArgs e)
{
    // to unloading stuff here
}

Behavior Code:

/// <summary>
/// This behavior raises an event when the containing window of a <see cref="UserControl"/> is closing.
/// </summary>
public class UserControlSupportsUnloadingEventBehavior : System.Windows.Interactivity.Behavior<UserControl>
{
    protected override void OnAttached()
    {
        AssociatedObject.Loaded += UserControlLoadedHandler;
    }

    protected override void OnDetaching()
    {
        AssociatedObject.Loaded -= UserControlLoadedHandler;
        var window = Window.GetWindow(AssociatedObject);
        if (window != null)
            window.Closing -= WindowClosingHandler;
    }

    /// <summary>
    /// Registers to the containing windows Closing event when the UserControl is loaded.
    /// </summary>
    private void UserControlLoadedHandler(object sender, RoutedEventArgs e)
    {
        var window = Window.GetWindow(AssociatedObject);
        if (window == null)
            throw new Exception(
                "The UserControl {0} is not contained within a Window. The UserControlSupportsUnloadingEventBehavior cannot be used."
                    .FormatWith(AssociatedObject.GetType().Name));

        window.Closing += WindowClosingHandler;
    }

    /// <summary>
    /// The containing window is closing, raise the UserControlClosing event.
    /// </summary>
    private void WindowClosingHandler(object sender, CancelEventArgs e)
    {
        OnUserControlClosing();
    }

    /// <summary>
    /// This event will be raised when the containing window of the associated <see cref="UserControl"/> is closing.
    /// </summary>
    public event EventHandler UserControlClosing;

    protected virtual void OnUserControlClosing()
    {
        var handler = UserControlClosing;
        if (handler != null) 
            handler(this, EventArgs.Empty);
    }
}

Set Google Maps Container DIV width and height 100%

Very few people realize the power of css positioning. To set the map to occupy 100% height of it's parent container do following:

#map_canvas_container {position: relative;}

#map_canvas {position: absolute; top: 0; right: 0; bottom: 0; left: 0;}

If you have any non absolutely positioned elements inside #map_canvas_container they will set the height of it and the map will take the exact available space.

Google Maps: how to get country, state/province/region, city given a lat/long value?

I've created a small mapper function:

private getAddressParts(object): Object {
    let address = {};
    const address_components = object.address_components;
    address_components.forEach(element => {
        address[element.types[0]] = element.short_name;
    });
    return address;
}

It's a solution for Angular 4 but I think you'll get the idea.

Usage:

geocoder.geocode({ 'location' : latlng }, (results, status) => {
    if (status === google.maps.GeocoderStatus.OK) {
        const address = {
            formatted_address: results[0].formatted_address,
            address_parts: this.getAddressParts(results[0])
        };
        (....)
    }

This way the address object will be something like this:

address: {
    address_parts: {
        administrative_area_level_1: "NY",
        administrative_area_level_2: "New York County",
        country: "US",
        locality: "New York",
        neighborhood: "Lower Manhattan",
        political: "Manhattan",
        postal_code: "10038",
        route: "Beekman St",
        street_number: "90",
    },
    formatted_address: "90 Beekman St, New York, NY 10038, USA"
}

Hope it helps!

How do I download a file from the internet to my linux server with Bash

Using wget

wget -O /tmp/myfile 'http://www.google.com/logo.jpg'

or curl:

curl -o /tmp/myfile 'http://www.google.com/logo.jpg'

Check whether a path is valid

There are plenty of good solutions in here, but as none of then check if the path is rooted in an existing drive here's another one:

private bool IsValidPath(string path)
{
    // Check if the path is rooted in a driver
    if (path.Length < 3) return false;
    Regex driveCheck = new Regex(@"^[a-zA-Z]:\\$");
    if (!driveCheck.IsMatch(path.Substring(0, 3))) return false;

    // Check if such driver exists
    IEnumerable<string> allMachineDrivers = DriveInfo.GetDrives().Select(drive => drive.Name);
    if (!allMachineDrivers.Contains(path.Substring(0, 3))) return false;

    // Check if the rest of the path is valid
    string InvalidFileNameChars = new string(Path.GetInvalidPathChars());
    InvalidFileNameChars += @":/?*" + "\"";
    Regex containsABadCharacter = new Regex("[" + Regex.Escape(InvalidFileNameChars) + "]");
    if (containsABadCharacter.IsMatch(path.Substring(3, path.Length - 3)))
        return false;
    if (path[path.Length - 1] == '.') return false;

    return true;
}

This solution does not take relative paths into account.

How to get the previous page URL using JavaScript?

You want in page A to know the URL of page B?

Or to know in page B the URL of page A?

In Page B: document.referrer if set. As already shown here: How to get the previous URL in JavaScript?

In page A you would need to read a cookie or local/sessionStorage you set in page B, assuming the same domains

How to pick just one item from a generator?

You can pick specific items using destructuring, e.g.:

>>> [first, *middle, last] = range(10)
>>> first
0
>>> middle
[1, 2, 3, 4, 5, 6, 7, 8]
>>> last
9

Note that this is going to consume your generator, so while highly readable, it is less efficient than something like next(), and ruinous on infinite generators:

>>> [first, *rest] = itertools.count()

How to create python bytes object from long hex string?

result = bytes.fromhex(some_hex_string)

Move to another EditText when Soft Keyboard Next is clicked on Android

In Kotlin I have used Bellow like..

  1. xml:

    <EditText
      android:id="@+id/et_amount"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:imeOptions="actionNext"
      android:inputType="number"
      android:singleLine="true" />
    
  2. in kotlin:

    et_amount.setOnEditorActionListener { v, actionId, event ->
    
        if (actionId == EditorInfo.IME_ACTION_NEXT) {
            // do some code
            true
        } else {
            false
        }
    }
    

How do I extract Month and Year in a MySQL date and compare them?

SELECT * FROM Table_name Where Month(date)='10' && YEAR(date)='2016';

Could not create the Java virtual machine

I had this issue today, and for me the problem was that I had allocated too much memory:

-Xmx1024M -XX:MaxPermSize=1024m

Once I reduced the PermGen space, everything worked fine:

-Xmx1024M -XX:MaxPermSize=512m

I know that doesn't look like much of a difference, but my machine only has 4GB of RAM, and apparently that was the straw that broke the camel's back. The Java VM was failing immediately upon every action because it was failing to allocate the memory.

How to move screen without moving cursor in Vim?

I'm surprised no one is using the Scrolloff option which keeps the cursor in the middle of the page. Try it with:

:set so=999

It's the first recommended method on the Vim wiki and works well.

Counting the number of True Booleans in a Python List

Just for completeness' sake (sum is usually preferable), I wanted to mention that we can also use filter to get the truthy values. In the usual case, filter accepts a function as the first argument, but if you pass it None, it will filter for all "truthy" values. This feature is somewhat surprising, but is well documented and works in both Python 2 and 3.

The difference between the versions, is that in Python 2 filter returns a list, so we can use len:

>>> bool_list = [True, True, False, False, False, True]
>>> filter(None, bool_list)
[True, True, True]
>>> len(filter(None, bool_list))
3

But in Python 3, filter returns an iterator, so we can't use len, and if we want to avoid using sum (for any reason) we need to resort to converting the iterator to a list (which makes this much less pretty):

>>> bool_list = [True, True, False, False, False, True]
>>> filter(None, bool_list)
<builtins.filter at 0x7f64feba5710>
>>> list(filter(None, bool_list))
[True, True, True]
>>> len(list(filter(None, bool_list)))
3

How do I clear the previous text field value after submitting the form with out refreshing the entire page?

Assign empty value:

document.getElementById('numquest').value=null;

or, if want to clear all form fields. Just call form reset method as:

document.forms['form_name'].reset()

JSON forEach get Key and Value

Assuming that obj is a pre-constructed object (and not a JSON string), you can achieve this with the following:

Object.keys(obj).forEach(function(key){
   console.log(key + '=' + obj[key]);
});

What is the difference between dynamic and static polymorphism in Java?

Static Polymorphism: is where the decision to resolve which method to accomplish, is determined during the compile time. Method Overloading could be an example of this.

Dynamic Polymorphism: is where the decision to choose which method to execute, is set during the run-time. Method Overriding could be an example of this.

How do I detect unsigned integer multiply overflow?

mozilla::CheckedInt<T> provides overflow-checked integer math for integer type T (using compiler intrinsics on clang and gcc as available). The code is under MPL 2.0 and depends on three (IntegerTypeTraits.h, Attributes.h and Compiler.h) other header-only non-standard library headers plus Mozilla-specific assertion machinery. You probably want to replace the assertion machinery if you import the code.

Get first element in PHP stdObject

Update PHP 7.4

Curly brace access syntax is deprecated since PHP 7.4

Update 2019

Moving on to the best practices of OOPS, @MrTrick's answer must be marked as correct, although my answer provides a hacked solution its not the best method.

Simply iterate its using {}

Example:

$videos{0}->id

This way your object is not destroyed and you can easily iterate through object.

For PHP 5.6 and below use this

$videos{0}['id']

Both array() and the stdClass objects can be accessed using the current() key() next() prev() reset() end() functions.

So, if your object looks like

object(stdClass)#19 (3) {
  [0]=>
  object(stdClass)#20 (22) {
    ["id"]=>
    string(1) "123"
  etc...

Then you can just do;

$id = reset($obj)->id; //Gets the 'id' attr of the first entry in the object

If you need the key for some reason, you can do;

reset($obj); //Ensure that we're at the first element
$key = key($obj);

Hope that works for you. :-) No errors, even in super-strict mode, on PHP 5.4


2022 Update:
After PHP 7.4, using current(), end(), etc functions on objects is deprecated.

In newer versions of PHP, use the ArrayIterator class:

$objIterator = new ArrayIterator($obj);

$id = $objIterator->current()->id; // Gets the 'id' attr of the first entry in the object

$key = $objIterator->key(); // and gets the key

When should I use curly braces for ES6 import?

  • If there is any default export in the file, there isn't any need to use the curly braces in the import statement.

  • if there are more than one export in the file then we need to use curly braces in the import file so that which are necessary we can import.

  • You can find the complete difference when to use curly braces and default statement in the below YouTube video (very heavy Indian accent, including rolling on the r's...).

    21. ES6 Modules. Different ways of using import/export, Default syntax in the code. ES6 | ES2015

Set Matplotlib colorbar size to match graph

This combination (and values near to these) seems to "magically" work for me to keep the colorbar scaled to the plot, no matter what size the display.

plt.colorbar(im,fraction=0.046, pad=0.04)

It also does not require sharing the axis which can get the plot out of square.

How can I switch to a tag/branch in hg?

Once you have cloned the repo, you have everything: you can then hg up branchname or hg up tagname to update your working copy.

UP: hg up is a shortcut of hg update, which also has hg checkout alias for people with git habits.

How can I interrupt a running code in R with a keyboard command?

Try out Ctrl + z But it will kill the process, not suspend it.

What is a smart pointer and when should I use one?

http://en.wikipedia.org/wiki/Smart_pointer

In computer science, a smart pointer is an abstract data type that simulates a pointer while providing additional features, such as automatic garbage collection or bounds checking. These additional features are intended to reduce bugs caused by the misuse of pointers while retaining efficiency. Smart pointers typically keep track of the objects that point to them for the purpose of memory management. The misuse of pointers is a major source of bugs: the constant allocation, deallocation and referencing that must be performed by a program written using pointers makes it very likely that some memory leaks will occur. Smart pointers try to prevent memory leaks by making the resource deallocation automatic: when the pointer to an object (or the last in a series of pointers) is destroyed, for example because it goes out of scope, the pointed object is destroyed too.

Python variables as keys to dict

for i in ('apple', 'banana', 'carrot'):
    fruitdict[i] = locals()[i]

React - How to force a function component to render?

Disclaimer: NOT AN ANSWER TO THE PROBLEM.

Leaving an Important note here:

If you are trying to forceupdate a stateless component, chances are there is something wrong with your design.

Consider the following cases:

  1. Pass a setter (setState) to a child component that can change state and cause the parent component to re-render.
  2. Consider lifting state up
  3. Consider putting that state in your Redux store, that can automatically force a re-render on connected components.

How to check for file existence

# file? will only return true for files
File.file?(filename)

and

# Will also return true for directories - watch out!
File.exist?(filename)

How do I erase an element from std::vector<> by index?

The erase method will be used in two ways:

  1. Erasing single element:

    vector.erase( vector.begin() + 3 ); // Deleting the fourth element
    
  2. Erasing range of elements:

    vector.erase( vector.begin() + 3, vector.begin() + 5 ); // Deleting from fourth element to sixth element
    

3 column layout HTML/CSS

This is less for @easwee and more for others that might have the same question:

If you do not require support for IE < 10, you can use Flexbox. It's an exciting CSS3 property that unfortunately was implemented in several different versions,; add in vendor prefixes, and getting good cross-browser support suddenly requires quite a few more properties than it should.

With the current, final standard, you would be done with

.container {
    display: flex;
}

.container div {
    flex: 1;
}

.column_center {
    order: 2;
}

That's it. If you want to support older implementations like iOS 6, Safari < 6, Firefox 19 or IE10, this blossoms into

.container {
    display: -webkit-box;      /* OLD - iOS 6-, Safari 3.1-6 */
    display: -moz-box;         /* OLD - Firefox 19- (buggy but mostly works) */
    display: -ms-flexbox;      /* TWEENER - IE 10 */
    display: -webkit-flex;     /* NEW - Chrome */
    display: flex;             /* NEW, Spec - Opera 12.1, Firefox 20+ */
}

.container div {
    -webkit-box-flex: 1;      /* OLD - iOS 6-, Safari 3.1-6 */
    -moz-box-flex: 1;         /* OLD - Firefox 19- */
    -webkit-flex: 1;          /* Chrome */
    -ms-flex: 1;              /* IE 10 */
    flex: 1;                  /* NEW, Spec - Opera 12.1, Firefox 20+ */
}

.column_center {
    -webkit-box-ordinal-group: 2;   /* OLD - iOS 6-, Safari 3.1-6 */
    -moz-box-ordinal-group: 2;      /* OLD - Firefox 19- */
    -ms-flex-order: 2;              /* TWEENER - IE 10 */
    -webkit-order: 2;               /* NEW - Chrome */
    order: 2;                       /* NEW, Spec - Opera 12.1, Firefox 20+ */
}

jsFiddle demo

Here is an excellent article about Flexbox cross-browser support: Using Flexbox: Mixing Old And New

Bootstrap select dropdown list placeholder

Use hidden:

<select>
    <option hidden >Display but don't show in list</option>
    <option> text 1 </option>
    <option> text 2 </option>
    <option> text 3 </option>
</select>

Align button to the right

You can also use like below code.

<button style="position: absolute; right: 0;">Button</button>

What happens to C# Dictionary<int, int> lookup if the key does not exist?

The Dictionary throws a KeyNotFound exception in the event that the dictionary does not contain your key.

As suggested, ContainsKey is the appropriate precaution. TryGetValue is also effective.

This allows the dictionary to store a value of null more effectively. Without it behaving this way, checking for a null result from the [] operator would indicate either a null value OR the non-existance of the input key which is no good.

How to check whether an array is empty using PHP?

Making the most appropriate decision requires knowing the quality of your data and what processes are to follow.

  1. If you are going to disqualify/disregard/remove this row, then the earliest point of filtration should be in the mysql query.
  • WHERE players IS NOT NULL
  • WHERE players != ''
  • WHERE COALESCE(players, '') != ''
  • WHERE players IS NOT NULL AND players != ''
  • ...it kind of depends on your store data and there will be other ways, I'll stop here.
  1. If you aren't 100% sure if the column will exist in the result set, then you should check that the column is declared. This will mean calling array_key_exists(), isset(), or empty() on the column. I am not going to bother delineating the differences here (there are other SO pages for that breakdown, here's a start: 1, 2, 3). That said, if you aren't in total control of the result set, then maybe you have over-indulged application "flexibility" and should rethink if the trouble of potentially accessing non-existent column data is worth it. Effectively, I am saying that you should never need to check if a column is declared -- ergo you should never need empty() for this task. If anyone is arguing that empty() is more appropriate, then they are pushing their own personal opinion about expressiveness of scripting. If you find the condition in #5 below to be ambiguous, add an inline comment to your code -- but I wouldn't. The bottom line is that there is no programmatical advantage to making the function call.

  2. Might your string value contain a 0 that you want to deem true/valid/non-empty? If so, then you only need to check if the column value has length.

Here is a Demo using strlen(). This will indicated whether or not the string will create meaningful array elements if exploded.

  1. I think it is important to mention that by unconditionally exploding, you are GUARANTEED to generate a non-empty array. Here's proof: Demo In other words, checking if the array is empty is completely useless -- it will be non-empty every time.

  2. If your string will NOT POSSIBLY contain a zero value (because, say, this is a csv consisting of ids which start from 1 and only increment), then if ($gamerow['players']) { is all you need -- end of story.

  3. ...but wait, what are you doing after determining the emptiness of this value? If you have something down-script that is expecting $playerlist, but you are conditionally declaring that variable, then you risk using the previous row's value or again generating Notices. So do you need to unconditionally declare $playerlist as something? If there are no truthy values in the string, does your application benefit from declaring an empty array? Chances are, the answer is yes. In this case, you can ensure that the variable is array-type by falling back to an empty array -- this way it won't matter if you feed that variable into a loop. The following conditional declarations are all equivalent.

  • if ($gamerow['players']) { $playerlist = explode(',', $gamerow['players']); } else { $playerlist = []; }
  • $playerlist = $gamerow['players'] ? explode(',', $gamerow['players']) : [];

Why have I gone to such length to explain this very basic task?

  1. I have whistleblown nearly every answer on this page and this answer is likely to draw revenge votes (this happens often to whistleblowers who defend this site -- if an answer has downvotes and no comments, always be skeptical).
  2. I think it is important that Stackoverflow is a trusted resource that doesn't poison researchers with misinformation and suboptimal techniques.
  3. This is how I show how much I care about upcoming developers so that they learn the how and the why instead of just spoon-feeding a generation of copy-paste programmers.
  4. I frequently use old pages to close new duplicate pages -- this is the responsibility of veteran volunteers who know how to quickly find duplicates. I cannot bring myself to use an old page with bad/false/suboptimal/misleading information as a reference because then I am actively doing a disservice to a new researcher.

Find an element in DOM based on an attribute value

Modern browsers support native querySelectorAll so you can do:

document.querySelectorAll('[data-foo="value"]');

https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelectorAll

Details about browser compatibility:

You can use jQuery to support obsolete browsers (IE9 and older):

$('[data-foo="value"]');

Variables not showing while debugging in Eclipse

What worked for me is the following: I had a blank Variables view for the top stack frame. I selected a lower stack frame, then reselected the top one, and the Variables view refreshed itself somehow. Note: I'm using Eclipse Mars, so this bug appears to have returned in this version (or perhaps it's a different one, with the same symptoms?).

"installation of package 'FILE_PATH' had non-zero exit status" in R

I have had the same problem with a specific package in R and the solution was I should install in the ubuntu terminal libcurl. Look at the information that appears above explaining to us that curl package has error installation.

I knew this about the message:

Configuration failed because libcurl was not found. Try installing:
 * deb: libcurl4-openssl-dev (Debian, Ubuntu, etc)
 * rpm: libcurl-devel (Fedora, CentOS, RHEL)
 * csw: libcurl_dev (Solaris)
If libcurl is already installed, check that 'pkg-config' is in your
PATH and PKG_CONFIG_PATH contains a libcurl.pc file. If pkg-config
is unavailable you can set INCLUDE_DIR and LIB_DIR manually via:
R CMD INSTALL --configure-vars='INCLUDE_DIR=... LIB_DIR=...'

To install it I used the net command:

sudo apt-get install libcurl4-openssl-dev

Sometimes we can not install a specific package in R because we have problems with packages that must be installed previously as curl package. To know if we should install it we should check the warning errors such as: installation of package ‘curl’ had non-zero exit status.

I hope I have been helpful

How to bind list to dataGridView?

Use a BindingList and set the DataPropertyName-Property of the column.

Try the following:

...
private void BindGrid()
{
    gvFilesOnServer.AutoGenerateColumns = false;

    //create the column programatically
    DataGridViewCell cell = new DataGridViewTextBoxCell();
    DataGridViewTextBoxColumn colFileName = new DataGridViewTextBoxColumn()
    {
        CellTemplate = cell, 
        Name = "Value",
        HeaderText = "File Name",
        DataPropertyName = "Value" // Tell the column which property of FileName it should use
     };

    gvFilesOnServer.Columns.Add(colFileName);

    var filelist = GetFileListOnWebServer().ToList();
    var filenamesList = new BindingList<FileName>(filelist); // <-- BindingList

    //Bind BindingList directly to the DataGrid, no need of BindingSource
    gvFilesOnServer.DataSource = filenamesList 
}

PostgreSQL return result set as JSON array?

Also if you want selected field from table and aggregated then as array .

SELECT json_agg(json_build_object('data_a',a,
                                  'data_b',b,
))  from t;

The result will come .

 [{'data_a':1,'data_b':'value1'}
  {'data_a':2,'data_b':'value2'}]

Using python PIL to turn a RGB image into a pure black and white image

A simple way to do it using python :

Python
import numpy as np
import imageio

image = imageio.imread(r'[image-path]', as_gray=True)

# getting the threshold value
thresholdValue = np.mean(image)

# getting the dimensions of the image
xDim, yDim = image.shape

# turn the image into a black and white image
for i in range(xDim):
    for j in range(yDim):
        if (image[i][j] > thresholdValue):
            image[i][j] = 255
        else:
            image[i][j] = 0

Local variable referenced before assignment?

Put a global statement at the top of your function and you should be good:

def onLoadFinished(result):
    global feed
    ...

To demonstrate what I mean, look at this little test:

x = 0
def t():
    x += 1
t()

this blows up with your exact same error where as:

x = 0
def t():
    global x
    x += 1
t()

does not.

The reason for this is that, inside t, Python thinks that x is a local variable. Furthermore, unless you explicitly tell it that x is global, it will try to use a local variable named x in x += 1. But, since there is no x defined in the local scope of t, it throws an error.

Get Insert Statement for existing row in MySQL

Since you copied the table with the SQL produced by SHOW CREATE TABLE MyTable, you could just do the following to load the data into the new table.

INSERT INTO dest_db.dest_table SELECT * FROM source_db.source_table;

If you really want the INSERT statements, then the only way that I know of is to use mysqldump http://dev.mysql.com/doc/refman/5.1/en/mysqldump.htm. You can give it options to just dump data for a specific table and even limit rows.

How to display Wordpress search results?

I am using searchform.php and search.php files as already mentioned, but here I provide the actual code.

Creating a Search Page codex page helps here and #Creating_a_Search_Page_Template shows the search query.

In my case I pass the $search_query arguments to the WP_Query Class (which can determine if is search query!). I then run The Loop to display the post information I want to, which in my case is the the_permalink and the_title.

Search box form:

<form class="search" method="get" action="<?php echo home_url(); ?>" role="search">
  <input type="search" class="search-field" placeholder="<?php echo esc_attr_x( 'Search …', 'placeholder' ) ?>" value="<?php echo get_search_query() ?>" name="s" title="<?php echo esc_attr_x( 'Search for:', 'label' ) ?>" />
  <button type="submit" role="button" class="btn btn-default right"/><span class="glyphicon glyphicon-search white"></span></button>
</form>

search.php template file:

<?php
    global $query_string;
    $query_args = explode("&", $query_string);
    $search_query = array();

    foreach($query_args as $key => $string) {
      $query_split = explode("=", $string);
      $search_query[$query_split[0]] = urldecode($query_split[1]);
    } // foreach

    $the_query = new WP_Query($search_query);
    if ( $the_query->have_posts() ) : 
    ?>
    <!-- the loop -->

    <ul>    
    <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
        <li>
            <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
        </li>   
    <?php endwhile; ?>
    </ul>
    <!-- end of the loop -->

    <?php wp_reset_postdata(); ?>

<?php else : ?>
    <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>

Moment get current date

Just call moment as a function without any arguments:

moment()

For timezone information with moment, look at the moment-timezone package: http://momentjs.com/timezone/

How to determine the screen width in terms of dp or dip at runtime in Android?

DisplayMetrics displayMetrics = new DisplayMetrics();

getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

int width_px = Resources.getSystem().getDisplayMetrics().widthPixels;

int height_px =Resources.getSystem().getDisplayMetrics().heightPixels;

int pixeldpi = Resources.getSystem().getDisplayMetrics().densityDpi;


int width_dp = (width_px/pixeldpi)*160;
int height_dp = (height_px/pixeldpi)*160;

How to copy a file to another path?

TO Copy The Folder I Use Two Text Box To Know The Place Of Folder And Anther Text Box To Know What The Folder To Copy It And This Is The Code

MessageBox.Show("The File is Create in The Place Of The Programe If you Don't Write The Place Of copy And You write Only Name Of Folder");// It Is To Help The User TO Know
          if (Fromtb.Text=="")
        {
            MessageBox.Show("Ples You Should Write All Text Box");
            Fromtb.Select();
            return;
        }
        else if (Nametb.Text == "")
        {
            MessageBox.Show("Ples You Should Write The Third Text Box");
            Nametb.Select();
            return;
        }
        else if (Totb.Text == "")
        {
            MessageBox.Show("Ples You Should Write The Second Text Box");
            Totb.Select();
            return;
        }

        string fileName = Nametb.Text;
        string sourcePath = @"" + Fromtb.Text;
        string targetPath = @"" + Totb.Text;


        string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
        string destFile = System.IO.Path.Combine(targetPath, fileName);


        if (!System.IO.Directory.Exists(targetPath))
        {
            System.IO.Directory.CreateDirectory(targetPath);
            //when The User Write The New Folder It Will Create 
            MessageBox.Show("The File is Create in "+" "+Totb.Text);
        }


        System.IO.File.Copy(sourceFile, destFile, true);


        if (System.IO.Directory.Exists(sourcePath))
        {
            string[] files = System.IO.Directory.GetFiles(sourcePath);


            foreach (string s in files)
            {
                fileName = System.IO.Path.GetFileName(s);
                destFile = System.IO.Path.Combine(targetPath, fileName);
                System.IO.File.Copy(s, destFile, true);

            }
            MessageBox.Show("The File is copy To " + Totb.Text);

        }

Unknown version of Tomcat was specified in Eclipse

I got the same error and resolved it by giving enough permissions to the folder. I gave full permissions by (you can try limited permissions which is enough for eclipse to run tomcat)

sudo chmod -R 777 apache-tomcat-8.5.33/

FYI, I encountered this error on my mac, but I think it should be same for ubuntu system too.

How can get the text of a div tag using only javascript (no jQuery)

You can use innerHTML(then parse text from HTML) or use innerText.

let textContentWithHTMLTags = document.querySelector('div').innerHTML; 
let textContent = document.querySelector('div').innerText;

console.log(textContentWithHTMLTags, textContent);

innerHTML and innerText is supported by all browser(except FireFox < 44) including IE6.

jQuery: Can I call delay() between addClass() and such?

Try this simple arrow funtion:

setTimeout( () => { $("#div").addClass("error") }, 900 );

What is the Difference Between Mercurial and Git?

Are there any Windows-based collaborators on your project?

Because if there are, the Git-for-Windows GUI seems awkward, difficult, unfriendly.

Mercurial-on-Windows, by contrast, is a no-brainer.

Difference between webdriver.get() and webdriver.navigate()

There are some differences between webdriver.get() and webdriver.navigate() method.


get()

As per the API Docs get() method in the WebDriver interface extends the SearchContext and is defined as:

/**
 * Load a new web page in the current browser window. This is done using an HTTP POST operation,
 * and the method will block until the load is complete.
 * This will follow redirects issued either by the server or as a meta-redirect from within the
 * returned HTML.
 * Synonym for {@link org.openqa.selenium.WebDriver.Navigation#to(String)}.
 */
void get(String url);
    
  • Usage:

    driver.get("https://www.google.com/");
    

navigate()

On the other hand, navigate() is the abstraction which allows the WebDriver instance i.e. the driver to access the browser's history as well as to navigate to a given URL. The methods along with the usage are as follows:

  • to(java.lang.String url): Load a new web page in the current browser window.

    driver.navigate().to("https://www.google.com/");
    
  • to(java.net.URL url): Overloaded version of to(String) that makes it easy to pass in a URL.

  • refresh(): Refresh the current page.

    driver.navigate().refresh();
    
  • back(): Move back a single "item" in the browser's history.

    driver.navigate().back();
    
  • forward(): Move a single "item" forward in the browser's history.

    driver.navigate().forward();
    

How to check permissions of a specific directory?

This displays files with its permisions

stat -c '%a - %n' directory/*

Get Row Index on Asp.net Rowcommand event

If you have a built-in command of GridView like insert, update or delete, on row command you can use the following code to get the index:

int index = Convert.ToInt32(e.CommandArgument);

In a custom command, you can set the command argument to yourRow.RowIndex.ToString() and then get it back in the RowCommand event handler. Unless, of course, you need the command argument for another purpose.

Getting Checkbox Value in ASP.NET MVC 4

I read through the other answers and wasn't quite getting it to work - so here's the solution I ended up with.

My form uses the Html.EditorFor(e => e.Property) to generate the checkbox, and using FormCollection in the controller, this passes a string value of 'true,false' in the controller.

When I'm handling the results I use a loop to cycle through them - I also use an InfoProperty instance to represent the current model value being assessed from the form.

So instead I just check if the string returned starts with the word 'true' and then set a boolean variable to true and pass that into the return model.

if (KeyName.EndsWith("OnOff"))
{
    // set on/off flags value to the model instance
    bool keyTrueFalse = false;
    if(values[KeyName].StartsWith("true"))
    {
        keyTrueFalse = true;
    }
    infoProperty.SetValue(processedInfo, keyTrueFalse);
}

npm install gives error "can't find a package.json file"

solve using this code:

npm install npm@latest -g

IntelliJ inspection gives "Cannot resolve symbol" but still compiles code

Yes, sounds like you have to create libraries containing the JARs you need and add them as a dependency in your module.

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.10:test

Right Click on Project -> Maven -> Update Project -> Select Force update of snapshot

Or

Navigate to project root folder and use following commands :

mvn clean install -U or mvn clean install --update-snapshots

Here -U will Forces a check for missing releases and updated snapshots on remote repositories

Fatal error: unexpectedly found nil while unwrapping an Optional values

Nil Coalescing Operator can be used as well.

rowName = rowName != nil ?rowName!.stringFromCamelCase():""

excel - if cell is not blank, then do IF statement

Your formula is wrong. You probably meant something like:

=IF(AND(NOT(ISBLANK(Q2));NOT(ISBLANK(R2)));IF(Q2<=R2;"1";"0");"")

Another equivalent:

=IF(NOT(OR(ISBLANK(Q2);ISBLANK(R2)));IF(Q2<=R2;"1";"0");"")

Or even shorter:

=IF(OR(ISBLANK(Q2);ISBLANK(R2));"";IF(Q2<=R2;"1";"0"))

OR EVEN SHORTER:

=IF(OR(ISBLANK(Q2);ISBLANK(R2));"";--(Q2<=R2))

How can I shutdown Spring task executor/scheduler pools before all other beans in the web app are destroyed?

Two ways:

  1. Have a bean implement ApplicationListener<ContextClosedEvent>. onApplicationEvent() will get called before the context and all the beans are destroyed.

  2. Have a bean implement Lifecycle or SmartLifecycle. stop() will get called before the context and all the beans are destroyed.

Either way you can shut down the task stuff before the bean destroying mechanism takes place.

Eg:

@Component
public class ContextClosedHandler implements ApplicationListener<ContextClosedEvent> {
    @Autowired ThreadPoolTaskExecutor executor;
    @Autowired ThreadPoolTaskScheduler scheduler;

    @Override
    public void onApplicationEvent(ContextClosedEvent event) {
        scheduler.shutdown();
        executor.shutdown();
    }       
}

(Edit: Fixed method signature)

Creating a chart in Excel that ignores #N/A or blank cells

I had the same problem with a full line appearing.

The end of my data only had #N/A.

When I changed the chart type from a stacked line to line then the end of the line was removed from the chart.

This did not work if the #N/A was in the middle of the data, only when it was in the trailing data.

How to show full height background image?

 html, body {
    height:100%;
}

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;
}

When does a cookie with expiration time 'At end of session' expire?

Just to correct mingos' answer:

If you set the expiration time to 0, the cookie won't be created at all. I've tested this on Google Chrome at least, and when set to 0 that was the result. The cookie, I guess, expires immediately after creation.

To set a cookie so it expires at the end of the browsing session, simply OMIT the expiration parameter altogether.

Example:

Instead of:

document.cookie = "cookie_name=cookie_value; 0; path=/";

Just write:

document.cookie = "cookie_name=cookie_value; path=/";

How to make an ng-click event conditional?

It is not good to manipulate with DOM (including checking of attributes) in any place except directives. You can add into scope some value indicating if link should be disabled.

But other problem is that ngDisabled does not work on anything except form controls, so you can't use it with <a>, but you can use it with <button> and style it as link.

Another way is to use lazy evaluation of expressions like isDisabled || action() so action wouold not be called if isDisabled is true.

Here goes both solutions: http://plnkr.co/edit/5d5R5KfD4PCE8vS3OSSx?p=preview

"Fade" borders in CSS

You can specify gradients for colours in certain circumstances in CSS3, and of course borders can be set to a colour, so you should be able to use a gradient as a border colour. This would include the option of specifying a transparent colour, which means you should be able to achieve the effect you're after.

However, I've never seen it used, and I don't know how well supported it is by current browsers. You'll certainly need to accept that at least some of your users won't be able to see it.

A quick google turned up these two pages which should help you on your way:

Hope that helps.

Getting binary (base64) data from HTML5 Canvas (readAsBinaryString)

The canvas element provides a toDataURL method which returns a data: URL that includes the base64-encoded image data in a given format. For example:

var jpegUrl = canvas.toDataURL("image/jpeg");
var pngUrl = canvas.toDataURL(); // PNG is the default

Although the return value is not just the base64 encoded binary data, it's a simple matter to trim off the scheme and the file type to get just the data you want.

The toDataURL method will fail if the browser thinks you've drawn to the canvas any data that was loaded from a different origin, so this approach will only work if your image files are loaded from the same server as the HTML page whose script is performing this operation.

For more information see the MDN docs on the canvas API, which includes details on toDataURL, and the Wikipedia article on the data: URI scheme, which includes details on the format of the URI you'll receive from this call.

Pad a string with leading zeros so it's 3 characters long in SQL Server 2008

I know this is an old ticket but I just thought I'd share this:

I found this code which provides a solution. Not sure if it works on all versions of MSSQL; I have MSSQL 2016.

declare @value as nvarchar(50) = 23
select REPLACE(STR(CAST(@value AS INT) + 1,4), SPACE(1), '0') as Leadingzero

This returns "0023".

The 4 in the STR function is the total length, including the value. For example, 4, 23 and 123 will all have 4 in STR and the correct amount of zeros will be added. You can increase or decrease it. No need to get the length on the 23.

Edit: I see it's the same as the post by @Anon.

Why does Vim save files with a ~ extension?

To turn off those files, just add these lines to .vimrc (vim configuration file on unix based OS):

set nobackup       #no backup files
set nowritebackup  #only in case you don't want a backup file while editing
set noswapfile     #no swap files

How to run C program on Mac OS X using Terminal?

A "C-program" is not supposed to be run. It is meant to be compiled into an "executable" program which then can be run from your terminal. You need a compiler for that.

Oh, and the answer to your last question ("Why?") is that the file you are trying to execute doesn't have the executable rights set (which a compiler usually does automatically with the binary, which let's infer that you were trying to run the source code as a script, hence the hint at compiling.)

How to set placeholder value using CSS?

You can do this for webkit:

#text2::-webkit-input-placeholder::before {
    color:#666;
    content:"Line 1\A Line 2\A Line 3\A";
}

http://jsfiddle.net/Z3tFG/1/

Scanner is never closed

Try this

Scanner scanner = new Scanner(System.in);
int amountOfPlayers;
do {
    System.out.print("Select the amount of players (1/2): ");
    while (!scanner.hasNextInt()) {
        System.out.println("That's not a number!");
        scanner.next(); // this is important!
    }

    amountOfPlayers = scanner.nextInt();
} while ((amountOfPlayers <= 0) || (amountOfPlayers > 2));
if(scanner != null) {
    scanner.close();
}
System.out.println("You've selected " + amountOfPlayers+" player(s).");

Using Intent in an Android application to show another activity

you can use the context of the view that did the calling. Example:

Button orderButton = (Button)findViewById(R.id.order);

orderButton.setOnClickListener(new View.OnClickListener() {

  @Override
  public void onClick(View view) {
    Intent intent = new Intent(/*FirstActivity.this*/ view.getContext(), OrderScreen.class);
    startActivity(intent);
  }

});

How to install both Python 2.x and Python 3.x in Windows

If you can't get anything else to work, open an interpreter in whichever version you choose (I prefer using iPython) and:

import subprocess

subprocess.call('python script.py -flags')

This uses whichever python version you are currently operating under. Works fine for a single script, but will quickly get out of hand if there are lots of scripts you run, in which case you can always make a batch file with all of these calls inside. Not the most elegant answer, but it works.

Is there a way to make aliases for different python version a la Linux?

How to unpublish an app in Google Play Developer Console

As per new Interface follow these steps

  1. Go to Google Play Developer Console
  2. Select your app you want to un-publish
  3. From the left Navigation Release >> Setup >> Advance Settings
  4. In the App Availability Check on Unpublished Radio button enter image description here

Update select2 data without rebuilding the control

As best I can tell, it is not possible to update the select2 options without refreshing the entire list or entering some search text and using a query function.

What are those buttons supposed to do? If they are used to determine the select options, why not put them outside of the select box, and have them programmatically set the select box data and then open it? I don't understand why you would want to put them on top of the search box. If the user is not supposed to search, you can use the minimumResultsForSearch option to hide the search feature.

Edit: How about this...

HTML:

<input type="hidden" id="select2" class="select" />

Javascript

var data = [{id: 0, text: "Zero"}],
    select = $('#select2');

select.select2({
  query: function(query) {
    query.callback({results: data});
  },
  width: '150px'
});

console.log('Opening select2...');
select.select2('open');

setTimeout(function() {
  console.log('Updating data...');
  data = [{id: 1, text: 'One'}];
}, 1500);

setTimeout(function() {
  console.log('Fake keyup-change...');
  select.data().select2.search.trigger('keyup-change');
}, 3000);

Example: Plunker

Edit 2: That will at least get it to update the list, however there is still some weirdness if you have entered search text before triggering the keyup-change event.

What does --net=host option in Docker command really do?

After the docker installation you have 3 networks by default:

docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
f3be8b1ef7ce        bridge              bridge              local
fbff927877c1        host                host                local
023bb5940080        none                null                local

I'm trying to keep this simple. So if you start a container by default it will be created inside the bridge (docker0) network.

$ docker run -d jenkins
1498e581cdba        jenkins             "/bin/tini -- /usr..."   3 minutes ago       Up 3 minutes        8080/tcp, 50000/tcp   friendly_bell

In the dockerfile of jenkins the ports 8080 and 50000 are exposed. Those ports are opened for the container on its bridge network. So everything inside that bridge network can access the container on port 8080 and 50000. Everything in the bridge network is in the private range of "Subnet": "172.17.0.0/16", If you want to access them from the outside you have to map the ports with -p 8080:8080. This will map the port of your container to the port of your real server (the host network). So accessing your server on 8080 will route to your bridgenetwork on port 8080.

Now you also have your host network. Which does not containerize the containers networking. So if you start a container in the host network it will look like this (it's the first one):

CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                 NAMES
1efd834949b2        jenkins             "/bin/tini -- /usr..."   6 minutes ago       Up 6 minutes                              eloquent_panini
1498e581cdba        jenkins             "/bin/tini -- /usr..."   10 minutes ago      Up 10 minutes       8080/tcp, 50000/tcp   friendly_bell

The difference is with the ports. Your container is now inside your host network. So if you open port 8080 on your host you will acces the container immediately.

$ sudo iptables -I INPUT 5 -p tcp -m tcp --dport 8080 -j ACCEPT

I've opened port 8080 in my firewall and when I'm now accesing my server on port 8080 I'm accessing my jenkins. I think this blog is also useful to understand it better.

Java String array: is there a size of method?

If you want a function to do this

Object array = new String[10];
int size = Array.getlength(array);

This can be useful if you don't know what type of array you have e.g. int[], byte[] or Object[].

JSTL if tag for equal strings

<c:if test="${ansokanInfo.pSystem eq 'NAT'}">

Changing nav-bar color after scrolling?

window.addEventListener('scroll', function (e) {
        var nav = document.getElementById('nav');
        if (document.documentElement.scrollTop || document.body.scrollTop > window.innerHeight) {
                nav.classList.add('nav-colored');
                nav.classList.remove('nav-transparent');
            } else {
                nav.classList.add('nav-transparent');
                nav.classList.remove('nav-colored');
            }
    });

best approach to use event listener. especially for Firefox browser, check this doc Scroll-linked effects and Firefox is no longer support document.body.scrollTop and alternative to use document.documentElement.scrollTop. This is completes the answer from Yahya Essam

How to default to other directory instead of home directory

Another solution for Windows users will be to copy the Git Bash.lnk file to the directory you need to start from and launch it from there.

Padding zeros to the left in postgreSQL

You can use the rpad and lpad functions to pad numbers to the right or to the left, respectively. Note that this does not work directly on numbers, so you'll have to use ::char or ::text to cast them:

SELECT RPAD(numcol::text, 3, '0'), -- Zero-pads to the right up to the length of 3
       LPAD(numcol::text, 3, '0'), -- Zero-pads to the left up to the length of 3
FROM   my_table

How do I remove an item from a stl vector with a certain value?

Two ways are there by which you can use to erase an item particularly. lets take a vector

std :: vector < int > v;
v.push_back(10);
v.push_back(20);
v.push_back(30);
v.push_back(40);
v.push_back(40);
v.push_back(50);

1) Non efficient way : Although it seems to be quite efficient but it's not because erase function delets the elements and shifts all the elements towards left by 1. so its complexity will be O(n^2)

std :: vector < int > :: iterator itr = v.begin();
int value = 40;
while ( itr != v.end() )
{
   if(*itr == value)
   { 
      v.erase(itr);
   }
   else
       ++itr;
}

2) Efficient way ( RECOMMENDED ) : It is also known as ERASE - REMOVE idioms .

  • std::remove transforms the given range into a range with all the elements that compare not equal to given element shifted to the start of the container.
  • So, actually don't remove the matched elements. It just shifted the non matched to starting and gives an iterator to new valid end. It just requires O(n) complexity.

output of the remove algorithm is :

10 20 30 50 40 50 

as return type of remove is iterator to the new end of that range.

template <class ForwardIterator, class T>
  ForwardIterator remove (ForwardIterator first, ForwardIterator last, const T& val);

Now use vector’s erase function to delete elements from the new end to old end of the vector. It requires O(1) time.

v.erase ( std :: remove (v.begin() , v.end() , element ) , v.end () );

so this method work in O(n)

Convert the first element of an array to a string in PHP

Convert array to a string in PHP:

Use the PHP join function like this:

$my_array = array(4,1,8);

print_r($my_array);
Array
(
    [0] => 4
    [1] => 1
    [2] => 8
)

$result_string = join(',' , $my_array);
echo $result_string;

Which delimits the items in the array by comma into a string:

4,1,8

What is Hash and Range Primary Key?

A well-explained answer is already given by @mkobit, but I will add a big picture of the range key and hash key.

In a simple words range + hash key = composite primary key CoreComponents of Dynamodb enter image description here

A primary key is consists of a hash key and an optional range key. Hash key is used to select the DynamoDB partition. Partitions are parts of the table data. Range keys are used to sort the items in the partition, if they exist.

So both have a different purpose and together help to do complex query. In the above example hashkey1 can have multiple n-range. Another example of range and hashkey is game, userA(hashkey) can play Ngame(range)

enter image description here

The Music table described in Tables, Items, and Attributes is an example of a table with a composite primary key (Artist and SongTitle). You can access any item in the Music table directly, if you provide the Artist and SongTitle values for that item.

A composite primary key gives you additional flexibility when querying data. For example, if you provide only the value for Artist, DynamoDB retrieves all of the songs by that artist. To retrieve only a subset of songs by a particular artist, you can provide a value for Artist along with a range of values for SongTitle.

enter image description here

https://www.slideshare.net/InfoQ/amazon-dynamodb-design-patterns-best-practices https://www.slideshare.net/AmazonWebServices/awsome-day-2016-module-4-databases-amazon-dynamodb-and-amazon-rds https://ceyhunozgun.blogspot.com/2017/04/implementing-object-persistence-with-dynamodb.html

PHP split alternative?

I want to clear here that preg_split(); is far away from it but explode(); can be used in similar way as split();

following is the comparison between split(); and explode(); usage

How was split() used

<?php

$date = "04/30/1973";
list($month, $day, $year) = split('[/.-]', $date);
echo $month; // foo
echo $day; // *
echo $year;

?>

URL: http://php.net/manual/en/function.split.php

How explode() can be used

<?php

$data = "04/30/1973";
list($month, $day, $year) = explode("/", $data);
echo $month; // foo
echo $day; // *
echo $year;

?>

URL: http://php.net/manual/en/function.explode.php

Here is how we can use it :)

How to pass value from <option><select> to form action

You don't have to use jQuery or Javascript.

Use the name tag of the select and let the form do it's job.

<select name="agent_id" id="agent_id">

Shortcut to open file in Vim

There's also command-t which I find to be the best of the bunch (and I've tried them all). It's a minor hassle to install it but, once it's installed, it's a dream to use.

https://wincent.com/products/command-t/

Vertical Text Direction

Try using:

writing-mode: lr-tb;

Cannot install Aptana Studio 3.6 on Windows

I had this issue and it was because of limited internet connection to source. You can use a proxy (VPN) but the better solution is download manually NodeJs from the source https://nodejs.org/download/ and Git, too.

after installation manually, aptana will check if they installed or not.

Radio/checkbox alignment in HTML/CSS

I wouldn't use tables for this at all. CSS can easily do this.

I would do something like this:

   <p class="clearfix">
      <input id="option1" type="radio" name="opt" />
      <label for="option1">Option 1</label>
   </p>

p { margin: 0px 0px 10px 0px; }
input { float: left; width: 50px; }
label { margin: 0px 0px 0px 10px; float: left; }

Note: I have used the clearfix class from : http://www.positioniseverything.net/easyclearing.html

.clearfix:after {
    content: ".";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;
}

.clearfix {display: inline-block;}

/* Hides from IE-mac \*/
* html .clearfix {height: 1%;}
.clearfix {display: block;}
/* End hide from IE-mac */

Superscript in Python plots

Alternatively, in python 3.6+, you can generate Unicode superscript and copy paste that in your code:

ax1.set_ylabel('Rate (min?¹)')

JPanel setBackground(Color.BLACK) does nothing

You need to create a new Jpanel object in the Board constructor. for example

public Board(){
    JPanel pane = new JPanel();
    pane.setBackground(Color.ORANGE);// sets the background to orange
} 

python "TypeError: 'numpy.float64' object cannot be interpreted as an integer"

I came here with the same Error, though one with a different origin.

It is caused by unsupported float index in 1.12.0 and newer numpy versions even if the code should be considered as valid.

An int type is expected, not a np.float64

Solution: Try to install numpy 1.11.0

sudo pip install -U numpy==1.11.0.

PHP Include for HTML?

I have a similar issue. It appears that PHP does not like php code inside included file. In your case solution is quite simple. Remove php code from navbar.php, simply leave plain HTML in it and it will work.

What is the easiest/best/most correct way to iterate through the characters of a string in Java?

If you have Guava on your classpath, the following is a pretty readable alternative. Guava even has a fairly sensible custom List implementation for this case, so this shouldn't be inefficient.

for(char c : Lists.charactersOf(yourString)) {
    // Do whatever you want     
}

UPDATE: As @Alex noted, with Java 8 there's also CharSequence#chars to use. Even the type is IntStream, so it can be mapped to chars like:

yourString.chars()
        .mapToObj(c -> Character.valueOf((char) c))
        .forEach(c -> System.out.println(c)); // Or whatever you want

Java optional parameters

There are no optional parameters in Java. What you can do is overloading the functions and then passing default values.

void SomeMethod(int age, String name) {
    //
}

// Overload
void SomeMethod(int age) {
    SomeMethod(age, "John Doe");
}

How to get base64 encoded data from html image

You can try following sample http://jsfiddle.net/xKJB8/3/

<img id="preview" src="http://www.gravatar.com/avatar/0e39d18b89822d1d9871e0d1bc839d06?s=128&d=identicon&r=PG">
<canvas id="myCanvas" />

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("preview");
ctx.drawImage(img, 10, 10);
alert(c.toDataURL());

The Import android.support.v7 cannot be resolved

I had the same issue every time I tried to create a new project, but based on the console output, it was because of two versions of android-support-v4 that were different:

[2014-10-29 16:31:57 - HeadphoneSplitter] Found 2 versions of android-support-v4.jar in the dependency list,
[2014-10-29 16:31:57 - HeadphoneSplitter] but not all the versions are identical (check is based on SHA-1 only at this time).
[2014-10-29 16:31:57 - HeadphoneSplitter] All versions of the libraries must be the same at this time.
[2014-10-29 16:31:57 - HeadphoneSplitter] Versions found are:
[2014-10-29 16:31:57 - HeadphoneSplitter] Path: C:\Users\jbaurer\workspace\appcompat_v7\libs\android-support-v4.jar
[2014-10-29 16:31:57 - HeadphoneSplitter]   Length: 627582
[2014-10-29 16:31:57 - HeadphoneSplitter]   SHA-1: cb6883d96005bc85b3e868f204507ea5b4fa9bbf
[2014-10-29 16:31:57 - HeadphoneSplitter] Path: C:\Users\jbaurer\workspace\HeadphoneSplitter\libs\android-support-v4.jar
[2014-10-29 16:31:57 - HeadphoneSplitter]   Length: 758727
[2014-10-29 16:31:57 - HeadphoneSplitter]   SHA-1: efec67655f6db90757faa37201efcee2a9ec3507
[2014-10-29 16:31:57 - HeadphoneSplitter] Jar mismatch! Fix your dependencies

I don't know a lot about Eclipse. but I simply deleted the copy of the jar file from my project's libs folder so that it would use the appcompat_v7 jar file instead. This fixed my issue.

PHP returning JSON to JQUERY AJAX CALL

You can return json in PHP this way:

header('Content-Type: application/json');
echo json_encode(array('foo' => 'bar'));
exit;

How to add an UIViewController's view as subview

You must set the bounds properties to fit that frame. frame its superview properties, and bounds limit the frame in the view itself coordinate system.

How can I brew link a specific version?

brew switch libfoo mycopy

You can use brew switch to switch between versions of the same package, if it's installed as versioned subdirectories under Cellar/<packagename>/

This will list versions installed ( for example I had Cellar/sdl2/2.0.3, I've compiled into Cellar/sdl2/2.0.4)

brew info sdl2

Then to switch between them

brew switch sdl2 2.0.4
brew info 

Info now shows * next to the 2.0.4

To install under Cellar/<packagename>/<version> from source you can do for example

cd ~/somewhere/src/foo-2.0.4
./configure --prefix $(brew --Cellar)/foo/2.0.4
make

check where it gets installed with

make install -n

if all looks correct

make install

Then from cd $(brew --Cellar) do the switch between version.

I'm using brew version 0.9.5

Initialize a string in C to empty string

You want to set the first character of the string to zero, like this:

char myString[10];
myString[0] = '\0';

(Or myString[0] = 0;)

Or, actually, on initialisation, you can do:

char myString[10] = "";

But that's not a general way to set a string to zero length once it's been defined.

run program in Python shell

If you're wanting to run the script and end at a prompt (so you can inspect variables, etc), then use:

python -i test.py

That will run the script and then drop you into a Python interpreter.

How to extract this specific substring in SQL Server?

select substring(your_field, CHARINDEX(';',your_field)+1 ,CHARINDEX('[',your_field)-CHARINDEX(';',your_field)-1) from your_table

Can't get the others to work. I believe you just want what is in between ';' and '[' in all cases regardless of how long the string in between is. After specifying the field in the substring function, the second argument is the starting location of what you will extract. That is, where the ';' is + 1 (fourth position - the c), because you don't want to include ';'. The next argument takes the location of the '[' (position 14) and subtracts the location of the spot after the ';' (fourth position - this is why I now subtract 1 in the query). This basically says substring(field,location I want substring to begin, how long I want substring to be). I've used this same function in other cases. If some of the fields don't have ';' and '[', you'll want to filter those out in the "where" clause, but that's a little different than the question. If your ';' was say... ';;;', you would use 3 instead of 1 in the example. Hope this helps!

What is the difference between a JavaBean and a POJO?

Pojo - Plain old java object

pojo class is an ordinary class without any specialties,class totally loosely coupled from technology/framework.the class does not implements from technology/framework and does not extends from technology/framework api that class is called pojo class.

pojo class can implements interfaces and extend classes but the super class or interface should not be an technology/framework.

Examples :

1.

class ABC{
----
}

ABC class not implementing or extending from technology/framework that's why this is pojo class.

2.

class ABC extends HttpServlet{
---
}

ABC class extending from servlet technology api that's why this is not a pojo class.

3.

class ABC implements java.rmi.Remote{
----
}

ABC class implements from rmi api that's why this is not a pojo class.

4.

class ABC implements java.io.Serializable{
---
}

this interface is part of java language not a part of technology/framework.so this is pojo class.

5.

class ABC extends Thread{
--
}

here thread is also class of java language so this is also a pojo class.

6.

class ABC extends Test{
--
}

if Test class extends or implements from technologies/framework then ABC is also not a pojo class because it inherits the properties of Test class. if Test class is not a pojo class then ABC class also not a pojo class.

7.

now this point is an exceptional case

@Entity
class ABC{
--
}

@Entity is an annotation given by hibernate api or jpa api but still we can call this class as pojo class. class with annotations given from technology/framework is called pojo class by this exceptional case.

How do I create an HTML table with a fixed/frozen left column and a scrollable body?

You can use sticky position. Here is a sample code. This is HTML/CSS solution. No js is required.

_x000D_
_x000D_
.view {
  margin: auto;
  width: 600px;
}

.wrapper {
  position: relative;
  overflow: auto;
  border: 1px solid black;
  white-space: nowrap;
}

.sticky-col {
  position: -webkit-sticky;
  position: sticky;
  background-color: white;
}

.first-col {
  width: 100px;
  min-width: 100px;
  max-width: 100px;
  left: 0px;
}

.second-col {
  width: 150px;
  min-width: 150px;
  max-width: 150px;
  left: 100px;
}
_x000D_
<div class="view">
  <div class="wrapper">
    <table class="table">
      <thead>
        <tr>
          <th class="sticky-col first-col">Number</th>
          <th class="sticky-col second-col">First Name</th>
          <th>Last Name</th>
          <th>Employer</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td class="sticky-col first-col">1</td>
          <td class="sticky-col second-col">Mark</td>
          <td>Ham</td>
          <td>Micro</td>
        </tr>
        <tr>
          <td class="sticky-col first-col">2</td>
          <td class="sticky-col second-col">Jacob</td>
          <td>Smith</td>
          <td>Adob Adob Adob AdobAdob Adob Adob Adob Adob</td>
        </tr>
        <tr>
          <td class="sticky-col first-col">3</td>
          <td class="sticky-col second-col">Larry</td>
          <td>Wen</td>
          <td>Goog Goog Goog GoogGoog Goog Goog Goog Goog Goog</td>
        </tr>
      </tbody>
    </table>
  </div>
</div>
_x000D_
_x000D_
_x000D_

Bootply code: https://www.bootply.com/g8pfBXOcY9

How does the ARM architecture differ from x86?

The ARM architecture was originally designed for Acorn personal computers (See Acorn Archimedes, circa 1987, and RiscPC), which were just as much keyboard-based personal computers as were x86 based IBM PC models. Only later ARM implementations were primarily targeted at the mobile and embedded market segment.

Originally, simple RISC CPUs of roughly equivalent performance could be designed by much smaller engineering teams (see Berkeley RISC) than those working on the x86 development at Intel.

But, nowadays, the fastest ARM chips have very complex multi-issue out-of-order instruction dispatch units designed by large engineering teams, and x86 cores may have something like a RISC core fed by an instruction translation unit.

So, any current differences between the two architectures are more related to the specific market needs of the product niches that the development teams are targeting. (Random opinion: ARM probably makes more in license fees from embedded applications that tend to be far more power and cost constrained. And Intel needs to maintain a performance edge in PCs and servers for their profit margins. Thus you see differing implementation optimizations.)

What's the key difference between HTML 4 and HTML 5?

You might be interested in this list of HTML5 elements and attributes.

Also, please note that it's "HTML 4", not "HTML4". Indeed, for HTML 5, both variants are used, but there is an important difference in meaning. HTML 5 refers to the name of the W3C specification, whereas "HTML5" is the document type of those HTML files with a text/html MIME type that follow this spec. The same goes for XHTML 5 vs. XHTML5.

Increasing nesting function calls limit

Do you have Zend, IonCube, or xDebug installed? If so, that is probably where you are getting this error from.

I ran into this a few years ago, and it ended up being Zend putting that limit there, not PHP. Of course removing it will let you go past the 100 iterations, but you will eventually hit the memory limits.

Postgres: clear entire database before re-creating / re-populating from bash script

To dump:

pg_dump -Fc mydb > db.dump

To restore:

pg_restore --verbose --clean --no-acl --no-owner -h localhost -U myuser -d my_db db/latest.dump

UnsupportedClassVersionError: JVMCFRE003 bad major version in WebSphere AS 7

In eclipse, Go to Project->Properties->Java build Path->Order and Export. If you are using multiple JREs, try like jdk and ibm. Order should start with jdk and then IBM. This is how my issue was resolved.

how to write javascript code inside php

Just echo the javascript out inside the if function

 <form name="testForm" id="testForm"  method="POST"  >
     <input type="submit" name="btn" value="submit" autofocus  onclick="return true;"/>
 </form>
 <?php
    if(isset($_POST['btn'])){
        echo "
            <script type=\"text/javascript\">
            var e = document.getElementById('testForm'); e.action='test.php'; e.submit();
            </script>
        ";
     }
  ?>

Remove element of a regular array

LINQ one-line solution:

myArray = myArray.Where((source, index) => index != 1).ToArray();

The 1 in that example is the index of the element to remove -- in this example, per the original question, the 2nd element (with 1 being the second element in C# zero-based array indexing).

A more complete example:

string[] myArray = { "a", "b", "c", "d", "e" };
int indexToRemove = 1;
myArray = myArray.Where((source, index) => index != indexToRemove).ToArray();

After running that snippet, the value of myArray will be { "a", "c", "d", "e" }.

What does 'low in coupling and high in cohesion' mean

Short and clear answer

  • High cohesion: Elements within one class/module should functionally belong together and do one particular thing.
  • Loose coupling: Among different classes/modules should be minimal dependency.

Exception in thread "main" java.util.NoSuchElementException

The nextInt() method leaves the \n (end line) symbol and is picked up immediately by nextLine(), skipping over the next input. What you want to do is use nextLine() for everything, and parse it later:

String nextIntString = keyboard.nextLine(); //get the number as a single line
int nextInt = Integer.parseInt(nextIntString); //convert the string to an int

This is by far the easiest way to avoid problems--don't mix your "next" methods. Use only nextLine() and then parse ints or separate words afterwards.


Also, make sure you use only one Scanner if your are only using one terminal for input. That could be another reason for the exception.


Last note: compare a String with the .equals() function, not the == operator.

if (playAgain == "yes"); // Causes problems
if (playAgain.equals("yes")); // Works every time

NullInjectorError: No provider for AngularFirestore

Weird thing for me was that I had the provider:[], but the HTML tag that uses the provider was what was causing the error. I'm referring to the red box below: enter image description here

It turns out I had two classes in different components with the same "employee-list.component.ts" filename and so the project compiled fine, but the references were all messed up.

Regular expression for URL validation (in JavaScript)

Try this regex, it works for me:

function isUrl(s) {
    var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
    return regexp.test(s);
}

Open file in a relative location in Python

Try this:

from pathlib import Path

data_folder = Path("/relative/path")
file_to_open = data_folder / "file.pdf"

f = open(file_to_open)

print(f.read())

Python 3.4 introduced a new standard library for dealing with files and paths called pathlib. It works for me!

Can someone explain how to append an element to an array in C programming?

If you have a code like int arr[10] = {0, 5, 3, 64}; , and you want to append or add a value to next index, you can simply add it by typing a[5] = 5.

The main advantage of doing it like this is you can add or append a value to an any index not required to be continued one, like if I want to append the value 8 to index 9, I can do it by the above concept prior to filling up before indices. But in python by using list.append() you can do it by continued indices.

.NET HashTable Vs Dictionary - Can the Dictionary be as fast?

Another important difference is that Hashtable is thread safe. Hashtable has built in multiple reader/single writer (MR/SW) thread safety which means Hashtable allows ONE writer together with multiple readers without locking. In the case of Dictionary there is no thread safety, if you need thread safety you must implement your own synchronization.

To elaborate further:

Hashtable, provide some thread-safety through the Synchronized property, which returns a thread-safe wrapper around the collection. The wrapper works by locking the entire collection on every add or remove operation. Therefore, each thread that is attempting to access the collection must wait for its turn to take the one lock. This is not scalable and can cause significant performance degradation for large collections. Also, the design is not completely protected from race conditions.

The .NET Framework 2.0 collection classes like List<T>, Dictionary<TKey, TValue>, etc do not provide any thread synchronization; user code must provide all synchronization when items are added or removed on multiple threads concurrently If you need type safety as well thread safety, use concurrent collections classes in the .NET Framework. Further reading here.

Difference between HashMap and Map in Java..?

Map is an interface, i.e. an abstract "thing" that defines how something can be used. HashMap is an implementation of that interface.

Why does "npm install" rewrite package-lock.json?

You probably have something like:

"typescript":"~2.1.6"

in your package.json which npm updates to the latest minor version, in your case being 2.4.1

Edit: Question from OP

But that doesn't explain why "npm install" would change the lock file. Isn't the lock file meant to create a reproducible build? If so, regardless of the semver value, it should still use the same 2.1.6 version.

Answer:

This is intended to lock down your full dependency tree. Let's say typescript v2.4.1 requires widget ~v1.0.0. When you npm install it grabs widget v1.0.0. Later on your fellow developer (or CI build) does an npm install and gets typescript v2.4.1 but widget has been updated to widget v1.0.1. Now your node module are out of sync. This is what package-lock.json prevents.

Or more generally:

As an example, consider

package A:

{ "name": "A", "version": "0.1.0", "dependencies": { "B": "<0.1.0" } }

package B:

{ "name": "B", "version": "0.0.1", "dependencies": { "C": "<0.1.0" } }

and package C:

{ "name": "C", "version": "0.0.1" }

If these are the only versions of A, B, and C available in the registry, then a normal npm install A will install:

[email protected] -- [email protected] -- [email protected]

However, if [email protected] is published, then a fresh npm install A will install:

[email protected] -- [email protected] -- [email protected] assuming the new version did not modify B's dependencies. Of course, the new version of B could include a new version of C and any number of new dependencies. If such changes are undesirable, the author of A could specify a dependency on [email protected]. However, if A's author and B's author are not the same person, there's no way for A's author to say that he or she does not want to pull in newly published versions of C when B hasn't changed at all.


OP Question 2: So let me see if I understand correctly. What you're saying is that the lock file specifies the versions of the secondary dependencies, but still relies on the fuzzy matching of package.json to determine the top-level dependencies. Is that accurate?

Answer: No. package-lock locks the entire package tree, including the root packages described in package.json. If typescript is locked at 2.4.1 in your package-lock.json, it should remain that way until it is changed. And lets say tomorrow typescript releases version 2.4.2. If I checkout your branch and run npm install, npm will respect the lockfile and install 2.4.1.

More on package-lock.json:

package-lock.json is automatically generated for any operations where npm modifies either the node_modules tree, or package.json. It describes the exact tree that was generated, such that subsequent installs are able to generate identical trees, regardless of intermediate dependency updates.

This file is intended to be committed into source repositories, and serves various purposes:

Describe a single representation of a dependency tree such that teammates, deployments, and continuous integration are guaranteed to install exactly the same dependencies.

Provide a facility for users to "time-travel" to previous states of node_modules without having to commit the directory itself.

To facilitate greater visibility of tree changes through readable source control diffs.

And optimize the installation process by allowing npm to skip repeated metadata resolutions for previously-installed packages.

https://docs.npmjs.com/files/package-lock.json

How to use ScrollView in Android?

As said above you can put it inside a ScrollView... and if you want the Scroll View to be horizontal put it inside HorizontalScrollView... and if you want your component (or layout) to support both put inside both of them like this:

  <HorizontalScrollView>
        <ScrollView>
            <!-- SOME THING -->
        </ScrollView>
    </HorizontalScrollView>

and with setting the layout_width and layout_height ofcourse.

Returning multiple objects in an R function

Is something along these lines what you are looking for?

x1 = function(x){
  mu = mean(x)
  l1 = list(s1=table(x),std=sd(x))
  return(list(l1,mu))
}

library(Ecdat)
data(Fair)
x1(Fair$age)

Trying to get PyCharm to work, keep getting "No Python interpreter selected"

Even I got the same issue and my mistake was that I didn't download python MSI file. You will get it here: https://www.python.org/downloads/

Once you download the msi, run the setup and that will solve the problem. After that you can go to File->Settings->Project Settings->Project Interpreter->Python Interpreters

and select the python.exe file. (This file will be available at c:\Python34) Select the python.exe file. That's it.

Angular CLI - Please add a @NgModule annotation when using latest

The problem is the import of ProjectsListComponent in your ProjectsModule. You should not import that, but add it to the export array, if you want to use it outside of your ProjectsModule.

Other issues are your project routes. You should add these to an exportable variable, otherwise it's not AOT compatible. And you should -never- import the BrowserModule anywhere else but in your AppModule. Use the CommonModule to get access to the *ngIf, *ngFor...etc directives:

@NgModule({
  declarations: [
     ProjectsListComponent
  ],
  imports: [
    CommonModule,
    RouterModule.forChild(ProjectRoutes)
  ],
  exports: [
     ProjectsListComponent
  ]
})

export class ProjectsModule {}

project.routes.ts

export const ProjectRoutes: Routes = [
      { path: 'projects', component: ProjectsListComponent }
]

Image overlay on responsive sized images bootstrap

If i understand your question you want to have the overlay just over the image and not cover everything?

I'd set the parent DIV (i renamed in content in the jsfiddle) position to relative, as the overlay should be positioned relative to this div not the window.

.content
{
  position: relative;
}

I did some pocking around and updated your fiddle to just have the overlay sized to the img which (I think) is what you want, let me know anyway :) http://jsfiddle.net/b9Vyw/

Waiting until two async blocks are executed before starting another block

The first answer is essentially correct, but if you want the very simplest way to accomplish the desired result, here's a stand-alone code example demonstrating how to do it with a semaphore (which is also how dispatch groups work behind the scenes, JFYI):

#include <dispatch/dispatch.h>
#include <stdio.h>

main()
{
        dispatch_queue_t myQ = dispatch_queue_create("my.conQ", DISPATCH_QUEUE_CONCURRENT);
        dispatch_semaphore_t mySem = dispatch_semaphore_create(0);

        dispatch_async(myQ, ^{ printf("Hi I'm block one!\n"); sleep(2); dispatch_semaphore_signal(mySem);});
        dispatch_async(myQ, ^{ printf("Hi I'm block two!\n"); sleep(4); dispatch_semaphore_signal(mySem);});
        dispatch_async(myQ, ^{ dispatch_semaphore_wait(mySem, DISPATCH_TIME_FOREVER); printf("Hi, I'm the final block!\n"); });
        dispatch_main();
}

I need to know how to get my program to output the word i typed in and also the new rearranged word using a 2D array

  1. What exactly doesn't work?
  2. Why are you using a 2d array?
  3. If you must use a 2d array:

    int numOfPairs = 10;  String[][] array = new String[numOfPairs][2]; for(int i = 0; i < array.length; i++){     for(int j = 0; j < array[i].length; j++){         array[i] = new String[2];         array[i][0] = "original word";         array[i][1] = "rearranged word";     }    } 

Does this give you a hint?

How to find the operating system version using JavaScript?

If you list all of window.navigator's properties using

_x000D_
_x000D_
console.log(navigator);
_x000D_
_x000D_
_x000D_

You'll see something like this

# platform = Win32
# appCodeName = Mozilla
# appName = Netscape
# appVersion = 5.0 (Windows; en-US)
# language = en-US
# mimeTypes = [object MimeTypeArray]
# oscpu = Windows NT 5.1
# vendor = Firefox
# vendorSub = 1.0.7
# product = Gecko
# productSub = 20050915
# plugins = [object PluginArray]
# securityPolicy =
# userAgent = Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.12) Gecko/20050915 Firefox/1.0.7
# cookieEnabled = true
# javaEnabled = function javaEnabled() { [native code] }
# taintEnabled = function taintEnabled() { [native code] }
# preference = function preference() { [native code] }

Note that oscpu attribute gives you the Windows version. Also, you should know that:

'Windows 3.11' => 'Win16',
'Windows 95' => '(Windows 95)|(Win95)|(Windows_95)',
'Windows 98' => '(Windows 98)|(Win98)',
'Windows 2000' => '(Windows NT 5.0)|(Windows 2000)',
'Windows XP' => '(Windows NT 5.1)|(Windows XP)',
'Windows Server 2003' => '(Windows NT 5.2)',
'Windows Vista' => '(Windows NT 6.0)',
'Windows 7' => '(Windows NT 6.1)',
'Windows 8' => '(Windows NT 6.2)|(WOW64)',
'Windows 10' => '(Windows 10.0)|(Windows NT 10.0)',
'Windows NT 4.0' => '(Windows NT 4.0)|(WinNT4.0)|(WinNT)|(Windows NT)',
'Windows ME' => 'Windows ME',
'Open BSD' => 'OpenBSD',
'Sun OS' => 'SunOS',
'Linux' => '(Linux)|(X11)',
'Mac OS' => '(Mac_PowerPC)|(Macintosh)',
'QNX' => 'QNX',
'BeOS' => 'BeOS',
'OS/2' => 'OS/2',
'Search Bot'=>'(nuhk)|(Googlebot)|(Yammybot)|(Openbot)|(Slurp)|(MSNBot)|(Ask Jeeves/Teoma)|(ia_archiver)'

How to do an INNER JOIN on multiple columns

You can JOIN with the same table more than once by giving the joined tables an alias, as in the following example:

SELECT 
    airline, flt_no, fairport, tairport, depart, arrive, fare
FROM 
    flights
INNER JOIN 
    airports from_port ON (from_port.code = flights.fairport)
INNER JOIN
    airports to_port ON (to_port.code = flights.tairport)
WHERE 
    from_port.code = '?' OR to_port.code = '?' OR airports.city='?'

Note that the to_port and from_port are aliases for the first and second copies of the airports table.

How to loop through an array of objects in swift

You can try using the simple NSArray in syntax for iterating over the array in swift which makes for shorter code. The following is working for me:

class ModelAttachment {
    var id: String?
    var url: String?
    var thumb: String?
}

var modelAttachementObj = ModelAttachment()
modelAttachementObj.id = "1"
modelAttachementObj.url = "http://www.google.com"
modelAttachementObj.thumb = "thumb"

var imgs: Array<ModelAttachment> = [modelAttachementObj]

for img in imgs  {
    let url = img.url
    NSLog(url!)
}

See docs here

Angular 4 - get input value

You can use (keyup) or (change) events, see example below:

in HTML:

<input (keyup)="change($event)">

Or

<input (change)="change($event)">

in Component:

change(event) {console.log(event.target.value);}

Handling a Menu Item Click Event - Android

in addition to the options shown in your question, there is the possibility of implementing the action directly in your xml file from the menu, for example:

<item
   android:id="@+id/OK_MENU_ITEM"
   android:onClick="showMsgDirectMenuXml" />

And for your Java (Activity) file, you need to implement a public method with a single parameter of type MenuItem, for example:

 private void showMsgDirectMenuXml(MenuItem item) {
    Toast toast = Toast.makeText(this, "OK", Toast.LENGTH_LONG);
    toast.show();
  }

NOTE: This method will have behavior similar to the onOptionsItemSelected (MenuItem item)

How to capture a backspace on the onkeydown event

Nowadays, code to do this should look something like:

document.getElementById('foo').addEventListener('keydown', function (event) {
    if (event.keyCode == 8) {
        console.log('BACKSPACE was pressed');

        // Call event.preventDefault() to stop the character before the cursor
        // from being deleted. Remove this line if you don't want to do that.
        event.preventDefault();
    }
    if (event.keyCode == 46) {
        console.log('DELETE was pressed');

        // Call event.preventDefault() to stop the character after the cursor
        // from being deleted. Remove this line if you don't want to do that.
        event.preventDefault();
    }
});

although in the future, once they are broadly supported in browsers, you may want to use the .key or .code attributes of the KeyboardEvent instead of the deprecated .keyCode.

Details worth knowing:

  • Calling event.preventDefault() in the handler of a keydown event will prevent the default effects of the keypress. When pressing a character, this stops it from being typed into the active text field. When pressing backspace or delete in a text field, it prevents a character from being deleted. When pressing backspace without an active text field, in a browser like Chrome where backspace takes you back to the previous page, it prevents that behaviour (as long as you catch the event by adding your event listener to document instead of a text field).

  • Documentation on how the value of the keyCode attribute is determined can be found in section B.2.1 How to determine keyCode for keydown and keyup events in the W3's UI Events Specification. In particular, the codes for Backspace and Delete are listed in B.2.3 Fixed virtual key codes.

  • There is an effort underway to deprecate the .keyCode attribute in favour of .key and .code. The W3 describe the .keyCode property as "legacy", and MDN as "deprecated".

    One benefit of the change to .key and .code is having more powerful and programmer-friendly handling of non-ASCII keys - see the specification that lists all the possible key values, which are human-readable strings like "Backspace" and "Delete" and include values for everything from modifier keys specific to Japanese keyboards to obscure media keys. Another, which is highly relevant to this question, is distinguishing between the meaning of a modified keypress and the physical key that was pressed.

    On small Mac keyboards, there is no Delete key, only a Backspace key. However, pressing Fn+Backspace is equivalent to pressing Delete on a normal keyboard - that is, it deletes the character after the text cursor instead of the one before it. Depending upon your use case, in code you might want to handle a press of Backspace with Fn held down as either Backspace or Delete. That's why the new key model lets you choose.

    The .key attribute gives you the meaning of the keypress, so Fn+Backspace will yield the string "Delete". The .code attribute gives you the physical key, so Fn+Backspace will still yield the string "Backspace".

    Unfortunately, as of writing this answer, they're only supported in 18% of browsers, so if you need broad compatibility you're stuck with the "legacy" .keyCode attribute for the time being. But if you're a reader from the future, or if you're targeting a specific platform and know it supports the new interface, then you could write code that looked something like this:

    document.getElementById('foo').addEventListener('keydown', function (event) {
        if (event.code == 'Delete') {
            console.log('The physical key pressed was the DELETE key');
        }
        if (event.code == 'Backspace') {
            console.log('The physical key pressed was the BACKSPACE key');
        } 
        if (event.key == 'Delete') {
            console.log('The keypress meant the same as pressing DELETE');
            // This can happen for one of two reasons:
            // 1. The user pressed the DELETE key
            // 2. The user pressed FN+BACKSPACE on a small Mac keyboard where
            //    FN+BACKSPACE deletes the character in front of the text cursor,
            //    instead of the one behind it.
        }
        if (event.key == 'Backspace') {
            console.log('The keypress meant the same as pressing BACKSPACE');
        }
    });
    

Target Unreachable, identifier resolved to null in JSF 2.2

I solved this problem.

My Java version was the 1.6 and I found that was using 1.7 with CDI however after that I changed the Java version to 1.7 and import the package javax.faces.bean.ManagedBean and everything worked.

Thanks @PM77-1


git clone from another directory

Using the path itself didn't work for me.

Here's what finally worked for me on MacOS:

cd ~/projects
git clone file:///Users/me/projects/myawesomerepo myawesomerepocopy

This also worked:

git clone file://localhost/Users/me/projects/myawesomerepo myawesomerepocopy

The path itself worked if I did this:

git clone --local myawesomerepo myawesomerepocopy

Pass multiple arguments into std::thread

If you're getting this, you may have forgotten to put #include <thread> at the beginning of your file. OP's signature seems like it should work.

Find oldest/youngest datetime object in a list

Oldest:

oldest = min(datetimes)

Youngest before now:

now = datetime.datetime.now(pytz.utc)
youngest = max(dt for dt in datetimes if dt < now)

Running a CMD or BAT in silent mode

Include the phrase:

@echo off

Right at the top of your bat script.

What's the difference between Invoke() and BeginInvoke()

The difference between Control.Invoke() and Control.BeginInvoke() is,

  • BeginInvoke() will schedule the asynchronous action on the GUI thread. When the asynchronous action is scheduled, your code continues. Some time later (you don't know exactly when) your asynchronous action will be executed
  • Invoke() will execute your asynchronous action (on the GUI thread) and wait until your action has completed.

A logical conclusion is that a delegate you pass to Invoke() can have out-parameters or a return-value, while a delegate you pass to BeginInvoke() cannot (you have to use EndInvoke to retrieve the results).

Debugging the error "gcc: error: x86_64-linux-gnu-gcc: No such file or directory"

apt-get install python-dev

...solved the problem for me.

Organizing a multiple-file Go project

I find very useful to understand how to organize code in Golang this chapter http://www.golang-book.com/11 of the book written by Caleb Doxsey

"Cannot create an instance of OLE DB provider" error as Windows Authentication user

In SQL Server Enterprise Manager, open \Server Objects\Linked Servers\Providers, right click on the OraOLEDB.Oracle provider, select properties and check the "Allow inprocess" option. Recreate your linked server and test again.

You can also execute the following query if you don't have access to SQL Server Management Studio :

EXEC master.dbo.sp_MSset_oledb_prop N'OraOLEDB.Oracle', N'AllowInProcess', 1

What are the retransmission rules for TCP?

There's no fixed time for retransmission. Simple implementations estimate the RTT (round-trip-time) and if no ACK to send data has been received in 2x that time then they re-send.

They then double the wait-time and re-send once more if again there is no reply. Rinse. Repeat.

More sophisticated systems make better estimates of how long it should take for the ACK as well as guesses about exactly which data has been lost.

The bottom-line is that there is no hard-and-fast rule about exactly when to retransmit. It's up to the implementation. All retransmissions are triggered solely by the sender based on lack of response from the receiver.

TCP never drops data so no, there is no way to indicate a server should forget about some segment.

How to replace values at specific indexes of a python list?

You can use operator.setitem.

from operator import setitem
a = [5, 4, 3, 2, 1, 0]
ell = [0, 1, 3, 5]
m = [0, 0, 0, 0]
for b, c in zip(ell, m):
    setitem(a, b, c)
>>> a
[0, 0, 3, 0, 1, 0]

Is it any more readable or efficient than your solution? I am not sure!

How can I add a new column and data to a datatable that already contains data?

Only you want to set default value parameter. This calling third overloading method.

dt.Columns.Add("MyRow", type(System.Int32),0);

Difference between "or" and || in Ruby?

The way I use these operators:

||, && are for boolean logic. or, and are for control flow. E.g.

do_smth if may_be || may_be -- we evaluate the condition here

do_smth or do_smth_else -- we define the workflow, which is equivalent to do_smth_else unless do_smth

to give a simple example:

> puts "a" && "b"
b

> puts 'a' and 'b'
a

A well-known idiom in Rails is render and return. It's a shortcut for saying return if render, while render && return won't work. See "Avoiding Double Render Errors" in the Rails documentation for more information.

Failed to resolve version for org.apache.maven.archetypes

I had the same problem i solved it by only adding remote catalog in eclipse go to Window -> Preferences ->Maven ->Archetypes ->click on add remote Catalog then a window will open in that paste
http://repo.maven.apache.org/maven2/archetype-catalog.xml in that catalog file then hit ok restart eclipse now all working fine

If "0" then leave the cell blank

You can change the number format of the column to this custom format:

0;-0;;@

which will hide all 0 values.

To do this, select the column, right-click > Format Cells > Custom.

How to list all the files in a commit?

Preferred Way (because it's a plumbing command; meant to be programmatic):

$ git diff-tree --no-commit-id --name-only -r bd61ad98
index.html
javascript/application.js
javascript/ie6.js

Another Way (less preferred for scripts, because it's a porcelain command; meant to be user-facing)

$ git show --pretty="" --name-only bd61ad98    
index.html
javascript/application.js
javascript/ie6.js

  • The --no-commit-id suppresses the commit ID output.
  • The --pretty argument specifies an empty format string to avoid the cruft at the beginning.
  • The --name-only argument shows only the file names that were affected (Thanks Hank). Use --name-status instead, if you want to see what happened to each file (Deleted, Modified, Added)
  • The -r argument is to recurse into sub-trees

Iterating over dictionaries using 'for' loops

If you are looking for a clear and visual example:

cat  = {'name': 'Snowy', 'color': 'White' ,'age': 14}
for key , value in cat.items():
   print(key, ': ', value)

Result:

name:  Snowy
color:  White
age:  14

HTTP Status 500 - org.apache.jasper.JasperException: java.lang.NullPointerException

In Tomcat a .java and .class file will be created for every jsp files with in the application and the same can be found from the path below, Apache-Tomcat\work\Catalina\localhost\'ApplicationName'\org\apache\jsp\index_jsp.java

In your case the jsp name is error.jsp so the path should be something like below Apache-Tomcat\work\Catalina\localhost\'ApplicationName'\org\apache\jsp\error_jsp.java in line no 124 you are trying to access a null object which results in null pointer exception.

AccessDenied for ListObjects for S3 bucket when permissions are s3:*

I was unable to access to S3 because

  • first I configured key access on the instance (it was impossible to attach role after the launch then)
  • forgot about it for a few months
  • attached role to instance
  • tried to access. The configured key had higher priority than role, and access was denied because the user wasn't granted with necessary S3 permissions.

Solution: rm -rf .aws/credentials, then aws uses role.

Creating a dynamic choice field

the problem is when you do

def __init__(self, user, *args, **kwargs):
    super(waypointForm, self).__init__(*args, **kwargs)
    self.fields['waypoints'] = forms.ChoiceField(choices=[ (o.id, str(o)) for o in Waypoint.objects.filter(user=user)])

in a update request, the previous value will lost!

Mask for an Input to allow phone numbers?

I do this using the TextMaskModule from 'angular2-text-mask'

Mine are split but you can get the idea

Package using NPM NodeJS

"dependencies": {
    "angular2-text-mask": "8.0.0",

HTML

<input *ngIf="column?.type =='areaCode'" type="text" [textMask]="{mask: areaCodeMask}" [(ngModel)]="areaCodeModel">


<input *ngIf="column?.type =='phone'" type="text" [textMask]="{mask: phoneMask}" [(ngModel)]="phoneModel"> 

Inside Component

public areaCodeModel = '';
public areaCodeMask = ['(', /[1-9]/, /\d/, /\d/, ')'];

public phoneModel = '';
public phoneMask = [/\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/];

How can I force component to re-render with hooks in React?

This will render depending components 3 times (arrays with equal elements aren't equal):

const [msg, setMsg] = useState([""])

setMsg(["test"])
setMsg(["test"])
setMsg(["test"])

referenced before assignment error in python

I think you are using 'global' incorrectly. See Python reference. You should declare variable without global and then inside the function when you want to access global variable you declare it global yourvar.

#!/usr/bin/python

total

def checkTotal():
    global total
    total = 0

See this example:

#!/usr/bin/env python

total = 0

def doA():
    # not accessing global total
    total = 10

def doB():
    global total
    total = total + 1

def checkTotal():
    # global total - not required as global is required
    # only for assignment - thanks for comment Greg
    print total

def main():
    doA()
    doB()
    checkTotal()

if __name__ == '__main__':
    main()

Because doA() does not modify the global total the output is 1 not 11.

How do I execute a file in Cygwin?

gcc under cygwin does not generate a Linux executable output file of type " ELF 32-bit LSB executable," but it generates a windows executable of type "PE32 executable for MS Windows" which has a dependency on cygwin1.dll, so it needs to be run under cygwin shell. If u need to run it under dos prompt independently, they cygwin1.dll needs to be in your Windows PATH.

-AD.

Memory Allocation "Error: cannot allocate vector of size 75.1 Mb"

R has gotten to the point where the OS cannot allocate it another 75.1Mb chunk of RAM. That is the size of memory chunk required to do the next sub-operation. It is not a statement about the amount of contiguous RAM required to complete the entire process. By this point, all your available RAM is exhausted but you need more memory to continue and the OS is unable to make more RAM available to R.

Potential solutions to this are manifold. The obvious one is get hold of a 64-bit machine with more RAM. I forget the details but IIRC on 32-bit Windows, any single process can only use a limited amount of RAM (2GB?) and regardless Windows will retain a chunk of memory for itself, so the RAM available to R will be somewhat less than the 3.4Gb you have. On 64-bit Windows R will be able to use more RAM and the maximum amount of RAM you can fit/install will be increased.

If that is not possible, then consider an alternative approach; perhaps do your simulations in batches with the n per batch much smaller than N. That way you can draw a much smaller number of simulations, do whatever you wanted, collect results, then repeat this process until you have done sufficient simulations. You don't show what N is, but I suspect it is big, so try smaller N a number of times to give you N over-all.

PHP strtotime +1 month adding an extra month

 $endOfCycle = date("Y-m", mktime(0, 0, 0, date("m", time())+1 , 15, date("m", time())));

add onclick function to a submit button

html:

<form method="post" name="form1" id="form1">    
    <input id="submit" name="submit" type="submit" value="Submit" onclick="eatFood();" />
</form>

Javascript: to submit the form using javascript

function eatFood() {
document.getElementById('form1').submit();
}

to show onclick message

function eatFood() {
alert('Form has been submitted');
}

is python capable of running on multiple cores?

I converted the script to Python3 and ran it on my Raspberry Pi 3B+:

import time
import threading

def t():
        with open('/dev/urandom', 'rb') as f:
                for x in range(100):
                        f.read(4 * 65535)

if __name__ == '__main__':
    start_time = time.time()
    t()
    t()
    t()
    t()
    print("Sequential run time: %.2f seconds" % (time.time() - start_time))

    start_time = time.time()
    t1 = threading.Thread(target=t)
    t2 = threading.Thread(target=t)
    t3 = threading.Thread(target=t)
    t4 = threading.Thread(target=t)
    t1.start()
    t2.start()
    t3.start()
    t4.start()
    t1.join()
    t2.join()
    t3.join()
    t4.join()
    print("Parallel run time: %.2f seconds" % (time.time() - start_time))

python3 t.py

Sequential run time: 2.10 seconds
Parallel run time: 1.41 seconds

For me, running parallel was quicker.

Creating Threads in python

You don't need to use a subclass of Thread to make this work - take a look at the simple example I'm posting below to see how:

from threading import Thread
from time import sleep

def threaded_function(arg):
    for i in range(arg):
        print("running")
        sleep(1)


if __name__ == "__main__":
    thread = Thread(target = threaded_function, args = (10, ))
    thread.start()
    thread.join()
    print("thread finished...exiting")

Here I show how to use the threading module to create a thread which invokes a normal function as its target. You can see how I can pass whatever arguments I need to it in the thread constructor.

Attach a body onload event with JS

Cross browser window.load event

function load(){}

window[ addEventListener ? 'addEventListener' : 'attachEvent' ]( addEventListener ? 'load' : 'onload', load )

What is the difference between loose coupling and tight coupling in the object oriented paradigm?

Tight coupling means classes and objects are dependent on one another. In general, tight coupling is usually not good because it reduces the flexibility and re-usability of the code while Loose coupling means reducing the dependencies of a class that uses the different class directly.

Tight Coupling The tightly coupled object is an object that needs to know about other objects and is usually highly dependent on each other's interfaces. Changing one object in a tightly coupled application often requires changes to a number of other objects. In the small applications, we can easily identify the changes and there is less chance to miss anything. But in large applications, these inter-dependencies are not always known by every programmer and there is a chance of overlooking changes. Example:

    class A {
       public int a = 0;
       public int getA() {
          System.out.println("getA() method");
          return a;
       }
       public void setA(int aa) {
          if(!(aa > 10))
             a = aa;
       }
    }
    public class B {
       public static void main(String[] args) {
          A aObject = new A();
          aObject.a = 100; // Not suppose to happen as defined by class A, this causes tight coupling.
          System.out.println("aObject.a value is: " + aObject.a);
       }
    }

In the above example, the code that is defined by this kind of implementation uses tight coupling and is very bad since class B knows about the detail of class A, if class A changes the variable 'a' to private then class B breaks, also class A's implementation states that variable 'a' should not be more than 10 but as we can see there is no way to enforce such a rule as we can go directly to the variable and change its state to whatever value we decide.

    Output
    aObject.a value is: 100

Loose Coupling
Loose coupling is a design goal to reduce the inter-dependencies between components of a system with the goal of reducing the risk that changes in one component will require changes in any other component.
Loose coupling is a much more generic concept intended to increase the flexibility of the system, make it more maintainable and makes the entire framework more stable.
Example:

class A {
   private int a = 0;
   public int getA() {
      System.out.println("getA() method");
      return a;
   }
   public void setA(int aa) {
      if(!(aa > 10))
         a = aa;
   }
}
public class B {
   public static void main(String[] args) {
      A aObject = new A();
      aObject.setA(100); // No way to set 'a' to such value as this method call will
                         // fail due to its enforced rule.
      System.out.println("aObject value is: " + aObject.getA());
   }
}

In the above example, the code that is defined by this kind of implementation uses loose coupling and is recommended since class B has to go through class A to get its state where rules are enforced. If class A is changed internally, class B will not break as it uses only class A as a way of communication.

Output
getA() method
aObject value is: 0

Cancel a vanilla ECMAScript 6 Promise chain

If your code is placed in a class you could use a decorator for that. You have such decorator in the utils-decorators (npm install --save utils-decorators). It will cancel the previous invocation of the decorated method if before the resolving of the previous call there was made another call for that specific method.

import {cancelPrevious} from 'utils-decorators';

class SomeService {

   @cancelPrevious()
   doSomeAsync(): Promise<any> {
    ....
   }
}

or you could use a wrapper function:

import {cancelPreviousify} from 'utils-decorators';

const cancelable = cancelPreviousify(originalMethod)

https://github.com/vlio20/utils-decorators#cancelprevious-method

How do I set vertical space between list items?

<br>between <li></li> line entries seems to work perfectly well in all web browsers that I've tried, but it fails to pass the on-line W3C CSS3 checker. It gives me precisely the line spacing I am after. As far as I am concerned, since it undoubtedly works, I am persisting in using it, whatever W3C says, until someone can come up with a good legal alternative.

Operator overloading ==, !=, Equals

I think you declared the Equals method like this:

public override bool Equals(BOX obj)

Since the object.Equals method takes an object, there is no method to override with this signature. You have to override it like this:

public override bool Equals(object obj)

If you want type-safe Equals, you can implement IEquatable<BOX>.

Replace all spaces in a string with '+'

NON BREAKING SPACE ISSUE

In some browsers

(MSIE "as usually" ;-))

replacing space in string ignores the non-breaking space (the 160 char code).

One should always replace like this:

myString.replace(/[ \u00A0]/, myReplaceString)

Very nice detailed explanation:

http://www.adamkoch.com/2009/07/25/white-space-and-character-160/

What is the optimal algorithm for the game 2048?

There is already an AI implementation for this game here. Excerpt from README:

The algorithm is iterative deepening depth first alpha-beta search. The evaluation function tries to keep the rows and columns monotonic (either all decreasing or increasing) while minimizing the number of tiles on the grid.

There is also a discussion on Hacker News about this algorithm that you may find useful.

How do I make an HTML button not reload the page

I can't comment yet, so I'm posting this as an answer. Best way to avoid reload is how @user2868288 said: using the onsubmit on the form tag.

From all the other possibilities mentioned here, it's the only way which allows the new HTML5 browser data input validation to be triggered (<button> won't do it nor the jQuery/JS handlers) and allows your jQuery/AJAX dynamic info to be appended on the page. For example:

<form id="frmData" onsubmit="return false">
 <input type="email" id="txtEmail" name="input_email" required="" placeholder="Enter a valid e-mail" spellcheck="false"/>
 <input type="tel" id="txtTel" name="input_tel" required="" placeholder="Enter your telephone number" spellcheck="false"/>
 <input type="submit" id="btnSubmit" value="Send Info"/>
</form>
<script type="text/javascript">
  $(document).ready(function(){
    $('#btnSubmit').click(function() {
        var tel = $("#txtTel").val();
        var email = $("#txtEmail").val();
        $.post("scripts/contact.php", {
            tel1: tel,
            email1: email
        })
        .done(function(data) {
            $('#lblEstatus').append(data); // Appends status
            if (data == "Received") {
                $("#btnSubmit").attr('disabled', 'disabled'); // Disable doubleclickers.
            }
        })
        .fail(function(xhr, textStatus, errorThrown) { 
            $('#lblEstatus').append("Error. Try later."); 
        });
     });
   }); 
</script>

Selecting a row of pandas series/dataframe by integer index

The primary purpose of the DataFrame indexing operator, [] is to select columns.

When the indexing operator is passed a string or integer, it attempts to find a column with that particular name and return it as a Series.

So, in the question above: df[2] searches for a column name matching the integer value 2. This column does not exist and a KeyError is raised.


The DataFrame indexing operator completely changes behavior to select rows when slice notation is used

Strangely, when given a slice, the DataFrame indexing operator selects rows and can do so by integer location or by index label.

df[2:3]

This will slice beginning from the row with integer location 2 up to 3, exclusive of the last element. So, just a single row. The following selects rows beginning at integer location 6 up to but not including 20 by every third row.

df[6:20:3]

You can also use slices consisting of string labels if your DataFrame index has strings in it. For more details, see this solution on .iloc vs .loc.

I almost never use this slice notation with the indexing operator as its not explicit and hardly ever used. When slicing by rows, stick with .loc/.iloc.