Programs & Examples On #External dependencies

How do files get into the External Dependencies in Visual Studio C++?

The External Dependencies folder is populated by IntelliSense: the contents of the folder do not affect the build at all (you can in fact disable the folder in the UI).

You need to actually include the header (using a #include directive) to use it. Depending on what that header is, you may also need to add its containing folder to the "Additional Include Directories" property and you may need to add additional libraries and library folders to the linker options; you can set all of these in the project properties (right click the project, select Properties). You should compare the properties with those of the project that does build to determine what you need to add.

How to bundle vendor scripts separately and require them as needed with Webpack?

I am not sure if I fully understand your problem but since I had similar issue recently I will try to help you out.

Vendor bundle.

You should use CommonsChunkPlugin for that. in the configuration you specify the name of the chunk (e.g. vendor), and file name that will be generated (vendor.js).

new webpack.optimize.CommonsChunkPlugin("vendor", "vendor.js", Infinity),

Now important part, you have to now specify what does it mean vendor library and you do that in an entry section. One one more item to entry list with the same name as the name of the newly declared chunk (i.e. 'vendor' in this case). The value of that entry should be the list of all the modules that you want to move to vendor bundle. in your case it should look something like:

entry: {
    app: 'entry.js',
    vendor: ['jquery', 'jquery.plugin1']
}

JQuery as global

Had the same problem and solved it with ProvidePlugin. here you are not defining global object but kind of shurtcuts to modules. i.e. you can configure it like that:

new webpack.ProvidePlugin({
    $: "jquery"
})

And now you can just use $ anywhere in your code - webpack will automatically convert that to

require('jquery')

I hope it helped. you can also look at my webpack configuration file that is here

I love webpack, but I agree that the documentation is not the nicest one in the world... but hey.. people were saying same thing about Angular documentation in the begining :)


Edit:

To have entrypoint-specific vendor chunks just use CommonsChunkPlugins multiple times:

new webpack.optimize.CommonsChunkPlugin("vendor-page1", "vendor-page1.js", Infinity),
new webpack.optimize.CommonsChunkPlugin("vendor-page2", "vendor-page2.js", Infinity),

and then declare different extenral libraries for different files:

entry: {
    page1: ['entry.js'],
    page2: ['entry2.js'],
    "vendor-page1": [
        'lodash'
    ],
    "vendor-page2": [
        'jquery'
    ]
},

If some libraries are overlapping (and for most of them) between entry points then you can extract them to common file using same plugin just with different configuration. See this example.

Delete the 'first' record from a table in SQL Server, without a WHERE condition

SQL-92:

DELETE Field FROM Table WHERE Field IN (SELECT TOP 1 Field FROM Table ORDER BY Field DESC)

error LNK2005, already defined?

And if you want these translation units to share this variable, define int k; in A.cpp and put extern int k; in B.cpp.

How can I group data with an Angular filter?

In addition to the accepted answers above I created a generic 'groupBy' filter using the underscore.js library.

JSFiddle (updated): http://jsfiddle.net/TD7t3/

The filter

app.filter('groupBy', function() {
    return _.memoize(function(items, field) {
            return _.groupBy(items, field);
        }
    );
});

Note the 'memoize' call. This underscore method caches the result of the function and stops angular from evaluating the filter expression every time, thus preventing angular from reaching the digest iterations limit.

The html

<ul>
    <li ng-repeat="(team, players) in teamPlayers | groupBy:'team'">
        {{team}}
        <ul>
            <li ng-repeat="player in players">
                {{player.name}}
            </li>
        </ul>
    </li>
</ul>

We apply our 'groupBy' filter on the teamPlayers scope variable, on the 'team' property. Our ng-repeat receives a combination of (key, values[]) that we can use in our following iterations.

Update June 11th 2014 I expanded the group by filter to account for the use of expressions as the key (eg nested variables). The angular parse service comes in quite handy for this:

The filter (with expression support)

app.filter('groupBy', function($parse) {
    return _.memoize(function(items, field) {
        var getter = $parse(field);
        return _.groupBy(items, function(item) {
            return getter(item);
        });
    });
});

The controller (with nested objects)

app.controller('homeCtrl', function($scope) {
    var teamAlpha = {name: 'team alpha'};
    var teamBeta = {name: 'team beta'};
    var teamGamma = {name: 'team gamma'};

    $scope.teamPlayers = [{name: 'Gene', team: teamAlpha},
                      {name: 'George', team: teamBeta},
                      {name: 'Steve', team: teamGamma},
                      {name: 'Paula', team: teamBeta},
                      {name: 'Scruath of the 5th sector', team: teamGamma}];
});

The html (with sortBy expression)

<li ng-repeat="(team, players) in teamPlayers | groupBy:'team.name'">
    {{team}}
    <ul>
        <li ng-repeat="player in players">
            {{player.name}}
        </li>
    </ul>
</li>

JSFiddle: http://jsfiddle.net/k7fgB/2/

Finding length of char array

If anyone is looking for a quick fix for this, here's how you do it.

while (array[i] != '\0') i++;

The variable i will hold the used length of the array, not the entire initialized array. I know it's a late post, but it may help someone.

c# datagridview doubleclick on row with FullRowSelect

For your purpose, there is a default event when the row header is double-clicked. Check the following code,

 private void dgvCustom_RowHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
 {
      //Your code goes here
 }

Remove an item from array using UnderscoreJS

Just using plain JavaScript, this has been answered already: remove objects from array by object property.

Using underscore.js, you could combine .findWhere with .without:

_x000D_
_x000D_
var arr = [{_x000D_
  id: 1,_x000D_
  name: 'a'_x000D_
}, {_x000D_
  id: 2,_x000D_
  name: 'b'_x000D_
}, {_x000D_
  id: 3,_x000D_
  name: 'c'_x000D_
}];_x000D_
_x000D_
//substract third_x000D_
arr = _.without(arr, _.findWhere(arr, {_x000D_
  id: 3_x000D_
}));_x000D_
console.log(arr);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
_x000D_
_x000D_
_x000D_

Although, since you are creating a new array in this case anyway, you could simply use _.filter or the native Array.prototype.filter function (just like shown in the other question). Then you would only iterate over array once instead of potentially twice like here.

If you want to modify the array in-place, you have to use .splice. This is also shown in the other question and undescore doesn't seem to provide any useful function for that.

How to know if a DateTime is between a DateRange in C#

Following on from Sergey's answer, I think this more generic version is more in line with Fowler's Range idea, and resolves some of the issues with that answer such as being able to have the Includes methods within a generic class by constraining T as IComparable<T>. It's also immutable like what you would expect with types that extend the functionality of other value types like DateTime.

public struct Range<T> where T : IComparable<T>
{
    public Range(T start, T end)
    {
        Start = start;
        End = end;
    }

    public T Start { get; }

    public T End { get; }

    public bool Includes(T value) => Start.CompareTo(value) <= 0 && End.CompareTo(value) >= 0;

    public bool Includes(Range<T> range) => Start.CompareTo(range.Start) <= 0 && End.CompareTo(range.End) >= 0;
}

How to convert Django Model object to dict with its fields and values?

There are many ways to convert an instance to a dictionary, with varying degrees of corner case handling and closeness to the desired result.


1. instance.__dict__

instance.__dict__

which returns

{'_foreign_key_cache': <OtherModel: OtherModel object>,
 '_state': <django.db.models.base.ModelState at 0x7ff0993f6908>,
 'auto_now_add': datetime.datetime(2018, 12, 20, 21, 34, 29, 494827, tzinfo=<UTC>),
 'foreign_key_id': 2,
 'id': 1,
 'normal_value': 1,
 'readonly_value': 2}

This is by far the simplest, but is missing many_to_many, foreign_key is misnamed, and it has two unwanted extra things in it.


2. model_to_dict

from django.forms.models import model_to_dict
model_to_dict(instance)

which returns

{'foreign_key': 2,
 'id': 1,
 'many_to_many': [<OtherModel: OtherModel object>],
 'normal_value': 1}

This is the only one with many_to_many, but is missing the uneditable fields.


3. model_to_dict(..., fields=...)

from django.forms.models import model_to_dict
model_to_dict(instance, fields=[field.name for field in instance._meta.fields])

which returns

{'foreign_key': 2, 'id': 1, 'normal_value': 1}

This is strictly worse than the standard model_to_dict invocation.


4. query_set.values()

SomeModel.objects.filter(id=instance.id).values()[0]

which returns

{'auto_now_add': datetime.datetime(2018, 12, 20, 21, 34, 29, 494827, tzinfo=<UTC>),
 'foreign_key_id': 2,
 'id': 1,
 'normal_value': 1,
 'readonly_value': 2}

This is the same output as instance.__dict__ but without the extra fields. foreign_key_id is still wrong and many_to_many is still missing.


5. Custom Function

The code for django's model_to_dict had most of the answer. It explicitly removed non-editable fields, so removing that check and getting the ids of foreign keys for many to many fields results in the following code which behaves as desired:

from itertools import chain

def to_dict(instance):
    opts = instance._meta
    data = {}
    for f in chain(opts.concrete_fields, opts.private_fields):
        data[f.name] = f.value_from_object(instance)
    for f in opts.many_to_many:
        data[f.name] = [i.id for i in f.value_from_object(instance)]
    return data

While this is the most complicated option, calling to_dict(instance) gives us exactly the desired result:

{'auto_now_add': datetime.datetime(2018, 12, 20, 21, 34, 29, 494827, tzinfo=<UTC>),
 'foreign_key': 2,
 'id': 1,
 'many_to_many': [2],
 'normal_value': 1,
 'readonly_value': 2}

6. Use Serializers

Django Rest Framework's ModelSerialzer allows you to build a serializer automatically from a model.

from rest_framework import serializers
class SomeModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = SomeModel
        fields = "__all__"

SomeModelSerializer(instance).data

returns

{'auto_now_add': '2018-12-20T21:34:29.494827Z',
 'foreign_key': 2,
 'id': 1,
 'many_to_many': [2],
 'normal_value': 1,
 'readonly_value': 2}

This is almost as good as the custom function, but auto_now_add is a string instead of a datetime object.


Bonus Round: better model printing

If you want a django model that has a better python command-line display, have your models child-class the following:

from django.db import models
from itertools import chain

class PrintableModel(models.Model):
    def __repr__(self):
        return str(self.to_dict())

    def to_dict(instance):
        opts = instance._meta
        data = {}
        for f in chain(opts.concrete_fields, opts.private_fields):
            data[f.name] = f.value_from_object(instance)
        for f in opts.many_to_many:
            data[f.name] = [i.id for i in f.value_from_object(instance)]
        return data

    class Meta:
        abstract = True

So, for example, if we define our models as such:

class OtherModel(PrintableModel): pass

class SomeModel(PrintableModel):
    normal_value = models.IntegerField()
    readonly_value = models.IntegerField(editable=False)
    auto_now_add = models.DateTimeField(auto_now_add=True)
    foreign_key = models.ForeignKey(OtherModel, related_name="ref1")
    many_to_many = models.ManyToManyField(OtherModel, related_name="ref2")

Calling SomeModel.objects.first() now gives output like this:

{'auto_now_add': datetime.datetime(2018, 12, 20, 21, 34, 29, 494827, tzinfo=<UTC>),
 'foreign_key': 2,
 'id': 1,
 'many_to_many': [2],
 'normal_value': 1,
 'readonly_value': 2}

Resize on div element

I've created jquery plugin jquery.resize it use resizeObserver if supported or solution based on marcj/css-element-queries scroll event, no setTimeout/setInterval.

You use just

 jQuery('div').on('resize', function() { /* What ever */ });

or as resizer plugin

jQuery('div').resizer(function() { /* What ever */ });

I've created this for jQuery Terminal and extracted into separated repo and npm package, but in a mean time I switched to hidden iframe because I had problems with resize if element was inside iframe. I may update the plugin accordingly. You can look at iframe based resizer plugin in jQuery Terminal source code.

EDIT: new version use iframe and resize on it's window object because the previous solutions was not working when page was inside iframe.

EDIT2: Because the fallback use iframe you can't use it with form controls or images, you need to add it to the wrapper element.

EDIT3:: there is better solution using resizeObserver polyfill that use mutation observer (if resizeObserver is not supported) and work even in IE. It also have TypeScript typings.

Javascript: Uncaught TypeError: Cannot call method 'addEventListener' of null

Move script tag at the end of BODY instead of HEAD because in current code when the script is computed html element doesn't exist in document.

Since you don't want to you jquery. Use window.onload or document.onload to execute the entire piece of code that you have in current script tag. window.onload vs document.onload

How to rename a class and its corresponding file in Eclipse?

You can rename classes or any file by hitting F2 on the filename in Eclipse. It will ask you if you want to update references. It's really as easy as that :)

Transparent color of Bootstrap-3 Navbar

.navbar {
   background-color: transparent;
   background: transparent;
   border-color: transparent;
}

.navbar li { color: #000 } 

http://bootply.com/106969

Can I change the scroll speed using css or jQuery?

Just use this js file. (I mentioned 2 examples with different js files. hope the second one is what you need) You can simply change the scroll amount, speed etc by changing the parameters.

https://github.com/nathco/jQuery.scrollSpeed

Here's a Demo

You can also try this. Here's a demo

Twitter Bootstrap Datepicker within modal window

try use this code it works for me. by the way it came from this site https://github.com/eternicode/bootstrap-datepicker/issues/464 .

$('#datepicker').datepicker().on('show', function () {
                var modal = $('#datepicker').closest('.modal');
                var datePicker = $('body').find('.datepicker');
                if (!modal.length) {
                    $(datePicker).css('z-index', 'auto');
                    return;
                }
                var zIndexModal = $(modal).css('z-index');
                $(datePicker).css('z-index', zIndexModal + 1);
            });

How to check model string property for null in a razor view

Try this first, you may be passing a Null Model:

@if (Model != null && !String.IsNullOrEmpty(Model.ImageName))
{
    <label for="Image">Change picture</label>
}
else
{ 
    <label for="Image">Add picture</label>
}

Otherise, you can make it even neater with some ternary fun! - but that will still error if your model is Null.

<label for="Image">@(String.IsNullOrEmpty(Model.ImageName) ? "Add" : "Change") picture</label>

Where is git.exe located?

Just to add to a couple of answers already here:

On Windows, you can use the built in "where" instead of "which" (which is for Linux). So, where git will tell you the location of git assuming that it is in the system path.

If it is not in the system path, and you want a native (no downloads or installations), reasonable time command to find it, use dir /s git.exe

A reference to the dll could not be added

  1. start cmd.exe and type:
  2. Regsvr32 %dllpath%
  3. "%dllpath%" replace to your dll path

Cloning a private Github repo

Using Git for Windows it is easier to use HTTPS url.

Open a git shell then git clone https://github.com/user/repo. Enter username and password when prompted. No need to setup a SSH key.

Overflow:hidden dots at the end

Try this if you want to restrict the lines up to 3 and after three lines the dots will appear. If we want to increase the lines just change the -webkit-line-clamp value and give the width for div size.

div {
   display: -webkit-box;
   -webkit-line-clamp: 3;
   -webkit-box-orient: vertical;
   overflow: hidden;
   text-overflow: ellipsis;
}

Getting activity from context in android

From your Activity, just pass in this as the Context for your layout:

ProfileView pv = new ProfileView(this, null, temp, tempPd);

Afterwards you will have a Context in the layout, but you will know it is actually your Activity and you can cast it so that you have what you need:

Activity activity = (Activity) context;

no module named zlib

I had a lot of problems making a virtual environment (venv) as described in the tensorflow installation guide.

Most of the commands listed in this post didn't help me either so, if this is also your case this is what I did:

  1. pip3 install --user pipenv
  2. pip install virtualenv

Installs the dependencies to create a virtual environment

  1. mkdir myenv

Makes a new directory called myenv but you can call it whatever you want e.g. mynewenv

  1. cd myenv

Or whatever you call your directory so: cd [your_directory_name]

  1. virtualenv -p /usr/bin/python3 venv

Creates a virtual environment called venv in the folder myenv. You can call your virtual env whatever you like e.g. vitualenv [v_env_name]

  1. source ./venv/bin/activate

Activates the virtual environment. Note that if you choose a different v. env. name your commands should be written as such source ./[v_env_name]/bin/activate

  1. deactivate

Deactivates the virtual environment.

Note: I am using Python 3.6.6 & Ubuntu 18.04

source for the commands

Fix GitLab error: "you are not allowed to push code to protected branches on this project"?

there's no problem - everything works as expected.

In GitLab some branches can be protected. By default only Maintainer/Owner users can commit to protected branches (see permissions docs). master branch is protected by default - it forces developers to issue merge requests to be validated by project maintainers before integrating them into main code.

You can turn on and off protection on selected branches in Project Settings (where exactly depends on GitLab version - see instructions below).

On the same settings page you can also allow developers to push into the protected branches. With this setting on, protection will be limited to rejecting operations requiring git push --force (rebase etc.)

Since GitLab 9.3

Go to project: "Settings" ? "Repository" ? "Expand" on "Protected branches"

enter image description here

I'm not really sure when this change was introduced, screenshots are from 10.3 version.

Now you can select who is allowed to merge or push into selected branches (for example: you can turn off pushes to master at all, forcing all changes to branch to be made via Merge Requests). Or you can click "Unprotect" to completely remove protection from branch.

Since GitLab 9.0

Similarly to GitLab 9.3, but no need to click "Expand" - everything is already expanded:

Go to project: "Settings" ? "Repository" ? scroll down to "Protected branches".

enter image description here

Pre GitLab 9.0

Project: "Settings" ? "Protected branches" (if you are at least 'Master' of given project).

Settings ? Protected branches

Then click on "Unprotect" or "Developers can push":

enter image description here

Query a parameter (postgresql.conf setting) like "max_connections"

You can use SHOW:

SHOW max_connections;

This returns the currently effective setting. Be aware that it can differ from the setting in postgresql.conf as there are a multiple ways to set run-time parameters in PostgreSQL. To reset the "original" setting from postgresql.conf in your current session:

RESET max_connections;

However, not applicable to this particular setting. The manual:

This parameter can only be set at server start.

To see all settings:

SHOW ALL;

There is also pg_settings:

The view pg_settings provides access to run-time parameters of the server. It is essentially an alternative interface to the SHOW and SET commands. It also provides access to some facts about each parameter that are not directly available from SHOW, such as minimum and maximum values.

For your original request:

SELECT *
FROM   pg_settings
WHERE  name = 'max_connections';

Finally, there is current_setting(), which can be nested in DML statements:

SELECT current_setting('max_connections');

Related:

Inserting an image with PHP and FPDF

You can use $pdf->GetX() and $pdf->GetY() to get current cooridnates and use them to insert image.

$pdf->Image($image1, 5, $pdf->GetY(), 33.78);

or even

$pdf->Image($image1, 5, null, 33.78);

(ALthough in first case you can add a number to create a bit of a space)

$pdf->Image($image1, 5, $pdf->GetY() + 5, 33.78);

ASP.NET MVC3 - textarea with @Html.EditorFor

Someone asked about adding attributes (specifically, 'rows' and 'cols'). If you're using Razor, you could just do this:

@Html.TextAreaFor(model => model.Text, new { cols = 35, @rows = 3 })

That works for me. The '@' is used to escape keywords so they are treated as variables/properties.

Basic CSS - how to overlay a DIV with semi-transparent DIV on top

Here's a pure CSS solution, similar to DarkBee's answer, but without the need for an extra .wrapper div:

.dimmed {
  position: relative;
}

.dimmed:after {
  content: " ";
  z-index: 10;
  display: block;
  position: absolute;
  height: 100%;
  top: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.5);
}

I'm using rgba here, but of course you can use other transparency methods if you like.

Receive JSON POST with PHP

Read the doc:

In general, php://input should be used instead of $HTTP_RAW_POST_DATA.

as in the php Manual

Swift apply .uppercaseString to only the first letter of a string

Including mutating and non mutating versions that are consistent with API guidelines.

Swift 3:

extension String {
    func capitalizingFirstLetter() -> String {
        let first = String(characters.prefix(1)).capitalized
        let other = String(characters.dropFirst())
        return first + other
    }

    mutating func capitalizeFirstLetter() {
        self = self.capitalizingFirstLetter()
    }
}

Swift 4:

extension String {
    func capitalizingFirstLetter() -> String {
      return prefix(1).uppercased() + self.lowercased().dropFirst()
    }

    mutating func capitalizeFirstLetter() {
      self = self.capitalizingFirstLetter()
    }
}

Nested iframes, AKA Iframe Inception

var iframeInner = jQuery(iframe).find('iframe').contents();

var iframeContent = jQuery(iframeInner).contents().find('#element');

iframeInner contains elements from

<div id="element">other markup goes here</div> 

and iframeContent will find for elements which are inside of

 <div id="element">other markup goes here</div> 

(find doesn't search on current element) that's why it is returning null.

Change tab bar item selected color in a storyboard

You can subclass the UITabBarController, and replace the one with it in the storyboard. In your viewDidLoad implementation of subclass call this:

[self.tabBar setTintColor:[UIColor greenColor]];

Open the terminal in visual studio?

View -> debug console (Ctrl+Shift+Y) next to debug console is terminal

How can I configure my makefile for debug and release builds?

If by configure release/build, you mean you only need one config per makefile, then it is simply a matter and decoupling CC and CFLAGS:

CFLAGS=-DDEBUG
#CFLAGS=-O2 -DNDEBUG
CC=g++ -g3 -gdwarf2 $(CFLAGS)

Depending on whether you can use gnu makefile, you can use conditional to make this a bit fancier, and control it from the command line:

DEBUG ?= 1
ifeq ($(DEBUG), 1)
    CFLAGS =-DDEBUG
else
    CFLAGS=-DNDEBUG
endif

.o: .c
    $(CC) -c $< -o $@ $(CFLAGS)

and then use:

make DEBUG=0
make DEBUG=1

If you need to control both configurations at the same time, I think it is better to have build directories, and one build directory / config.

Global and local variables in R

<- does assignment in the current environment.

When you're inside a function R creates a new environment for you. By default it includes everything from the environment in which it was created so you can use those variables as well but anything new you create will not get written to the global environment.

In most cases <<- will assign to variables already in the global environment or create a variable in the global environment even if you're inside a function. However, it isn't quite as straightforward as that. What it does is checks the parent environment for a variable with the name of interest. If it doesn't find it in your parent environment it goes to the parent of the parent environment (at the time the function was created) and looks there. It continues upward to the global environment and if it isn't found in the global environment it will assign the variable in the global environment.

This might illustrate what is going on.

bar <- "global"
foo <- function(){
    bar <- "in foo"
    baz <- function(){
        bar <- "in baz - before <<-"
        bar <<- "in baz - after <<-"
        print(bar)
    }
    print(bar)
    baz()
    print(bar)
}
> bar
[1] "global"
> foo()
[1] "in foo"
[1] "in baz - before <<-"
[1] "in baz - after <<-"
> bar
[1] "global"

The first time we print bar we haven't called foo yet so it should still be global - this makes sense. The second time we print it's inside of foo before calling baz so the value "in foo" makes sense. The following is where we see what <<- is actually doing. The next value printed is "in baz - before <<-" even though the print statement comes after the <<-. This is because <<- doesn't look in the current environment (unless you're in the global environment in which case <<- acts like <-). So inside of baz the value of bar stays as "in baz - before <<-". Once we call baz the copy of bar inside of foo gets changed to "in baz" but as we can see the global bar is unchanged. This is because the copy of bar that is defined inside of foo is in the parent environment when we created baz so this is the first copy of bar that <<- sees and thus the copy it assigns to. So <<- isn't just directly assigning to the global environment.

<<- is tricky and I wouldn't recommend using it if you can avoid it. If you really want to assign to the global environment you can use the assign function and tell it explicitly that you want to assign globally.

Now I change the <<- to an assign statement and we can see what effect that has:

bar <- "global"
foo <- function(){
    bar <- "in foo"   
    baz <- function(){
        assign("bar", "in baz", envir = .GlobalEnv)
    }
    print(bar)
    baz()
    print(bar)
}
bar
#[1] "global"
foo()
#[1] "in foo"
#[1] "in foo"
bar
#[1] "in baz"

So both times we print bar inside of foo the value is "in foo" even after calling baz. This is because assign never even considered the copy of bar inside of foo because we told it exactly where to look. However, this time the value of bar in the global environment was changed because we explicitly assigned there.

Now you also asked about creating local variables and you can do that fairly easily as well without creating a function... We just need to use the local function.

bar <- "global"
# local will create a new environment for us to play in
local({
    bar <- "local"
    print(bar)
})
#[1] "local"
bar
#[1] "global"

Convert hex string (char []) to int?

I made a librairy to make Hexadecimal / Decimal conversion without the use of stdio.h. Very simple to use :

unsigned hexdec (const char *hex, const int s_hex);

Before the first conversion intialize the array used for conversion with :

void init_hexdec ();

Here the link on github : https://github.com/kevmuret/libhex/

java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)

Try it like this....

public static Connection getConnection() throws SQLException{

    String driver = "com.mysql.jdbc.Driver";
    String url    = "jdbc:mysql://localhost:3306/test";
    String username = "root";
    String password = "vicky";            // Change it to your Password
    System.setProperty(driver,"");

    return DriverManager.getConnection(url,username,password);
}

OnClick vs OnClientClick for an asp:CheckBox?

That is very weird. I checked the CheckBox documentation page which reads

<asp:CheckBox id="CheckBox1" 
     AutoPostBack="True|False"
     Text="Label"
     TextAlign="Right|Left"
     Checked="True|False"
     OnCheckedChanged="OnCheckedChangedMethod"
     runat="server"/>

As you can see, there is no OnClick or OnClientClick attributes defined.

Keeping this in mind, I think this is what is happening.

When you do this,

<asp:CheckBox runat="server" OnClick="alert(this.checked);" />

ASP.NET doesn't modify the OnClick attribute and renders it as is on the browser. It would be rendered as:

  <input type="checkbox" OnClick="alert(this.checked);" />

Obviously, a browser can understand 'OnClick' and puts an alert.

And in this scenario

<asp:CheckBox runat="server" OnClientClick="alert(this.checked);" />

Again, ASP.NET won't change the OnClientClick attribute and will render it as

<input type="checkbox" OnClientClick="alert(this.checked);" />

As browser won't understand OnClientClick nothing will happen. It also won't raise any error as it is just another attribute.

You can confirm above by looking at the rendered HTML.

And yes, this is not intuitive at all.

Bootstrap 3 - Set Container Width to 940px Maximum for Desktops?

In the first place consider the Small grid, see: http://getbootstrap.com/css/#grid-options. A max container width of 750 px will maybe to small for you (also read: Why does Bootstrap 3 force the container width to certain sizes?)

When using the Small grid use media queries to set the max-container width:

@media (min-width: 768px) { .container { max-width: 750px; } }

Second also read this question: Bootstrap 3 - 940px width grid?, possible duplicate?

12 x 60 = 720px for the columns and 11 x 20 = 220px

there will also a gutter of 20px on both sides of the grid so 220 + 720 + 40 makes 980px

there is 'no' @ColumnWidth

You colums width will be calculated dynamically based on your settings in variables.less. you could set @grid-columns and @grid-gutter-width. The width of a column will be set as a percentage via grid.less in mixins.less:

.calc-grid(@index, @class, @type) when (@type = width) {
  .col-@{class}-@{index} {
    width: percentage((@index / @grid-columns));
  }
}

update Set @grid-gutter-width to 20px;, @container-desktop: 940px;, @container-large-desktop: @container-desktop and recompile bootstrap.

How can I verify if an AD account is locked?

Here's another one:

PS> Search-ADAccount -Locked | Select Name, LockedOut, LastLogonDate

Name                                       LockedOut LastLogonDate
----                                       --------- -------------
Yxxxxxxx                                        True 14/11/2014 10:19:20
Bxxxxxxx                                        True 18/11/2014 08:38:34
Administrator                                   True 03/11/2014 20:32:05

Other parameters worth mentioning:

Search-ADAccount -AccountExpired
Search-ADAccount -AccountDisabled
Search-ADAccount -AccountInactive

Get-Help Search-ADAccount -ShowWindow

Cannot make a static reference to the non-static method

Since getText() is non-static you cannot call it from a static method.

To understand why, you have to understand the difference between the two.

Instance (non-static) methods work on objects that are of a particular type (the class). These are created with the new like this:

SomeClass myObject = new SomeClass();

To call an instance method, you call it on the instance (myObject):

myObject.getText(...)

However a static method/field can be called only on the type directly, say like this: The previous statement is not correct. One can also refer to static fields with an object reference like myObject.staticMethod() but this is discouraged because it does not make it clear that they are class variables.

... = SomeClass.final

And the two cannot work together as they operate on different data spaces (instance data and class data)

Let me try and explain. Consider this class (psuedocode):

class Test {
     string somedata = "99";
     string getText() { return somedata; } 
     static string TTT = "0";
}

Now I have the following use case:

Test item1 = new Test();
 item1.somedata = "200";

 Test item2 = new Test();

 Test.TTT = "1";

What are the values?

Well

in item1 TTT = 1 and somedata = 200
in item2 TTT = 1 and somedata = 99

In other words, TTT is a datum that is shared by all the instances of the type. So it make no sense to say

class Test {
         string somedata = "99";
         string getText() { return somedata; } 
  static string TTT = getText(); // error there is is no somedata at this point 
}

So the question is why is TTT static or why is getText() not static?

Remove the static and it should get past this error - but without understanding what your type does it's only a sticking plaster till the next error. What are the requirements of getText() that require it to be non-static?

Get single row result with Doctrine NativeQuery

->getSingleScalarResult() will return a single value, instead of an array.

VB.NET: how to prevent user input in a ComboBox

Set the ReadOnly attribute to true.

Or if you want the combobox to appear and display the list of "available" values, you could handle the ValueChanged event and force it back to your immutable value.

Switch tabs using Selenium WebDriver with Java

The first thing you need to do is opening a new tab and save it's handle name. It will be best to do it using javascript and not keys(ctrl+t) since keys aren't always available on automation servers. example:

public static String openNewTab(String url) {
    executeJavaScript("window.parent = window.open('parent');");
    ArrayList<String> tabs = new ArrayList<String>(bot.driver.getWindowHandles());
    String handleName = tabs.get(1);
    bot.driver.switchTo().window(handleName);
    System.setProperty("current.window.handle", handleName);
    bot.driver.get(url);
    return handleName;
}

The second thing you need to do is switching between the tabs. Doing it by switch window handles only, will not always work since the tab you'll work on, won't always be in focus and Selenium will fail from time to time. As I said, it's a bit problematic to use keys, and javascript doesn't really support switching tabs, so I used alerts to switch tabs and it worked like a charm:

public static void switchTab(int tabNumber, String handleName) {
        driver.switchTo().window(handleName);
        System.setProperty("current.window.handle", handleName);
        if (tabNumber==1)
            executeJavaScript("alert(\"alert\");");
        else
            executeJavaScript("parent.alert(\"alert\");");
        bot.wait(1000);
        driver.switchTo().alert().accept();
    }

A fatal error has been detected by the Java Runtime Environment: SIGSEGV, libjvm

add new server (tomcat) with different location. if i am not make mistake you are run multiple project with same tomcat and add same tomcat server on same location ..

add new tomcat for each new workspace.

Quickly create large file on a Windows system

Short of writing a full application, us Python guys can achieve files of any size with four lines, same snippet on Windows and Linux (the os.stat() line is just a check):

>>> f = open('myfile.txt','w')
>>> f.seek(1024-1) # an example, pick any size
>>> f.write('\x00')
>>> f.close()
>>> os.stat('myfile.txt').st_size
1024L
>>>

how do I get the bullet points of a <ul> to center with the text?

Add list-style-position: inside to the ul element. (example)

The default value for the list-style-position property is outside.

_x000D_
_x000D_
ul {_x000D_
    text-align: center;_x000D_
    list-style-position: inside;_x000D_
}
_x000D_
<ul>_x000D_
    <li>one</li>_x000D_
    <li>two</li>_x000D_
    <li>three</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Another option (which yields slightly different results) would be to center the entire ul element:

_x000D_
_x000D_
.parent {_x000D_
  text-align: center;_x000D_
}_x000D_
.parent > ul {_x000D_
  display: inline-block;_x000D_
}
_x000D_
<div class="parent">_x000D_
  <ul>_x000D_
    <li>one</li>_x000D_
    <li>two</li>_x000D_
    <li>three</li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What is the best method of handling currency/money?

Here's a fine, simple approach that leverages composed_of (part of ActiveRecord, using the ValueObject pattern) and the Money gem

You'll need

  • The Money gem (version 4.1.0)
  • A model, for example Product
  • An integer column in your model (and database), for example :price

Write this in your product.rb file:

class Product > ActiveRecord::Base

  composed_of :price,
              :class_name => 'Money',
              :mapping => %w(price cents),
              :converter => Proc.new { |value| Money.new(value) }
  # ...

What you'll get:

  • Without any extra changes, all of your forms will show dollars and cents, but the internal representation is still just cents. The forms will accept values like "$12,034.95" and convert it for you. There's no need to add extra handlers or attributes to your model, or helpers in your view.
  • product.price = "$12.00" automatically converts to the Money class
  • product.price.to_s displays a decimal formatted number ("1234.00")
  • product.price.format displays a properly formatted string for the currency
  • If you need to send cents (to a payment gateway that wants pennies), product.price.cents.to_s
  • Currency conversion for free

How to escape a while loop in C#

Use break; to escape the first loop:

if (s.Contains("mp4:production/CATCHUP/"))
{
   RemoveEXELog();
   Process p = new Process();
   p.StartInfo.WorkingDirectory = "dump";
   p.StartInfo.FileName = "test.exe"; 
   p.StartInfo.Arguments = s; 
   p.Start();
   break;
}

If you want to also escape the second loop, you might need to use a flag and check in the out loop's guard:

        boolean breakFlag = false;
        while (!breakFlag)
        {
            Thread.Sleep(5000);
            if (!System.IO.File.Exists("Command.bat")) continue;
            using (System.IO.StreamReader sr = System.IO.File.OpenText("Command.bat"))
            {
                string s = "";
                while ((s = sr.ReadLine()) != null)
                {
                    if (s.Contains("mp4:production/CATCHUP/"))
                    {

                        RemoveEXELog();

                        Process p = new Process();
                        p.StartInfo.WorkingDirectory = "dump";
                        p.StartInfo.FileName = "test.exe"; 
                        p.StartInfo.Arguments = s; 
                        p.Start();

                        breakFlag = true;
                        break;
                    }
                }
            }

Or, if you want to just exit the function completely from within the nested loop, put in a return; instead of a break;.

But these aren't really considered best practices. You should find some way to add the necessary Boolean logic into your while guards.

CS1617: Invalid option ‘6’ for /langversion; must be ISO-1, ISO-2, 3, 4, 5 or Default

This happened to me when I pulled down my repo after moving it to a new location. The solution was to unload and then reload each project that was showing this error.

I tried a few other options but nothing worked for me. Also in this situation my config files were set to use languageversion 6, so setting them to default did not fix the issue.

Activity has leaked window that was originally added

This can be if you have an error at doInBackground() function and have this code.

Try to add dialog at last. At first check and fix doInBackground() function

protected void onPreExecute() {
     super.onPreExecute();
     pDialog = new ProgressDialog(CreateAccount.this);
     pDialog.setMessage("Creating Product..");
     pDialog.setIndeterminate(false);
     pDialog.setCancelable(true);
     pDialog.show();

 }

 protected String doInBackground(String...args) {
     ERROR CAN BE IS HERE
 }

 protected void onPostExecute(String file_url) {
     // dismiss the dialog once done
     pDialog.dismiss();

Abort a Git Merge

If you do "git status" while having a merge conflict, the first thing git shows you is how to abort the merge.

output of git status while having a merge conflict

how to pass data in an hidden field from one jsp page to another?

To pass the value you must included the hidden value value="hiddenValue" in the <input> statement like so:

<input type="hidden" id="thisField" name="inputName" value="hiddenValue">

Then you recuperate the hidden form value in the same way that you recuperate the value of visible input fields, by accessing the parameter of the request object. Here is an example:

This code goes on the page where you want to hide the value.

<form action="anotherPage.jsp" method="GET">
    <input type="hidden" id="thisField" name="inputName" value="hiddenValue">
<input type="submit">   
</form>

Then on the 'anotherPage.jsp' page you recuperate the value by calling the getParameter(String name) method of the implicit request object, as so:

<% String hidden = request.getParameter("inputName"); %>
The Hidden Value is <%=hidden %>

The output of the above script will be:

The Hidden Value is hiddenValue 

How do I create an executable in Visual Studio 2013 w/ C++?

  1. Click BUILD > Configuration Manager...
  2. Under Project contexts > Configuration, select "Release"
  3. BUILD > Build Solution or Rebuild Solution

What's the safest way to iterate through the keys of a Perl hash?

One thing you should be aware of when using each is that it has the side effect of adding "state" to your hash (the hash has to remember what the "next" key is). When using code like the snippets posted above, which iterate over the whole hash in one go, this is usually not a problem. However, you will run into hard to track down problems (I speak from experience ;), when using each together with statements like last or return to exit from the while ... each loop before you have processed all keys.

In this case, the hash will remember which keys it has already returned, and when you use each on it the next time (maybe in a totaly unrelated piece of code), it will continue at this position.

Example:

my %hash = ( foo => 1, bar => 2, baz => 3, quux => 4 );

# find key 'baz'
while ( my ($k, $v) = each %hash ) {
    print "found key $k\n";
    last if $k eq 'baz'; # found it!
}

# later ...

print "the hash contains:\n";

# iterate over all keys:
while ( my ($k, $v) = each %hash ) {
    print "$k => $v\n";
}

This prints:

found key bar
found key baz
the hash contains:
quux => 4
foo => 1

What happened to keys "bar" and baz"? They're still there, but the second each starts where the first one left off, and stops when it reaches the end of the hash, so we never see them in the second loop.

Cannot implicitly convert type from Task<>

You need to make TestGetMethod async too and attach await in front of GetIdList(); will unwrap the task to List<int>, So if your helper function is returning Task make sure you have await as you are calling the function async too.

public Task<List<int>> TestGetMethod()
{
    return GetIdList();
}    

async Task<List<int>> GetIdList()
{
    using (HttpClient proxy = new HttpClient())
    {
        string response = await proxy.GetStringAsync("www.test.com");
        List<int> idList = JsonConvert.DeserializeObject<List<int>>();
        return idList;
    }
}

Another option

public async void TestGetMethod(List<int> results)
{
    results = await GetIdList(); // await will unwrap the List<int>
}

Genymotion Android emulator - adb access?

I know it's way too late to answer this question, but I'll just post the solution that worked for me, in case someone runs into trouble again in the future.

I tried using genymotion's own adb tools and the original Android SDK ones, and even purging and reinstalling adb from my system, but nothing worked. I kept getting the error:

adb server is out of date. killing... cannot bind 'tcp:5037' ADB server didn't ACK *failed to start daemon* error:
So I tried adb connect [ip] as suggested here, but I didn't work either, the same error came up.

What finally worked for me was downloading ADT, and running adb directly from the downloaded folder, instead of the system-wide command. So adb devices will give me the error above, but /yourdownloadpath/adb devices works just fine for me.

Hope it helped.

Difference between signed / unsigned char

There are three char types: (plain) char, signed char and unsigned char. Any char is usually an 8-bit integer* and in that sense, a signed and unsigned char have a useful meaning (generally equivalent to uint8_t and int8_t). When used as a character in the sense of text, use a char (also referred to as a plain char). This is typically a signed char but can be implemented either way by the compiler.

* Technically, a char can be any size as long as sizeof(char) is 1, but it is usually an 8-bit integer.

What does git push -u mean?

"Upstream" would refer to the main repo that other people will be pulling from, e.g. your GitHub repo. The -u option automatically sets that upstream for you, linking your repo to a central one. That way, in the future, Git "knows" where you want to push to and where you want to pull from, so you can use git pull or git push without arguments. A little bit down, this article explains and demonstrates this concept.

How to quickly form groups (quartiles, deciles, etc) by ordering column(s) in a data frame

The method I use is one of these or Hmisc::cut2(value, g=4):

temp$quartile <- with(temp, cut(value, 
                                breaks=quantile(value, probs=seq(0,1, by=0.25), na.rm=TRUE), 
                                include.lowest=TRUE))

An alternate might be:

temp$quartile <- with(temp, factor(
                            findInterval( val, c(-Inf,
                               quantile(val, probs=c(0.25, .5, .75)), Inf) , na.rm=TRUE), 
                            labels=c("Q1","Q2","Q3","Q4")
      ))

The first one has the side-effect of labeling the quartiles with the values, which I consider a "good thing", but if it were not "good for you", or the valid problems raised in the comments were a concern you could go with version 2. You can use labels= in cut, or you could add this line to your code:

temp$quartile <- factor(temp$quartile, levels=c("1","2","3","4") )

Or even quicker but slightly more obscure in how it works, although it is no longer a factor, but rather a numeric vector:

temp$quartile <- as.numeric(temp$quartile)

Set environment variables from file of key/value pairs

The allexport option is mentioned in a couple of other answers here, for which set -a is the shortcut. Sourcing the .env really is better than looping over lines and exporting because it allows for comments, blank lines, and even environment variables generated by commands. My .bashrc includes the following:

# .env loading in the shell
dotenv () {
  set -a
  [ -f .env ] && . .env
  set +a
}

# Run dotenv on login
dotenv

# Run dotenv on every new directory
cd () {
  builtin cd $@
  dotenv
}

How to get the current logged in user Id in ASP.NET Core

you have to import Microsoft.AspNetCore.Identity & System.Security.Claims

// to get current user ID
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);

// to get current user info
var user = await _userManager.FindByIdAsync(userId);

Convert a string to a datetime

Try to see if the following code helps you:

Dim iDate As String = "05/05/2005"
Dim oDate As DateTime = Convert.ToDateTime(iDate)

Delete element in a slice

... is syntax for variadic arguments.

I think it is implemented by the complier using slice ([]Type), just like the function append :

func append(slice []Type, elems ...Type) []Type

when you use "elems" in "append", actually it is a slice([]type). So "a = append(a[:0], a[1:]...)" means "a = append(a[0:0], a[1:])"

a[0:0] is a slice which has nothing

a[1:] is "Hello2 Hello3"

This is how it works

How do I parse JSON with Objective-C?

  1. I recommend and use TouchJSON for parsing JSON.
  2. To answer your comment to Alex. Here's quick code that should allow you to get the fields like activity_details, last_name, etc. from the json dictionary that is returned:

    NSDictionary *userinfo=[jsondic valueforKey:@"#data"];
    NSDictionary *user;
    NSInteger i = 0;
    NSString *skey;
    if(userinfo != nil){
        for( i = 0; i < [userinfo count]; i++ ) {
            if(i)
                skey = [NSString stringWithFormat:@"%d",i];
            else
                skey = @"";
    
            user = [userinfo objectForKey:skey];
            NSLog(@"activity_details:%@",[user objectForKey:@"activity_details"]);
            NSLog(@"last_name:%@",[user objectForKey:@"last_name"]);
            NSLog(@"first_name:%@",[user objectForKey:@"first_name"]);
            NSLog(@"photo_url:%@",[user objectForKey:@"photo_url"]);
        }
    }
    

Is there a wikipedia API just for retrieve content summary?

This code allows you to retrieve the content of the first paragraph of the page in plain text.

Parts of this answer come from here and thus here. See MediaWiki API documentation for more information.

// action=parse: get parsed text
// page=Baseball: from the page Baseball
// format=json: in json format
// prop=text: send the text content of the article
// section=0: top content of the page

$url = 'http://en.wikipedia.org/w/api.php?format=json&action=parse&page=Baseball&prop=text&section=0';
$ch = curl_init($url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_USERAGENT, "TestScript"); // required by wikipedia.org server; use YOUR user agent with YOUR contact information. (otherwise your IP might get blocked)
$c = curl_exec($ch);

$json = json_decode($c);

$content = $json->{'parse'}->{'text'}->{'*'}; // get the main text content of the query (it's parsed HTML)

// pattern for first match of a paragraph
$pattern = '#<p>(.*)</p>#Us'; // http://www.phpbuilder.com/board/showthread.php?t=10352690
if(preg_match($pattern, $content, $matches))
{
    // print $matches[0]; // content of the first paragraph (including wrapping <p> tag)
    print strip_tags($matches[1]); // Content of the first paragraph without the HTML tags.
}

Parsing HTML using Python

Compared to the other parser libraries lxml is extremely fast:

And with cssselect it’s quite easy to use for scraping HTML pages too:

from lxml.html import parse
doc = parse('http://www.google.com').getroot()
for div in doc.cssselect('a'):
    print '%s: %s' % (div.text_content(), div.get('href'))

lxml.html Documentation

How to convert UTF8 string to byte array?

The Google Closure library has functions to convert to/from UTF-8 and byte arrays. If you don't want to use the whole library, you can copy the functions from here. For completeness, the code to convert to a string to a UTF-8 byte array is:

goog.crypt.stringToUtf8ByteArray = function(str) {
  // TODO(user): Use native implementations if/when available
  var out = [], p = 0;
  for (var i = 0; i < str.length; i++) {
    var c = str.charCodeAt(i);
    if (c < 128) {
      out[p++] = c;
    } else if (c < 2048) {
      out[p++] = (c >> 6) | 192;
      out[p++] = (c & 63) | 128;
    } else if (
        ((c & 0xFC00) == 0xD800) && (i + 1) < str.length &&
        ((str.charCodeAt(i + 1) & 0xFC00) == 0xDC00)) {
      // Surrogate Pair
      c = 0x10000 + ((c & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF);
      out[p++] = (c >> 18) | 240;
      out[p++] = ((c >> 12) & 63) | 128;
      out[p++] = ((c >> 6) & 63) | 128;
      out[p++] = (c & 63) | 128;
    } else {
      out[p++] = (c >> 12) | 224;
      out[p++] = ((c >> 6) & 63) | 128;
      out[p++] = (c & 63) | 128;
    }
  }
  return out;
};

Reading from text file until EOF repeats last line

There's an alternative approach to this:

#include <iterator>
#include <algorithm>

// ...

    copy(istream_iterator<int>(iFile), istream_iterator<int>(),
         ostream_iterator<int>(cerr, "\n"));

How to style the menu items on an Android action bar

I know its an old post, but just in case anyone is looking here. I added this to my style.xml and it worked for me.

<!-- This is the main theme parent -->
<style name="MyTabStyle">
    <item name="android:actionBarTabTextStyle">@style/MyTabTextStyle</item>
</style>

<style name="MyTabTextStyle" parent="@android:style/Widget.ActionBar.TabText">
    <item name="android:textAppearance">@android:style/TextAppearance.Medium</item>
    <item name="android:textSize">14sp</item>
    <item name="android:textStyle">bold</item>
    <item name="android:textColor">@color/pressed_skylogtheme</item>
</style>

ADB.exe is obsolete and has serious performance problems

None of the top-voted answers worked for me, except when I unchecked "Use detected ADB location" as mentioned above by @???. Fortunately, in my case though, the message didn't show up, even when I turned it back on. In other words, the problem might be resolved by restarting "Use detected ADB location" :)

form action with javascript

It has been almost 8 years since the question was asked, but I will venture an answer not previously given. The OP said this doesn't work:

action="javascript:simpleCart.checkout()"

And the OP said that this code continued to fail despite trying all the good advice he got. So I will venture a guess. The action is calling checkout() as a static method of the simpleCart class; but maybe checkout() is actually an instance member, and not static. It depends how he defined checkout().

By the way, simpleCart is presumably a class name, and by convention class names have an initial capital letter, so let's use that convention, here. Let's use the name SimpleCart.

Here is some sample code that illustrates defining checkout() as an instance member. This was the correct way to do it, prior to ECMA-6:

function SimpleCart() {
    ...
}
SimpleCart.prototype.checkout = function() { ... };

Many people have used a different technique, as illustrated in the following. This was popular, and it worked, but I advocate against it, because instances are supposed to be defined on the prototype, just once, while the following technique defines the member on this and does so repeatedly, with every instantiation.

function SimpleCart() {
    ...
    this.checkout = function() { ... };
}

And here is an instance definition in ECMA-6, using an official class:

class SimpleCart {
    constructor() { ... }
    ...
    checkout()    { ... }
}

Compare to a static definition in ECMA-6. The difference is just one word:

class SimpleCart {
    constructor() { ... }
    ...
    static checkout()    { ... }
}

And here is a static definition the old way, pre-ECMA-6. Note that the checkout() method is defined outside of the function. It is a member of the function object, not the prototype object, and that's what makes it static.

function SimpleCart() {
    ...
}
SimpleCart.checkout = function() { ... };

Because of the way it is defined, a static function will have a different concept of what the keyword this references. Note that instance member functions are called using the this keyword:

this.checkout();

Static member functions are called using the class name:

SimpleCart.checkout();

The problem is that the OP wants to put the call into HTML, where it will be in global scope. He can't use the keyword this because this would refer to the global scope (which is window).

action="javascript:this.checkout()" // not as intended
action="javascript:window.checkout()" // same thing

There is no easy way to use an instance member function in HTML. You can do stuff in combination with JavaScript, creating a registry in the static scope of the Class, and then calling a surrogate static method, while passing an argument to that surrogate that gives the index into the registry of your instance, and then having the surrogate call the actual instance member function. Something like this:

// In Javascript:
SimpleCart.registry[1234] = new SimpleCart();

// In HTML
action="javascript:SimpleCart.checkout(1234);"

// In Javascript
SimpleCart.checkout = function(myIndex) {
    var myThis = SimpleCart.registry[myIndex];
    myThis.checkout();
}

You could also store the index as an attribute on the element.

But usually it is easier to just do nothing in HTML and do everything in JavaScript with .addEventListener() and use the .bind() capability.

Warning: mysqli_select_db() expects exactly 2 parameters, 1 given in C:\

mysqli_select_db() should have 2 parameters, the connection link and the database name -

mysqli_select_db($con, 'phpcadet') or die(mysqli_error($con));

Using mysqli_error in the die statement will tell you exactly what is wrong as opposed to a generic error message.

How to write to a file without overwriting current contents?

Instead of "w" use "a" (append) mode with open function:

with open("games.txt", "a") as text_file:

tmux status bar configuration

I used tmux-powerline to fully pimp my tmux status bar. I was googling for a way to change to background of the status bar when your typing a tmux command. When I stumbled on this post I thought I should mention it for completeness.

Update: This project is in a maintenance mode and no future functionality is likely to be added. tmux-powerline, with all other powerline projects, is replaced by the new unifying powerline. However this project is still functional and can serve as a lightweight alternative for non-python users.

Java: convert seconds to minutes, hours and days

Thanks guys for all the help, I really appreciate but I actually did some thinking and start doing some pseudo code and came up with this.

import java.util.Scanner;

public class Project {

public static void main(String[] args) {



//variable declaration  
Scanner scan = new Scanner(System.in);
final int MIN = 60, HRS = 3600, DYS = 84600;
int input, days, seconds, minutes, hours, rDays, rHours;

//input 
System.out.println("Enter amount of seconds!");
input = scan.nextInt();


//calculations
days = input/DYS;
rDays = input%DYS;
hours = rDays/HRS;
rHours = rDays%HRS;
minutes = rHours/MIN;
seconds = rHours%MIN;

//output
if (input >= DYS) {
    System.out.println(input + " seconds equals to " + days + " days " + hours + " hours " + minutes + " minutes " + seconds + " seconds");
}

else if (input >= HRS && input < DYS) {
    System.out.println(input + " seconds equals to " + hours + " hours " + minutes + " minutes " + seconds + " seconds");
}

else if (input >= MIN && input < HRS) {
    System.out.println(input + " seconds equals to " + minutes + " minutes " + seconds + " seconds");
}

else if (input < MIN) {
    System.out.println(input + " seconds equals to seconds");
}

scan.close();


}   

I know it looks really noobie but keep in mind I'm still new not just Java but programming entirely, and who knew pseudo code was actually really helpful.

Dealing with "Xerces hell" in Java/Maven?

There are 2.11.0 JARs (and source JARs!) of Xerces in Maven Central since 20th February 2013! See Xerces in Maven Central. I wonder why they haven't resolved https://issues.apache.org/jira/browse/XERCESJ-1454...

I've used:

<dependency>
    <groupId>xerces</groupId>
    <artifactId>xercesImpl</artifactId>
    <version>2.11.0</version>
</dependency>

and all dependencies have resolved fine - even proper xml-apis-1.4.01!

And what's most important (and what wasn't obvious in the past) - the JAR in Maven Central is the same JAR as in the official Xerces-J-bin.2.11.0.zip distribution.

I couldn't however find xml-schema-1.1-beta version - it can't be a Maven classifier-ed version because of additional dependencies.

sed command with -i option failing on Mac, but works on Linux

As the other answers indicate, there is not a way to use sed portably across OS X and Linux without making backup files. So, I instead used this Ruby one-liner to do so:

ruby -pi -e "sub(/ $/, '')" ./config/locales/*.yml

In my case, I needed to call it from a rake task (i.e., inside a Ruby script), so I used this additional level of quoting:

sh %q{ruby -pi -e "sub(/ $/, '')" ./config/locales/*.yml}

Single Form Hide on Startup

Extend your main form with this one:

using System.Windows.Forms;

namespace HideWindows
{
    public class HideForm : Form
    {
        public HideForm()
        {
            Opacity = 0;
            ShowInTaskbar = false;
        }

        public new void Show()
        {
            Opacity = 100;
            ShowInTaskbar = true;

            Show(this);
        }
    }
}

For example:

namespace HideWindows
{
    public partial class Form1 : HideForm
    {
        public Form1()
        {
            InitializeComponent();
        }
    }
}

More info in this article (spanish):

http://codelogik.net/2008/12/30/primer-form-oculto/

port forwarding in windows

I've used this little utility whenever the need arises: http://www.analogx.com/contents/download/network/pmapper/freeware.htm

The last time this utility was updated was in 2009. I noticed on my Win10 machine, it hangs for a few seconds when opening new windows sometimes. Other then that UI glitch, it still does its job fine.

Do I need to compile the header files in a C program?

Okay, let's understand the difference between active and passive code.

The active code is the implementation of functions, procedures, methods, i.e. the pieces of code that should be compiled to executable machine code. We store it in .c files and sure we need to compile it.

The passive code is not being execute itself, but it needed to explain the different modules how to communicate with each other. Usually, .h files contains only prototypes (function headers), structures.

An exception are macros, that formally can contain an active pieces, but you should understand that they are using at the very early stage of building (preprocessing) with simple substitution. At the compile time macros already are substituted to your .c file.

Another exception are C++ templates, that should be implemented in .h files. But here is the story similar to macros: they are substituted on the early stage (instantiation) and formally, each other instantiation is another type.

In conclusion, I think, if the modules formed properly, we should never compile the header files.

Return only string message from Spring MVC 3 Controller

Although, @Tomasz is absolutely right there is another way:

@RequestMapping(value="/controller", method=GET)
public void foo(HttpServletResponse res) {
    try {       
        PrintWriter out = res.getWriter();
        out.println("Hello, world!");
        out.close();
    } catch (IOException ex) { 
        ...
    }
}

but the first method is preferable. You can use this method if you want to return response with custom content type or return binary type (file, etc...);

Passing arguments to AsyncTask, and returning results

I dont do it like this. I find it easier to overload the constructor of the asychtask class ..

public class calc_stanica extends AsyncTask>

String String mWhateveryouwantToPass;

 public calc_stanica( String whateveryouwantToPass)
{

    this.String mWhateveryouwantToPass = String whateveryouwantToPass;
}
/*Now you can use  whateveryouwantToPass in the entire asynchTask ... you could pass in a context to your activity and try that too.*/   ...  ...  

How to use a Bootstrap 3 glyphicon in an html select

I ended up using the bootstrap 3 dropdown button, I'm posting my solution here in case it helps someone in future. Adding the bootstrap 3 list-inline to the class for the ul causes it to display in a nicely compact format as well.

<div class="btn-group">
    <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
        Select icon <span class="caret"></span>
    </button>
    <ul class="dropdown-menu list-inline" role="menu">
        <li><span class="glyphicon glyphicon-cutlery"></span></li>
        <li><span class="glyphicon glyphicon-fire"></span></li>
        <li><span class="glyphicon glyphicon-glass"></span></li>
        <li><span class="glyphicon glyphicon-heart"></span></li>          
    </ul>
</div>

I'm using Angular.js so this is the actual code I used:

<div class="btn-group">
            <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
                Avatar <span class="caret"></span>
            </button>
            <ul class="dropdown-menu list-inline" role="menu">
                <li ng-repeat="avatar in avatars" ng-click="avatarSelected(avatar)">
                    <span ng-class="getAvatar(avatar)"></span>
                </li>
            </ul>
        </div>

And in my controller:

$scope.avatars=['cutlery','eye-open','flag','flash','glass','fire','hand-right','heart','heart-empty','leaf','music','send','star','star-empty','tint','tower','tree-conifer','tree-deciduous','usd','user','wrench','time','road','cloud'];

$scope.getAvatar=function(avatar){
     return 'glyphicon glyphicon-'+avatar;
};

Disable ONLY_FULL_GROUP_BY

I'm using doctrine and I have added the driverOptions in my doctrine.local.php :

return array(
'doctrine' => array(
    'connection' => array(
        'orm_default' => array(
            'driverClass' => 'Doctrine\DBAL\Driver\PDOMySql\Driver',
            'params' => array(
                'host' => 'localhost',
                'port' => '3306',
                'user' => 'myusr',
                'password' => 'mypwd',
                'dbname' => 'mydb',
                'driverOptions' => array(
                    PDO::MYSQL_ATTR_INIT_COMMAND => "SET sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''))"
                ),
            ),
        ),
    ),
));

In phpmyadmin the user needs SUPER activated in the privileges.

How do I update/upsert a document in Mongoose?

//Here is my code to it... work like ninj

router.param('contractor', function(req, res, next, id) {
  var query = Contractors.findById(id);

  query.exec(function (err, contractor){
    if (err) { return next(err); }
    if (!contractor) { return next(new Error("can't find contractor")); }

    req.contractor = contractor;
    return next();
  });
});

router.get('/contractors/:contractor/save', function(req, res, next) {

    contractor = req.contractor ;
    contractor.update({'_id':contractor._id},{upsert: true},function(err,contractor){
       if(err){ 
            res.json(err);
            return next(); 
            }
    return res.json(contractor); 
  });
});


--

.ssh directory not being created

I am assuming that you have enough permissions to create this directory.

To fix your problem, you can either ssh to some other location:

ssh [email protected]

and accept new key - it will create directory ~/.ssh and known_hosts underneath, or simply create it manually using

mkdir ~/.ssh
chmod 700 ~/.ssh

Note that chmod 700 is an important step!

After that, ssh-keygen should work without complaints.

Fastest way to copy a file in Node.js

This is a good way to copy a file in one line of code using streams:

var fs = require('fs');
fs.createReadStream('test.log').pipe(fs.createWriteStream('newLog.log'));

In Node.js v8.5.0, copyFile was added.

const fs = require('fs');

// File destination.txt will be created or overwritten by default.
fs.copyFile('source.txt', 'destination.txt', (err) => {
  if (err) throw err;
  console.log('source.txt was copied to destination.txt');
});

How can I make the browser wait to display the page until it's fully loaded?

There is certainly a valid use for this. One is to prevent people from clicking on links/causing JavaScript events to occur until all the page elements and JavaScript have loaded.

In IE, you could use page transitions which mean the page doesn't display until it's fully loaded:

<meta http-equiv="Page-Enter" content="blendTrans(Duration=.01)" />
<meta http-equiv="Page-Exit" content="blendTrans(Duration=.01)" />

Notice the short duration. It's just enough to make sure the page doesn't display until it's fully loaded.

In FireFox and other browsers, the solution I've used is to create a DIV that is the size of the page and white, then at the very end of the page put in JavaScript that hides it. Another way would be to use jQuery and hide it as well. Not as painless as the IE solution but both work well.

MySQLi count(*) always returns 1

$result->num_rows; only returns the number of row(s) affected by a query. When you are performing a count(*) on a table it only returns one row so you can not have an other result than 1.

Consider marking event handler as 'passive' to make the page more responsive

This hides the warning message:

jQuery.event.special.touchstart = {
  setup: function( _, ns, handle ) {
      this.addEventListener("touchstart", handle, { passive: !ns.includes("noPreventDefault") });
  }
};

How to fix PHP Warning: PHP Startup: Unable to load dynamic library 'ext\\php_curl.dll'?

maybe useful for somebody, I got next problem on windows 8, apache 2.4, php 7+.

php.ini conf>

extension_dir="C:/Server/PHP7/ext"

php on apache works ok but on cli problem with libs loading, as a result, I changed to

extension_dir="C:/server/PHP7/ext"

How to set default value for form field in Symfony2?

I solved this problem, by adding value in attr:

->add('projectDeliveringInDays', null, [
    'attr' => [
          'min'=>'1',
          'value'=>'1'
          ]
     ])

Public class is inaccessible due to its protection level

Also if you want to do something like ClassB.Run("thing");, make sure the Method Run(); is static or you could call it like this: thing.Run("thing");.

MySQL Server has gone away when importing large sql file

I had similar error today when duplicating database (MySQL server has gone away...), but when I tried to restart mysql.server restart I got error

ERROR! The server quit without updating PID ...

This is how I solved it: I opened up Applications/Utilities/ and ran Activity Monitor

 quit mysqld

then was able to solve the error problem with

mysql.server restart

indexOf method in an object array?

While, most other answers here are valid. Sometimes, it's best to just make a short simple function near where you will use it.

// indexOf wrapper for the list of objects
function indexOfbyKey(obj_list, key, value) {
    for (index in obj_list) {
        if (obj_list[index][key] === value) return index;
    }
    return -1;
}
// Find the string in the list (default -1)
var test1 = indexOfbyKey(object_list, 'name', 'Stevie');
var test2 = indexOfbyKey(object_list, 'last_name', 'some other name');

It depends on what is important to you. It might save lines of code and be very clever to use a one-liner, or to put a generic solution somewhere that covers various edge cases. But sometimes it's better to just say: "here I did it like this" rather than leave future developers to have extra reverse engineering work. Especially if you consider yourself "a newbie" like in your question.

Is there a C++ decompiler?

information is discarded in the compiling process. Even if a decompiler could produce the logical equivalent code with classes and everything (it probably can't), the self-documenting part is gone in optimized release code. No variable names, no routine names, no class names - just addresses.

Assign an initial value to radio button as checked

The other way to set default checked on radio buttons, especially if you're using angularjs is setting the 'ng-checked' flag to "true" eg: <input id="d_man" value="M" ng-disabled="some Value" type="radio" ng-checked="true">Man

the checked="checked" did not work for me..

How to implement a Navbar Dropdown Hover in Bootstrap v4?

Just Add this simple css code in your style-sheet and you are ready to go.

.dropdown:hover > .dropdown-menu {
    display: block;
}
.dropdown > .dropdown-toggle:active {
    /*Without this, clicking will make it sticky*/
    pointer-events: none;
}

Split varchar into separate columns in Oracle

Depends on the consistency of the data - assuming a single space is the separator between what you want to appear in column one vs two:

SELECT SUBSTR(t.column_one, 1, INSTR(t.column_one, ' ')-1) AS col_one,
       SUBSTR(t.column_one, INSTR(t.column_one, ' ')+1) AS col_two
  FROM YOUR_TABLE t

Oracle 10g+ has regex support, allowing more flexibility depending on the situation you need to solve. It also has a regex substring method...

Reference:

Build Maven Project Without Running Unit Tests

If you want to skip running and compiling tests:

mvn -Dmaven.test.skip=true install

If you want to compile but not run tests:

mvn install -DskipTests

Partition Function COUNT() OVER possible using DISTINCT

There is a very simple solution using dense_rank()

dense_rank() over (partition by [Mth] order by [UserAccountKey]) 
+ dense_rank() over (partition by [Mth] order by [UserAccountKey] desc) 
- 1

This will give you exactly what you were asking for: The number of distinct UserAccountKeys within each month.

How to present UIAlertController when not in a view controller?

Updated to work with iOS 13 Scenes which breaks the new UIWindow approach. Swift 5.1.

fileprivate var alertWindows = [UIAlertController:UIWindow]()

extension UIAlertController {

    func presentInNewWindow(animated: Bool, completion: (() -> Void)?) {
        let foregroundActiveScene = UIApplication.shared.connectedScenes.filter { $0.activationState == .foregroundActive }.first
        guard let foregroundWindowScene = foregroundActiveScene as? UIWindowScene else { return }

        let window = UIWindow(windowScene: foregroundWindowScene)
        alertWindows[self] = window

        window.rootViewController = UIViewController()
        window.windowLevel = .alert + 1
        window.makeKeyAndVisible()
        window.rootViewController!.present( self, animated: animated, completion: completion)
    }

    open override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        alertWindows[self] = nil
    }

}

How can I String.Format a TimeSpan object with a custom format in .NET?

I would go with

myTimeSpan.ToString("hh\\:mm\\:ss");

Gradient borders

try this code

.gradientBoxesWithOuterShadows { 
height: 200px;
width: 400px; 
padding: 20px;
background-color: white; 

/* outer shadows  (note the rgba is red, green, blue, alpha) */
-webkit-box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.4); 
-moz-box-shadow: 0px 1px 6px rgba(23, 69, 88, .5);

/* rounded corners */
-webkit-border-radius: 12px;
-moz-border-radius: 7px; 
border-radius: 7px;

/* gradients */
background: -webkit-gradient(linear, left top, left bottom, 
color-stop(0%, white), color-stop(15%, white), color-stop(100%, #D7E9F5)); 
background: -moz-linear-gradient(top, white 0%, white 55%, #D5E4F3 130%); 
}

or maybe refer to this fiddle: http://jsfiddle.net/necolas/vqnk9/

What's the most useful and complete Java cheat sheet?

It's not really a cheat-sheet, but for me I setup a 'java' search keyword in Google Chrome to search over the javadoc, using site:<javadoc_domain_here>.

You could do the same but also add the domain for the Sun Java Tutorial and for several Java FAQ sites and you'd be OK.

Otherwise, StackOverflow is a pretty good cheat-sheet :)

How can I count the occurrences of a string within a file?

I'm taking some guesses here, because I don't quite understand what you're asking.

I think that what you want is a count of the number of lines on which the pattern 'echo' appears in the given file.

I've pasted your sample text into a file called 6741967.

First, grep finds the matches:

james@Brindle:tmp$grep echo 6741967 
    echo "Preparing to add a new user..."
echo "1. Add user"
echo "2. Exit"
echo "Enter your choice: "

Second, use wc -l to count the lines

james@Brindle:tmp$grep echo 6741967  | wc -l
       4

How To Convert A Number To an ASCII Character?

Edit: By request, I added a check to make sure the value entered was within the ASCII range of 0 to 127. Whether you want to limit this is up to you. In C# (and I believe .NET in general), chars are represented using UTF-16, so any valid UTF-16 character value could be cast into it. However, it is possible a system does not know what every Unicode character should look like so it may show up incorrectly.

// Read a line of input
string input = Console.ReadLine();

int value;
// Try to parse the input into an Int32
if (Int32.TryParse(input, out value)) {
    // Parse was successful
    if (value >= 0 and value < 128) {
        //value entered was within the valid ASCII range
        //cast value to a char and print it
        char c = (char)value;
        Console.WriteLine(c);
    }
}

How to get an enum value from a string value in Java?

In Java 8 the static Map pattern is even easier and is my preffered method. If you want to use the Enum with Jackson you can override toString and use that instead of name, then annotate with @JsonValue

public enum MyEnum {
    BAR,
    BAZ;
    private static final Map<String, MyEnum> MAP = Stream.of(MyEnum.values()).collect(Collectors.toMap(Enum::name, Function.identity()));
    public static MyEnum fromName(String name){
        return MAP.get(name);
    }
}

public enum MyEnumForJson {
    BAR("bar"),
    BAZ("baz");
    private static final Map<String, MyEnumForJson> MAP = Stream.of(MyEnumForJson.values()).collect(Collectors.toMap(Object::toString, Function.identity()));
    private final String value;

    MyEnumForJson(String value) {
        this.value = value;
    }

    @JsonValue
    @Override
    public String toString() {
        return value;
    }

    public static MyEnumForJson fromValue(String value){
        return MAP.get(value);
    }
}

Where can I find the .apk file on my device, when I download any app and install?

You can use a file browser with an backup function, for example the ES File Explorer Long tap a item and select create backup

Python - How to convert JSON File to Dataframe

jsondata = '{"0001":{"FirstName":"John","LastName":"Mark","MiddleName":"Lewis","username":"johnlewis2","password":"2910"}}'
import json
import pandas as pd
jdata = json.loads(jsondata)
df = pd.DataFrame(jdata)
print df.T

This should look like this:.

         FirstName LastName MiddleName password    username
0001      John     Mark      Lewis     2910  johnlewis2

Trying to detect browser close event

Maybe it's better to use the path detecting mouse.

In BrowserClosureNotice you have a demo example and pure javascript library to do it.

It isn't perfect, but avoid problems of document or mouse events...

Maven and adding JARs to system scope

Thanks to Ging3r i got solution:

follow these steps:

  1. don't use in dependency tag. Use following in dependencies tag in pom.xml file::

    <dependency>
    <groupId>com.netsuite.suitetalk.proxy.v2019_1</groupId>
    <artifactId>suitetalk-axis-proxy-v2019_1</artifactId>
    <version>1.0.0</version>
    </dependency>
    <dependency>
        <groupId>com.netsuite.suitetalk.client.v2019_1</groupId>
        <artifactId>suitetalk-client-v2019_1</artifactId>
        <version>2.0.0</version>
    </dependency>
    <dependency>
        <groupId>com.netsuite.suitetalk.client.common</groupId>
        <artifactId>suitetalk-client-common</artifactId>
        <version>1.0.0</version>
    </dependency>
    
  2. use following code in plugins tag in pom.xml file:

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-install-plugin</artifactId>
            <version>2.5.2</version>
            <executions>
                <execution>
                    <id>suitetalk-proxy</id>
                    <phase>clean</phase>
                    <configuration>
                        <file>${basedir}/lib/suitetalk-axis-proxy-v2019_1-1.0.0.jar</file>
                        <repositoryLayout>default</repositoryLayout>
                        <groupId>com.netsuite.suitetalk.proxy.v2019_1</groupId>
                        <artifactId>suitetalk-axis-proxy-v2019_1</artifactId>
                        <version>1.0.0</version>
                        <packaging>jar</packaging>
                        <generatePom>true</generatePom>
                    </configuration>
                    <goals>
                        <goal>install-file</goal>
                    </goals>
                </execution>
                <execution>
                    <id>suitetalk-client</id>
                    <phase>clean</phase>
                    <configuration>
                        <file>${basedir}/lib/suitetalk-client-v2019_1-2.0.0.jar</file>
                        <repositoryLayout>default</repositoryLayout>
                        <groupId>com.netsuite.suitetalk.client.v2019_1</groupId>
                        <artifactId>suitetalk-client-v2019_1</artifactId>
                        <version>2.0.0</version>
                        <packaging>jar</packaging>
                        <generatePom>true</generatePom>
                    </configuration>
                    <goals>
                        <goal>install-file</goal>
                    </goals>
                </execution>
                <execution>
                    <id>suitetalk-client-common</id>
                    <phase>clean</phase>
                    <configuration>
                        <file>${basedir}/lib/suitetalk-client-common-1.0.0.jar</file>
                        <repositoryLayout>default</repositoryLayout>
                        <groupId>com.netsuite.suitetalk.client.common</groupId>
                        <artifactId>suitetalk-client-common</artifactId>
                        <version>1.0.0</version>
                        <packaging>jar</packaging>
                        <generatePom>true</generatePom>
                    </configuration>
                    <goals>
                        <goal>install-file</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    

I am including 3 jars from lib folder:

including external jar in spring boot project

Finally, use mvn clean and then mvn install or 'mvn clean install' and just run jar file from target folder or the path where install(see mvn install log):

java -jar abc.jar

note: Remember one thing if you are working at jenkins then first use mvn clean and then mvn clean install command work for you because with previous code mvn clean install command store cache for dependency.

How to import a module given its name as string?

Nowadays you should use importlib.

Import a source file

The docs actually provide a recipe for that, and it goes like:

import sys
import importlib.util

file_path = 'pluginX.py'
module_name = 'pluginX'

spec = importlib.util.spec_from_file_location(module_name, file_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)

# check if it's all there..
def bla(mod):
    print(dir(mod))
bla(module)

This way you can access the members (e.g, a function "hello") from your module pluginX.py -- in this snippet being called module -- under its namespace; E.g, module.hello().

If you want to import the members (e.g, "hello") you can include module/pluginX in the in-memory list of modules:

sys.modules[module_name] = module

from pluginX import hello
hello()

Import a package

Importing a package (e.g., pluginX/__init__.py) under your current dir is actually straightforward:

import importlib

pkg = importlib.import_module('pluginX')

# check if it's all there..
def bla(mod):
    print(dir(mod))
bla(pkg)

How do I show a console output/window in a forms application?

Create a Windows Forms Application, and change the output type to Console.

It will result in both a console and the form to open.

enter image description here

HTML/CSS: how to put text both right and left aligned in a paragraph

I wouldn't put it in the same <p>, since IMHO the two infos are semantically too different. If you must, I'd suggest this:

<p style="text-align:right">
 <span style="float:left">I'll be on the left</span>
 I'll be on the right
</p>

Typedef function pointer?

Without the typedef word, in C++ the declaration would declare a variable FunctionFunc of type pointer to function of no arguments, returning void.

With the typedef it instead defines FunctionFunc as a name for that type.

Adding three months to a date in PHP

This answer is not exactly to this question. But I will add this since this question still searchable for how to add/deduct period from date.

$date = new DateTime('now');
$date->modify('+3 month'); // or you can use '-90 day' for deduct
$date = $date->format('Y-m-d h:i:s');
echo $date;

Image height and width not working?

You must write

<img src="theSource" style="width:30px;height:30px;" />

Inline styling will always take precedence over CSS styling. The width and height attributes are being overridden by your stylesheet, so you need to switch to this format.

Sort collection by multiple fields in Kotlin

sortedWith + compareBy (taking a vararg of lambdas) do the trick:

val sortedList = list.sortedWith(compareBy({ it.age }, { it.name }))

You can also use the somewhat more succinct callable reference syntax:

val sortedList = list.sortedWith(compareBy(Person::age, Person::name))

Text in a flex container doesn't wrap in IE11

Why use a complicated solution if a simple one works too?

.child {
  white-space: normal;
}

How do I find the time difference between two datetime objects in python?

Based on @Attaque great answer, I propose a shorter simplified version of the datetime difference calculator:

seconds_mapping = {
    'y': 31536000,
    'm': 2628002.88, # this is approximate, 365 / 12; use with caution
    'w': 604800,
    'd': 86400,
    'h': 3600,
    'min': 60,
    's': 1,
    'mil': 0.001,
}

def get_duration(d1, d2, interval, with_reminder=False):
    if with_reminder:
        return divmod((d2 - d1).total_seconds(), seconds_mapping[interval])
    else:
        return (d2 - d1).total_seconds() / seconds_mapping[interval]

I've changed it to avoid declaring repetetive functions, removed the pretty print default interval and added support for milliseconds, weeks and ISO months (bare in mind months are just approximate, based on assumption that each month is equal to 365/12).

Which produces:

d1 = datetime(2011, 3, 1, 1, 1, 1, 1000)
d2 = datetime(2011, 4, 1, 1, 1, 1, 2500)

print(get_duration(d1, d2, 'y', True))      # => (0.0, 2678400.0015)
print(get_duration(d1, d2, 'm', True))      # => (1.0, 50397.12149999989)
print(get_duration(d1, d2, 'w', True))      # => (4.0, 259200.00149999978)
print(get_duration(d1, d2, 'd', True))      # => (31.0, 0.0014999997802078724)
print(get_duration(d1, d2, 'h', True))      # => (744.0, 0.0014999997802078724)
print(get_duration(d1, d2, 'min', True))    # => (44640.0, 0.0014999997802078724)
print(get_duration(d1, d2, 's', True))      # => (2678400.0, 0.0014999997802078724)
print(get_duration(d1, d2, 'mil', True))    # => (2678400001.0, 0.0004999997244524721)

print(get_duration(d1, d2, 'y', False))     # => 0.08493150689687975
print(get_duration(d1, d2, 'm', False))     # => 1.019176965856293
print(get_duration(d1, d2, 'w', False))     # => 4.428571431051587
print(get_duration(d1, d2, 'd', False))     # => 31.00000001736111
print(get_duration(d1, d2, 'h', False))     # => 744.0000004166666
print(get_duration(d1, d2, 'min', False))   # => 44640.000024999994
print(get_duration(d1, d2, 's', False))     # => 2678400.0015
print(get_duration(d1, d2, 'mil', False))   # => 2678400001.4999995

How do I scroll to an element within an overflowed Div?

I write these 2 functions to make my life easier:

function scrollToTop(elem, parent, speed) {
    var scrollOffset = parent.scrollTop() + elem.offset().top;
    parent.animate({scrollTop:scrollOffset}, speed);
    // parent.scrollTop(scrollOffset, speed);
}

function scrollToCenter(elem, parent, speed) {
    var elOffset = elem.offset().top;
    var elHeight = elem.height();
    var parentViewTop = parent.offset().top;
    var parentHeight = parent.innerHeight();
    var offset;

    if (elHeight >= parentHeight) {
        offset = elOffset;
    } else {
        margin = (parentHeight - elHeight)/2;
        offset = elOffset - margin;
    }

    var scrollOffset = parent.scrollTop() + offset - parentViewTop;

    parent.animate({scrollTop:scrollOffset}, speed);
    // parent.scrollTop(scrollOffset, speed);
}

And use them:

scrollToTop($innerListItem, $parentDiv, 200);
// or
scrollToCenter($innerListItem, $parentDiv, 200);

json_decode() expects parameter 1 to be string, array given

json_decode() is used to decode a json string to an array/data object. json_encode() creates a json string from an array or data. You are using the wrong function my friend, try json_encode();

How to convert an xml string to a dictionary?

The easiest to use XML parser for Python is ElementTree (as of 2.5x and above it is in the standard library xml.etree.ElementTree). I don't think there is anything that does exactly what you want out of the box. It would be pretty trivial to write something to do what you want using ElementTree, but why convert to a dictionary, and why not just use ElementTree directly.

htaccess redirect all pages to single page

RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www\.)?olddomain\.com$ [NC]
RewriteRule ^(.*)$ "http://www.thenewdomain.com/" [R=301,L]

How to fetch all Git branches

You will need to create local branches tracking remote branches.

Assuming that you've got only one remote called origin, this snippet will create local branches for all remote tracking ones:

for b in `git branch -r | grep -v -- '->'`; do git branch --track ${b##origin/} $b; done

After that, git fetch --all will update all local copies of remote branches.

Also, git pull --all will update your local tracking branches, but depending on your local commits and how the 'merge' configure option is set it might create a merge commit, fast-forward or fail.

How to insert text at beginning of a multi-line selection in vi/Vim

If you want to get super fancy about it, put this in your .vimrc:

vmap \c :s!^!//!<CR>
vmap \u :s!^//!!<CR>

Then, whenever in visual mode, you can hit \c to comment the block and \u to uncomment it. Of course, you can change those shortcut keystrokes to whatever.

vue.js 2 how to watch store values from vuex

Let's say, for example, that you have a basket of fruits, and each time you add or remove a fruit from the basket, you want to (1) display info about fruit count, but you also (2) want to be notified of the count of the fruits in some fancy fashion...

fruit-count-component.vue

<template>
  <!-- We meet our first objective (1) by simply -->
  <!-- binding to the count property. -->
  <p>Fruits: {{ count }}</p>
</template>

<script>
import basket from '../resources/fruit-basket'

export default () {
  computed: {
    count () {
      return basket.state.fruits.length
      // Or return basket.getters.fruitsCount
      // (depends on your design decisions).
    }
  },
  watch: {
    count (newCount, oldCount) {
      // Our fancy notification (2).
      console.log(`We have ${newCount} fruits now, yay!`)
    }
  }
}
</script>

Please note, that the name of the function in the watch object, must match the name of the function in the computed object. In the example above the name is count.

New and old values of a watched property will be passed into watch callback (the count function) as parameters.

The basket store could look like this:

fruit-basket.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const basket = new Vuex.Store({
  state: {
    fruits: []
  },
  getters: {
    fruitsCount (state) {
      return state.fruits.length
    }
  }
  // Obviously you would need some mutations and actions,
  // but to make example cleaner I'll skip this part.
})

export default basket

You can read more in the following resources:

Open Facebook Page in Facebook App (if installed) on Android

I already have answered here and it's working for me, please refer this link https://stackoverflow.com/a/40133225/3636561

    String socailLink="https://www.facebook.com/kfc";
    Intent intent = new Intent(Intent.ACTION_VIEW);
    String facebookUrl = Utils.getFacebookUrl(getActivity(), socailLink);
    if (facebookUrl == null || facebookUrl.length() == 0) {
        Log.d("facebook Url", " is coming as " + facebookUrl);
        return;
    }
    intent.setData(Uri.parse(facebookUrl));
    startActivity(intent);

please refer link to get rest part.

Spring mvc @PathVariable

It is one of the annotation used to map/handle dynamic URIs. You can even specify a regular expression for URI dynamic parameter to accept only specific type of input.

For example, if the URL to retrieve a book using a unique number would be:

URL:http://localhost:8080/book/9783827319333

The number denoted at the last of the URL can be fetched using @PathVariable as shown:

@RequestMapping(value="/book/{ISBN}", method= RequestMethod.GET)

public String showBookDetails(@PathVariable("ISBN") String id,

Model model){

model.addAttribute("ISBN", id);

return "bookDetails";

}

In short it is just another was to extract data from HTTP requests in Spring.

Segmentation fault on large array sizes

Because you store the array in the stack. You should store it in the heap. See this link to understand the concept of the heap and the stack.

Absolute positioning ignoring padding of parent

Could have easily done using an extra level of Div.

<div style="background-color: blue; padding: 10px; position: relative; height: 100px;">
  <div style="position: absolute; left: 0px; right: 0px; bottom: 10px; padding:0px 10px;">
    <div style="background-color: gray;">css sux</div>
  </div>
</div>

Demo: https://jsfiddle.net/soxv3vr0/

Configuring user and password with Git Bash

From Git Bash I prefer to run the command:

git config --global credential.helper wincred

At that point running a command like git pull and entering your credentials one time should have it stored for future use. Git has a built-in credentials system that works in different OS environments. You can get more details here: 7.14 Git Tools - Credential Storage

How to Find Item in Dictionary Collection?

thisTag = _tags.FirstOrDefault(t => t.Key == tag);

is an inefficient and a little bit strange way to find something by key in a dictionary. Looking things up for a Key is the basic function of a Dictionary.

The basic solution would be:

if (_tags.Containskey(tag)) { string myValue = _tags[tag]; ... }

But that requires 2 lookups.

TryGetValue(key, out value) is more concise and efficient, it only does 1 lookup. And that answers the last part of your question, the best way to do a lookup is:

string myValue;
if (_tags.TryGetValue(tag, out myValue)) { /* use myValue */ }

VS 2017 update, for C# 7 and beyond we can declare the result variable inline:

if (_tags.TryGetValue(tag, out string myValue))
{
    // use myValue;
}
// use myValue, still in scope, null if not found

How do I return JSON without using a template in Django?

If you want to pass the result as a rendered template you have to load and render a template, pass the result of rendering it to the json.This could look like that:

from django.template import loader, RequestContext

#render the template
t=loader.get_template('sample/sample.html')
context=RequestContext()
html=t.render(context)

#create the json
result={'html_result':html)
json = simplejson.dumps(result)

return HttpResponse(json)

That way you can pass a rendered template as json to your client. This can be useful if you want to completely replace ie. a containing lots of different elements.

What is the maximum length of a URL in different browsers?

WWW FAQs: What is the maximum length of a URL? has its own answer based on empirical testing and research. The short answer is that going over 2048 characters makes Internet Explorer unhappy and thus this is the limit you should use. See the page for a long answer.

Prevent textbox autofill with previously entered values

Adding autocomplete="new-password" to the password field did the trick. Removed auto filling of both user name and password fields in Chrome.

<input type="password" name="whatever" autocomplete="new-password" />

Android TextView Justify Text

I found a way to solve this problem, but this may not be very grace, but the effect is not bad.

Its principle is to replace the spaces of each line to the fixed-width ImageSpan (the color is transparent).

public static void justify(final TextView textView) {

    final AtomicBoolean isJustify = new AtomicBoolean(false);

    final String textString = textView.getText().toString();

    final TextPaint textPaint = textView.getPaint();

    final SpannableStringBuilder builder = new SpannableStringBuilder();

    textView.post(new Runnable() {
        @Override
        public void run() {

            if (!isJustify.get()) {

                final int lineCount = textView.getLineCount();
                final int textViewWidth = textView.getWidth();

                for (int i = 0; i < lineCount; i++) {

                    int lineStart = textView.getLayout().getLineStart(i);
                    int lineEnd = textView.getLayout().getLineEnd(i);

                    String lineString = textString.substring(lineStart, lineEnd);

                    if (i == lineCount - 1) {
                        builder.append(new SpannableString(lineString));
                        break;
                    }

                    String trimSpaceText = lineString.trim();
                    String removeSpaceText = lineString.replaceAll(" ", "");

                    float removeSpaceWidth = textPaint.measureText(removeSpaceText);
                    float spaceCount = trimSpaceText.length() - removeSpaceText.length();

                    float eachSpaceWidth = (textViewWidth - removeSpaceWidth) / spaceCount;

                    SpannableString spannableString = new SpannableString(lineString);
                    for (int j = 0; j < trimSpaceText.length(); j++) {
                        char c = trimSpaceText.charAt(j);
                        if (c == ' ') {
                            Drawable drawable = new ColorDrawable(0x00ffffff);
                            drawable.setBounds(0, 0, (int) eachSpaceWidth, 0);
                            ImageSpan span = new ImageSpan(drawable);
                            spannableString.setSpan(span, j, j + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                        }
                    }

                    builder.append(spannableString);
                }

                textView.setText(builder);
                isJustify.set(true);
            }
        }
    });
}

I put the code on GitHub: https://github.com/twiceyuan/TextJustification

Overview:

Overview

Failed to Connect to MySQL at localhost:3306 with user root

Try to execute below command in your terminal :

mysql -h localhost -P 3306 -u root -p

If you successfully connect to your database, then same thing has to happen with Mysql Workbench.

If you are unable to connect then I think 3306 port is acquired by another process.

Find which process running on 3306 port. If required, give admin privileges using sudo.

netstat -lnp | grep 3306

Kill/stop that process and restart your MySQL server. You are good to go.


Execute below command to find my.cnf file in macbook.

mysql --help | grep cnf

You can change MySQL port to any available port in your system. But after that, make sure you restart MySQL server.

Get property value from C# dynamic object by string (reflection?)

you can try like this:

d?.property1 , d?.property2

I have tested it and working with .netcore 2.1

How do I get the base URL with PHP?

function server_url(){
    $server ="";

    if(isset($_SERVER['SERVER_NAME'])){
        $server = sprintf("%s://%s%s", isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http', $_SERVER['SERVER_NAME'], '/');
    }
    else{
        $server = sprintf("%s://%s%s", isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http', $_SERVER['SERVER_ADDR'], '/');
    }
    print $server;

}

How to use "not" in xpath?

None of these answers worked for me for python. I solved by this

a[not(@id='XX')]

Also you can use or condition in your xpath by | operator. Such as

a[not(@id='XX')]|a[not(@class='YY')]

Sometimes we want element which has no class. So you can do like

a[not(@class)]

How do I find the length of an array?

#include <iostream>

int main ()
{
    using namespace std;
    int arr[] = {2, 7, 1, 111};
    auto array_length = end(arr) - begin(arr);
    cout << "Length of array: " << array_length << endl;
}

Quickest way to convert a base 10 number to any base in .NET?

Could this class from this forum post help you?

public class BaseConverter { 

public static string ToBase(string number, int start_base, int target_base) { 

  int base10 = this.ToBase10(number, start_base); 
  string rtn = this.FromBase10(base10, target_base); 
  return rtn; 

} 

public static int ToBase10(string number, int start_base) { 

  if (start_base < 2 || start_base > 36) return 0; 
  if (start_base == 10) return Convert.ToInt32(number); 

  char[] chrs = number.ToCharArray(); 
  int m = chrs.Length - 1; 
  int n = start_base; 
  int x; 
  int rtn = 0; 

  foreach(char c in chrs) { 

    if (char.IsNumber(c)) 
      x = int.Parse(c.ToString()); 
    else 
      x = Convert.ToInt32(c) - 55; 

    rtn += x * (Convert.ToInt32(Math.Pow(n, m))); 

    m--; 

  } 

  return rtn; 

} 

public static string FromBase10(int number, int target_base) { 

  if (target_base < 2 || target_base > 36) return ""; 
  if (target_base == 10) return number.ToString(); 

  int n = target_base; 
  int q = number; 
  int r; 
  string rtn = ""; 

  while (q >= n) { 

    r = q % n; 
    q = q / n; 

    if (r < 10) 
      rtn = r.ToString() + rtn; 
    else 
      rtn = Convert.ToChar(r + 55).ToString() + rtn; 

  } 

  if (q < 10) 
    rtn = q.ToString() + rtn; 
  else 
    rtn = Convert.ToChar(q + 55).ToString() + rtn; 

  return rtn; 

} 

}

Totally untested... let me know if it works! (Copy-pasted it in case the forum post goes away or something...)

How to extract epoch from LocalDate and LocalDateTime?

The conversion you need requires the offset from UTC/Greewich, or a time-zone.

If you have an offset, there is a dedicated method on LocalDateTime for this task:

long epochSec = localDateTime.toEpochSecond(zoneOffset);

If you only have a ZoneId then you can obtain the ZoneOffset from the ZoneId:

ZoneOffset zoneOffset = ZoneId.of("Europe/Oslo").getRules().getOffset(ldt);

But you may find conversion via ZonedDateTime simpler:

long epochSec = ldt.atZone(zoneId).toEpochSecond();

How to create a POJO?

POJO class acts as a bean which is used to set and get the value.

public class Data
{


private int id;
    private String deptname;
    private String date;
    private String name;
    private String mdate;
    private String mname;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getDeptname() {
        return deptname;
    }

    public void setDeptname(String deptname) {
        this.deptname = deptname;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getMdate() {
        return mdate;
    }

    public void setMdate(String mdate) {
        this.mdate = mdate;
    }

    public String getMname() {
        return mname;
    }

    public void setMname(String mname) {
        this.mname = mname;
    }
}

Catch multiple exceptions in one line (except block)

If you frequently use a large number of exceptions, you can pre-define a tuple, so you don't have to re-type them many times.

#This example code is a technique I use in a library that connects with websites to gather data

ConnectErrs  = (URLError, SSLError, SocketTimeoutError, BadStatusLine, ConnectionResetError)

def connect(url, data):
    #do connection and return some data
    return(received_data)

def some_function(var_a, var_b, ...):
    try: o = connect(url, data)
    except ConnectErrs as e:
        #do the recovery stuff
    blah #do normal stuff you would do if no exception occurred

NOTES:

  1. If you, also, need to catch other exceptions than those in the pre-defined tuple, you will need to define another except block.

  2. If you just cannot tolerate a global variable, define it in main() and pass it around where needed...

Combine or merge JSON on node.js without jQuery

Use spread operator. It is supported in Node since version 8.6

_x000D_
_x000D_
const object1 = {name: "John"};_x000D_
const object2 = {location: "San Jose"};_x000D_
_x000D_
const obj = {...object1, ...object2}_x000D_
_x000D_
console.log(obj)_x000D_
//   {_x000D_
//     "name": "John",_x000D_
//     "location": "San Jose"_x000D_
//   }
_x000D_
_x000D_
_x000D_

VBA code to set date format for a specific column as "yyyy-mm-dd"

Use the range's NumberFormat property to force the format of the range like this:

Sheet1.Range("A2", "A50000").NumberFormat = "yyyy-mm-dd"

Run java jar file on a server as background process

Systemd which now runs in the majority of distros

Step 1:

Find your user defined services mine was at /usr/lib/systemd/system/

Step 2:

Create a text file with your favorite text editor name it whatever_you_want.service

Step 3:

Put following Template to the file whatever_you_want.service

[Unit]
Description=webserver Daemon

[Service]
ExecStart=/usr/bin/java -jar /web/server.jar
User=user

[Install]
WantedBy=multi-user.target

Step 4:

Run your service
as super user

$ systemctl start whatever_you_want.service # starts the service
$ systemctl enable whatever_you_want.service # auto starts the service
$ systemctl disable whatever_you_want.service # stops autostart
$ systemctl stop whatever_you_want.service # stops the service
$ systemctl restart whatever_you_want.service # restarts the service

How to echo (or print) to the js console with php

<?php
   echo '<script>console.log("Your stuff here")</script>';
?>

How store a range from excel into a Range variable?

here is an example that allows for performing code on each line of the desired areas (pick either from top & bottom of selection, of from selection

Sub doROWSb()           'WORKS    for do selected rows     SEE FIX ROWS ABOVE  (small ver)
Dim E7 As String    'note:  workcell E7 shows:  BG381
E7 = RANGE("E7")    'see eg below
Dim r As Long       'NOTE: this example has a paste formula(s) down a column(s).  WILL REDUCE 10 HOUR DAYS OF PASTING COLUMNS, DOWN TO 3 MINUTES?
Dim c As Long
Dim rCell As RANGE
'Dim LastRow As Long
r = ActiveCell.row
c = ActiveCell.Column   'might not matter if your code affects whole line anyways, still leave as is

Dim FirstRow As Long    'not in use, Delete if only want last row, note: this code already allows for selection as start
Dim LastRow As Long


If 1 Then     'if you are unable to delete rows not needed, just change 2 lines from: If 1, to if 0 (to go from selection last row, to all rows down from selection)
With Selection
    'FirstRow = .Rows(1).row                 'not used here, Delete if only want last row
    LastRow = .Rows(.Rows.Count).row        'find last row in selection
End With
application.CutCopyMode = False             'if not doing any paste op below
Else
    LastRow = Cells(Rows.Count, 1).End(xlUp).row  'find last row used in sheet
End If
application.EnableEvents = True             'EVENTS  need this?
application.ScreenUpdating = False          'offset-cells(row, col)
'RANGE(E7).Select  'TOP ROW SELECT
RANGE("A1") = vbNullString                  'simple macros on-off switch, vb not here:  If RANGE("A1").Value > 0 Then


For Each rCell In RANGE(Cells(r, c), Cells(LastRow, c)) 'new
    rCell.Select    'make 3 macros for each paste macro below
'your code here:

If 1 Then     'to if 0, if want to paste formulas/formats/all down a column
    Selection.EntireRow.Calculate     'calcs all selected rows, even if just selecting 1 cell in each row (might only be doing 1 row aat here, as part of loop)
Else
'dorows() DO ROWS()
'eg's for paste cells down a column, can make 3 separate macros for each: sub alte() altf & altp
      Selection.PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone, SkipBlanks:=False, Transpose:=False    'make sub alte ()    add thisworkbook:  application.OnKey "%{e}", "alte"
      'Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, SkipBlanks:=False, Transpose:=False     'make sub altf ()    add thisworkbook:  application.OnKey "%{f}", "altf"
      'Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:=False, Transpose:=False         'amke sub altp ()    add thisworkbook:  application.OnKey "%{p}", "altp"
End If
Next rCell

'application.CutCopyMode = False            'finished - stop copy mode
'RANGE("A2").Select
goBEEPS (2), (0.25)       'beeps secs
application.EnableEvents = True             'EVENTS

'note:  workcell E7 has: SUBSTITUTE(SUBSTITUTE(CELL("address",$BG$369),"$",""),"","")
'other col eg (shows: BG:BG):  =SUBSTITUTE(SUBSTITUTE(CELL("address",$BG2),"$",""),ROW(),"")&":"& SUBSTITUTE(SUBSTITUTE(CELL("address",$BG2),"$",""),ROW(),"")
End Sub


'OTHER:
Sub goBEEPSx(b As Long, t As Double)   'beeps secs as:  goBEEPS (2), (0.25)  OR:  goBEEPS(2, 0.25)
  Dim dt  'as double    'worked wo as double
  Dim x
  For b = b To 1 Step -1
    Beep
    x = Timer
  Do
  DoEvents
  dt = Timer - x
  If dt < 0 Then dt = dt + 86400    '86400 no. seconds in a day, in case hit midnight & timer went down to 0
  Loop Until dt >= t
  Next
End Sub

How to check if a process is running via a batch script

Here's how I've worked it out:

tasklist /FI "IMAGENAME eq notepad.exe" /FO CSV > search.log

FOR /F %%A IN (search.log) DO IF %%~zA EQU 0 GOTO end

start notepad.exe

:end

del search.log

The above will open Notepad if it is not already running.

Edit: Note that this won't find applications hidden from the tasklist. This will include any scheduled tasks running as a different user, as these are automatically hidden.

How to compare pointers?

Simple code to check pointer aliasing:

int main () {
    int a = 10, b = 20;
    int *p1, *p2, *p3, *p4;

    p1 = &a;
    p2 = &a;
    if(p1 == p2){
        std::cout<<"p1 and p2 alias each other"<<std::endl;
    }
    else{
        std::cout<<"p1 and p2 do not alias each other"<<std::endl;
    }
    //------------------------
    p3 = &a;
    p4 = &b;
    if(p3 == p4){
        std::cout<<"p3 and p4 alias each other"<<std::endl;
    }
    else{
        std::cout<<"p3 and p4 do not alias each other"<<std::endl;
    }
    return 0;
}

Output:

p1 and p2 alias each other
p3 and p4 do not alias each other

Get started with Latex on Linux

I would personally use a complete editing package such as:

  • TexWorks
  • TexStudio

Then I would install "MikTeX" as the compiling package, which allows you to generate a PDF from your document, using the pdfLaTeX compiler.

Can I scale a div's height proportionally to its width using CSS?

You can use View Width for the "width" and again half of the View Width for the "height". In this way you're guaranteed the correct ratio regardless of the viewport size.

<div class="ss"></div>

.ss
{
    width: 30vw;
    height: 15vw;
}

Fiddle

What is std::move(), and when should it be used?

std::move itself doesn't really do much. I thought that it called the moved constructor for an object, but it really just performs a type cast (casting an lvalue variable to an rvalue so that the said variable can be passed as an argument to a move constructor or assignment operator).

So std::move is just used as a precursor to using move semantics. Move semantics is essentially an efficient way for dealing with temporary objects.

Consider Object A = B + C + D + E + F;

This is nice looking code, but E + F produces a temporary object. Then D + temp produces another temporary object and so on. In each normal "+" operator of a class, deep copies occur.

For example

Object Object::operator+ (const Object& rhs) {
    Object temp (*this);
    // logic for adding
    return temp;
}

The creation of the temporary object in this function is useless - these temporary objects will be deleted at the end of the line anyway as they go out of scope.

We can rather use move semantics to "plunder" the temporary objects and do something like

 Object& Object::operator+ (Object&& rhs) {
     // logic to modify rhs directly
     return rhs;
 }

This avoids needless deep copies being made. With reference to the example, the only part where deep copying occurs is now E + F. The rest uses move semantics. The move constructor or assignment operator also needs to be implemented to assign the result to A.

Can I display the value of an enum with printf()?

enum A { foo, bar } a;
a = foo;
printf( "%d", a );   // see comments below

Convert JsonNode into POJO

This should do the trick:

mapper.readValue(fileReader, MyClass.class);

I say should because I'm using that with a String, not a BufferedReader but it should still work.

Here's my code:

String inputString = // I grab my string here
MySessionClass sessionObject;
try {
    ObjectMapper objectMapper = new ObjectMapper();
    sessionObject = objectMapper.readValue(inputString, MySessionClass.class);

Here's the official documentation for that call: http://jackson.codehaus.org/1.7.9/javadoc/org/codehaus/jackson/map/ObjectMapper.html#readValue(java.lang.String, java.lang.Class)

You can also define a custom deserializer when you instantiate the ObjectMapper: http://wiki.fasterxml.com/JacksonHowToCustomDeserializers

Edit: I just remembered something else. If your object coming in has more properties than the POJO has and you just want to ignore the extras you'll want to set this:

    objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);

Or you'll get an error that it can't find the property to set into.

Fastest way to convert string to integer in PHP

You can simply convert long string into integer by using FLOAT

$float = (float)$num;

Or if you want integer not floating val then go with

$float = (int)$num;

For ex.

(int)   "1212.3"   = 1212 
(float) "1212.3"   = 1212.3

How to do a join in linq to sql with method syntax?

Justin has correctly shown the expansion in the case where the join is just followed by a select. If you've got something else, it becomes more tricky due to transparent identifiers - the mechanism the C# compiler uses to propagate the scope of both halves of the join.

So to change Justin's example slightly:

var result = from sc in enumerableOfSomeClass
             join soc in enumerableOfSomeOtherClass
             on sc.Property1 equals soc.Property2
             where sc.X + sc.Y == 10
             select new { SomeClass = sc, SomeOtherClass = soc }

would be converted into something like this:

var result = enumerableOfSomeClass
    .Join(enumerableOfSomeOtherClass,
          sc => sc.Property1,
          soc => soc.Property2,
          (sc, soc) => new { sc, soc })
    .Where(z => z.sc.X + z.sc.Y == 10)
    .Select(z => new { SomeClass = z.sc, SomeOtherClass = z.soc });

The z here is the transparent identifier - but because it's transparent, you can't see it in the original query :)

Java Generics With a Class & an Interface - Together

You can't do it with "anonymous" type parameters (ie, wildcards that use ?), but you can do it with "named" type parameters. Simply declare the type parameter at method or class level.

import java.util.List;
interface A{}
interface B{}
public class Test<E extends B & A, T extends List<E>> {
    T t;
}

How to move from one fragment to another fragment on click of an ImageView in Android?

you can move to another fragment by using the FragmentManager transactions. Fragment can not be called like activities,. Fragments exists on the existance of activities.

You can call another fragment by writing the code below:

        FragmentTransaction t = this.getFragmentManager().beginTransaction();
        Fragment mFrag = new MyFragment();
        t.replace(R.id.content_frame, mFrag);
        t.commit();

here "R.id.content_frame" is the id of the layout on which you want to replace the fragment.

you can also add the other fragment incase of replace.

Dismissing a Presented View Controller

I like this one:

        (viewController.navigationController?.presentingViewController
            ?? viewController.presentingViewController
            ?? viewController).dismiss(animated: true)

Insert all data of a datagridview to database at once

Please see if below can help you

Class Post_Sales

Public Shared Sub Post_sales()

    Dim ITM_ID As Integer

    Dim SLS_QTY As Integer

    Dim SLS_PRC As Double

    Dim SLS_AMT As Double

    Dim DSPL_RCT As String

    Dim TAX_CODE As Integer


    'Format the current  date and send it to a textbox
    Form1.TextBox6.Text = System.DateTime.Now.ToString((" yyyy-MM-dd"))

    'Open Connection

    Dim con As New SqlConnection("Initial Catalog=Your Database here;Data source=.;Network Library=DBMSSOCN;User ID=sa;Password=")

    con.Open()

    'Insert Records into the database


    For Each rw As DataGridViewRow In Form1.DataGridView1.Rows

        ITM_ID = rw.Cells("Column1").Value
        DSPL_RCT = rw.Cells("Column2").Value
        SLS_QTY = rw.Cells("Column3").Value
        SLS_PRC = rw.Cells("Column4").Value
        SLS_AMT = rw.Cells("Column5").Value
        TAX_CODE = rw.Cells("Column6").Value

        Dim cmd As New SqlCommand("INSERT INTO DAY_PLUSALES (DT,ITM_ID,DSPL_RCT,SLS_QTY,SLS_PRC,SLS_AMT,TAX_CODE) values ('" & Form1.TextBox6.Text & "','" & ITM_ID & "','" & DSPL_RCT & "','" & SLS_QTY & "','" & SLS_PRC & "','" & SLS_AMT & "','" & TAX_CODE & "')", con)

        cmd.ExecuteNonQuery()

    Next

    con.Close()

    MessageBox.Show("Records Added to the SQL Database successfully!", "Records Updated ")

End Sub

End Class

Getting Google+ profile picture url with user_id

trying to access the /s2/profile/photo url works for most users but not all.

The only full proof method is to use the Google+ API. You don't need user authentication to request public profile data so it's a rather simple method:

  1. Get a Google+ API key on https://cloud.google.com/console

  2. Make a simple GET request to: https://www.googleapis.com/plus/v1/people/+< username >?key=

Note the + before the username. If you use user ids instead (the long string of digits), you don't need the +

  1. you will get a very comprehensive JSON representation of the profile data which includes: "image":{"url": "https://lh4.googleusercontent.com/..... the rest of the picture url...."}

How to insert a newline in front of a pattern?

echo one,two,three | sed 's/,/\
/g'

How do I check if there are duplicates in a flat list?

If the list contains unhashable items, you can use Alex Martelli's solution but with a list instead of a set, though it's slower for larger inputs: O(N^2).

def has_duplicates(iterable):
    seen = []
    for x in iterable:
        if x in seen:
            return True
        seen.append(x)
    return False

How can I check for an empty/undefined/null string in JavaScript?

Trimming whitespace with the null-coalescing operator:

if (!str?.trim()) {
  // do something...
}

explicit casting from super class to subclass

Elaborating the answer given by Michael Berry.

Dog d = (Dog)Animal; //Compiles but fails at runtime

Here you are saying to the compiler "Trust me. I know d is really referring to a Dog object" although it's not. Remember compiler is forced to trust us when we do a downcast.

The compiler only knows about the declared reference type. The JVM at runtime knows what the object really is.

So when the JVM at the runtime figures out that the Dog d is actually referring to an Animal and not a Dog object it says. Hey... you lied to the compiler and throws a big fat ClassCastException.

So if you are downcasting you should use instanceof test to avoid screwing up.

if (animal instanceof Dog) { Dog dog = (Dog) animal; }

Now a question comes to our mind. Why the hell compiler is allowing the downcast when eventually it is going to throw a java.lang.ClassCastException?

The answer is that all the compiler can do is verify that the two types are in the same inheritance tree, so depending on whatever code might have come before the downcast, it's possible that animal is of type dog.

The compiler must allow things that might possible work at runtime.

Consider the following code snipet:

public static void main(String[] args) 
{   
    Dog d = getMeAnAnimal();// ERROR: Type mismatch: cannot convert Animal to Dog
    Dog d = (Dog)getMeAnAnimal(); // Downcast works fine. No ClassCastException :)
    d.eat();

}

private static Animal getMeAnAnimal()
{
    Animal animal = new Dog();
    return animal;
}

However, if the compiler is sure that the cast would not possible work, compilation will fail. I.E. If you try to cast objects in different inheritance hierarchies

String s = (String)d; // ERROR : cannot cast for Dog to String

Unlike downcasting, upcasting works implicitly because when you upcast you are implicitly restricting the number of method you can invoke, as opposite to downcasting, which implies that later on, you might want to invoke a more specific method.

Dog d = new Dog(); Animal animal1 = d; // Works fine with no explicit cast Animal animal2 = (Animal) d; // Works fine with n explicit cast

Both of the above upcast will work fine without any exception because a Dog IS-A Animal, anithing an Animal can do, a dog can do. But it's not true vica-versa.

Round number to nearest integer

I use and may advise the following solution (python3.6):

y = int(x + (x % (1 if x >= 0 else -1)))

It works fine for half-numbers (positives and negatives) and works even faster than int(round(x)):

round_methods = [lambda x: int(round(x)), 
                 lambda x: int(x + (x % (1 if x >= 0 else -1))),
                 lambda x: np.rint(x).astype(int),
                 lambda x: int(proper_round(x))]

for rm in round_methods:
    %timeit rm(112.5)
Out:
201 ns ± 3.96 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
159 ns ± 0.646 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
925 ns ± 7.66 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
1.18 µs ± 8.66 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

for rm in round_methods:
    print(rm(112.4), rm(112.5), rm(112.6))
    print(rm(-12.4), rm(-12.5), rm(-12.6))
    print('=' * 11)

Out:
112 112 113
-12 -12 -13
===========
112 113 113
-12 -13 -13
===========
112 112 113
-12 -12 -13
===========
112 113 113
-12 -13 -13
===========

Does IMDB provide an API?

Recently at SXSWi 2012, in their "Mashery Lounge", there was a booth for an IMDB-like API called from rovi. It's not a free API, but according to the sales guy I talked to they offer either a rev share or a flat fee for usage, depending on your budget. I haven't used it yet but it seems pretty cool.

reading a line from ifstream into a string variable

Use the std::getline() from <string>.

 istream & getline(istream & is,std::string& str)

So, for your case it would be:

std::getline(read,x);

How to format a number as percentage in R?

I did some benchmarking for speed on these answers and was surprised to see percent in the scales package so touted, given its sluggishness. I imagine the advantage is its automatic detector for for proper formatting, but if you know what your data looks like it seems clear to be avoided.

Here are the results from trying to format a list of 100,000 percentages in (0,1) to a percentage in 2 digits:

library(microbenchmark)
x = runif(1e5)
microbenchmark(times = 100L, andrie1(), andrie2(), richie(), krlmlr())
# Unit: milliseconds
#   expr       min        lq      mean    median        uq       max
# 1 andrie1()  91.08811  95.51952  99.54368  97.39548 102.75665 126.54918 #paste(round())
# 2 andrie2()  43.75678  45.56284  49.20919  47.42042  51.23483  69.10444 #sprintf()
# 3  richie()  79.35606  82.30379  87.29905  84.47743  90.38425 112.22889 #paste(formatC())
# 4  krlmlr() 243.19699 267.74435 304.16202 280.28878 311.41978 534.55904 #scales::percent()

So sprintf emerges as a clear winner when we want to add a percent sign. On the other hand, if we only want to multiply the number and round (go from proportion to percent without "%", then round() is fastest:

# Unit: milliseconds
#        expr      min        lq      mean    median        uq       max
# 1 andrie1()  4.43576  4.514349  4.583014  4.547911  4.640199  4.939159 # round()
# 2 andrie2() 42.26545 42.462963 43.229595 42.960719 43.642912 47.344517 # sprintf()
# 3  richie() 64.99420 65.872592 67.480730 66.731730 67.950658 96.722691 # formatC()

Check if value exists in the array (AngularJS)

You could use indexOf function.

if(list.indexOf(createItem.artNr) !== -1) {
  $scope.message = 'artNr already exists!';
}

More about indexOf:

I need to learn Web Services in Java. What are the different types in it?

If your application often uses http protocol then REST is best because of its light weight, and knowing that your application uses only http protocol choosing SOAP is not so good because it heavy,Better to make decision on web service selection based on the protocols we use in our applications.

mysql datatype for telephone number and address

Actually you can use a varchar for a telephone number. You do not need an int because you are not going to perform arithmetic on the numbers.

how can I debug a jar at runtime?

Even though it is a runnable jar, you can still run it from a console -- open a terminal window, navigate to the directory containing the jar, and enter "java -jar yourJar.jar". It will run in that terminal window, and sysout and syserr output will appear there, including stack traces from uncaught exceptions. Be sure to have your debug set to true when you compile. And good luck.


Just thought of something else -- if you're on Win7, it often has permission problems with user applications writing files to specific directories. Make sure the directory to which you are writing your output file is one for which you have permissions.

In a future project, if it's big enough, you can use one of the standard logging facilities for 'debug' output; then it will be easy(ier) to redirect it to a file instead of depending on having a console. But for a smaller job like this, this should be fine.

QtCreator: No valid kits found

Found the issue. Qt Creator wants you to use a compiler listed under one of their Qt libraries. Use the Maintenance Tool to install this.

To do so:

Go to Tools -> Options.... Select Build & Run on left. Open Kits tab. You should have Manual -> Desktop (default) line in list. Choose it. Now select something like Qt 5.5.1 in PATH (qt5) in Qt version combobox and click Apply button. From now you should be able to create, build and run empty Qt project.

How to Alter Constraint

No. We cannot alter the constraint, only thing we can do is drop and recreate it

ALTER TABLE [TABLENAME] DROP CONSTRAINT [CONSTRAINTNAME]

Foreign Key Constraint

Alter Table Table1 Add Constraint [CONSTRAINTNAME] Foreign Key (Column) References Table2 (Column) On Update Cascade On Delete Cascade

Primary Key constraint

Alter Table Table add constraint [Primary Key] Primary key(Column1,Column2,.....)

Convert from ASCII string encoded in Hex to plain ASCII?

A slightly simpler solution:

>>> "7061756c".decode("hex")
'paul'

How do you check current view controller class in Swift?

if let index = self.navigationController?.viewControllers.index(where: { $0 is MyViewController }) {
            let vc = self.navigationController?.viewControllers[vcIndex] as! MyViewController
            self.navigationController?.popToViewController(vc, animated: true)
        } else {
            self.navigationController?.popToRootViewController(animated: true)
        }

TypeError: 'module' object is not callable

Here is another gotcha, that took me awhile to see even after reading these posts. I was setting up a script to call my python bin scripts. I was getting the module not callable too.

My zig was that I was doing the following:

from mypackage.bin import myscript
...
myscript(...)

when my zag needed to do the following:

from mypackage.bin.myscript import myscript
...
myscript(...)

In summary, double check your package and module nesting.

What I am trying to do is have a scripts directory that does not have the *.py extension, and still have the 'bin' modules to be in mypackage/bin and these have my *.py extension. I am new to packaging, and trying to follow the standards as I am interpreting them. So, I have at the setup root:

setup.py
scripts/
      script1
mypackage/
   bin/
      script1.py
   subpackage1/
   subpackage_etc/

If this is not compliant with standard, please let me know.

What is the purpose of .PHONY in a Makefile?

The special target .PHONY: allows to declare phony targets, so that make will not check them as actual file names: it will work all the time even if such files still exist.

You can put several .PHONY: in your Makefile :

.PHONY: all

all : prog1 prog2

...

.PHONY: clean distclean

clean :
    ...
distclean :
    ...

There is another way to declare phony targets : simply put :: without prerequisites :

all :: prog1 prog2

...

clean ::
    ...
distclean ::
    ...

The :: has other special meanings, see here, but without prerequisites it always execute the recipes, even if the target already exists, thus acting as a phony target.

How do I reverse a C++ vector?

All containers offer a reversed view of their content with rbegin() and rend(). These two functions return so-calles reverse iterators, which can be used like normal ones, but it will look like the container is actually reversed.

#include <vector>
#include <iostream>

template<class InIt>
void print_range(InIt first, InIt last, char const* delim = "\n"){
  --last;
  for(; first != last; ++first){
    std::cout << *first << delim;
  }
  std::cout << *first;
}

int main(){
  int a[] = { 1, 2, 3, 4, 5 };
  std::vector<int> v(a, a+5);
  print_range(v.begin(), v.end(), "->");
  std::cout << "\n=============\n";
  print_range(v.rbegin(), v.rend(), "<-");
}

Live example on Ideone. Output:

1->2->3->4->5
=============
5<-4<-3<-2<-1

Obtain form input fields using jQuery?

serialize() is the best method. @ Christopher Parker say that Nickf's anwser accomplishes more, however it does not take into account that the form may contain textarea and select menus. It is far better to use serialize() and then manipulate that as you need to. Data from serialize() can be used in either an Ajax post or get, so there is no issue there.

How do I use brew installed Python as the default Python?

No idea what you mean with default Python. I consider it bad practice to replace the system Python interpreter with a different version. System functionality may depend in some way on the system Python and specific modules or a specific Python version. Instead install your custom Python installations in a safe different place and adjust your $PATH as needed in order to call you Python through a path lookup instead of looking for the default Python.

How to check a string starts with numeric number?

I think you ought to use a regex:


import java.util.regex.*;

public class Test {
  public static void main(String[] args) {
    String neg = "-123abc";
    String pos = "123abc";
    String non = "abc123";
        /* I'm not sure if this regex is too verbose, but it should be
         * clear. It checks that the string starts with either a series
         * of one or more digits... OR a negative sign followed by 1 or
         * more digits. Anything can follow the digits. Update as you need
         * for things that should not follow the digits or for floating
         * point numbers.
         */
    Pattern pattern = Pattern.compile("^(\\d+.*|-\\d+.*)");
    Matcher matcher = pattern.matcher(neg);
    if(matcher.matches()) {
        System.out.println("matches negative number");
    }
    matcher = pattern.matcher(pos);
    if (matcher.matches()) {
        System.out.println("positive matches");
    }
    matcher = pattern.matcher(non);
    if (!matcher.matches()) {
        System.out.println("letters don't match :-)!!!");
    }
  }
}

You may want to adjust this to accept floating point numbers, but this will work for negatives. Other answers won't work for negatives because they only check the first character! Be more specific about your needs and I can help you adjust this approach.

How to get exit code when using Python subprocess communicate method?

Use process.wait() after you call process.communicate().
For example:

import subprocess

process = subprocess.Popen(['ipconfig', '/all'], stderr=subprocess.PIPE, stdout=subprocess.PIPE)
stdout, stderr = process.communicate()
exit_code = process.wait()
print(stdout, stderr, exit_code)

Converting Float to Dollars and Cents

df_buy['BUY'] = df_buy['BUY'].astype('float')
df_buy['BUY'] = ['€ {:,.2f}'.format(i) for i in list(df_buy['BUY'])]

How can I use Python to get the system hostname?

os.getenv('HOSTNAME') and os.environ['HOSTNAME'] don't always work. In cron jobs and WSDL, HTTP HOSTNAME isn't set. Use this instead:

import socket
socket.gethostbyaddr(socket.gethostname())[0]

It always (even on Windows) returns a fully qualified host name, even if you defined a short alias in /etc/hosts.

If you defined an alias in /etc/hosts then socket.gethostname() will return the alias. platform.uname()[1] does the same thing.

I ran into a case where the above didn't work. This is what I'm using now:

import socket
if socket.gethostname().find('.')>=0:
    name=socket.gethostname()
else:
    name=socket.gethostbyaddr(socket.gethostname())[0]

It first calls gethostname to see if it returns something that looks like a host name, if not it uses my original solution.

React-router: How to manually invoke Link?

React Router 4 includes a withRouter HOC that gives you access to the history object via this.props:

import React, {Component} from 'react'
import {withRouter} from 'react-router-dom'

class Foo extends Component {
  constructor(props) {
    super(props)

    this.goHome = this.goHome.bind(this)
  }

  goHome() {
    this.props.history.push('/')
  }

  render() {
    <div className="foo">
      <button onClick={this.goHome} />
    </div>
  }
}

export default withRouter(Foo)

Permutations between two lists of unequal length

Answering the question "given two lists, find all possible permutations of pairs of one item from each list" and using basic Python functionality (i.e., without itertools) and, hence, making it easy to replicate for other programming languages:

def rec(a, b, ll, size):
    ret = []
    for i,e in enumerate(a):
        for j,f in enumerate(b):
            l = [e+f]
            new_l = rec(a[i+1:], b[:j]+b[j+1:], ll, size)
            if not new_l:
                ret.append(l)
            for k in new_l:
                l_k = l + k
                ret.append(l_k)
                if len(l_k) == size:
                    ll.append(l_k)
    return ret

a = ['a','b','c']
b = ['1','2']
ll = []
rec(a,b,ll, min(len(a),len(b)))
print(ll)

Returns

[['a1', 'b2'], ['a1', 'c2'], ['a2', 'b1'], ['a2', 'c1'], ['b1', 'c2'], ['b2', 'c1']]

How to kill an Android activity when leaving it so that it cannot be accessed from the back button?

You just need to call finish()

Intent intent = new Intent(this, NextActivity.class);
startActivity(intent);
finish();

Git push error: "origin does not appear to be a git repository"

I had this problem cause i had already origin remote defined locally. So just change "origin" into another name:

git remote add originNew https://github.com/UAwebM...

git push -u originNew

or u can remove your local origin. to check your remote name type:

git remote

to remove remote - log in your clone repository and type:

git remote remove origin(depending on your remote's name)

How can I beautify JSON programmatically?

Here's something that might be interesting for developers hacking (minified or obfuscated) JavaScript more frequently.

You can build your own CLI JavaScript beautifier in under 5 mins and have it handy on the command-line. You'll need Mozilla Rhino, JavaScript file of some of the JS beautifiers available online, small hack and a script file to wrap it all up.

I wrote an article explaining the procedure: Command-line JavaScript beautifier implemented in JavaScript.

Get the _id of inserted document in Mongo database in NodeJS

You could use async functions to get _id field automatically without manipulating data object:

async function save() {
  const data = {
    name: "John"
  }

  await db.collection('users').insertOne(data)

  return data
}

Returns data:

{
  _id: '5dbff150b407cc129ab571ca',
  name: 'John'
}

Official way to ask jQuery wait for all images to load before executing something

Use imagesLoaded PACKAGED v3.1.8 (6.8 Kb when minimized). It is relatively old (since 2010) but still active project.

You can find it on github: https://github.com/desandro/imagesloaded

Their official site: http://imagesloaded.desandro.com/

Why it is better than using:

$(window).load() 

Because you may want to load images dynamically, like this: jsfiddle

$('#button').click(function(){
    $('#image').attr('src', '...');
});

How to get a resource id with a known resource name?

I would suggest you using my method to get a resource ID. It's Much more efficient, than using getIdentidier() method, which is slow.

Here's the code:

/**
 * @author Lonkly
 * @param variableName - name of drawable, e.g R.drawable.<b>image</b>
 * @param ? - class of resource, e.g R.drawable.class or R.raw.class
 * @return integer id of resource
 */
public static int getResId(String variableName, Class<?> ?) {

    Field field = null;
    int resId = 0;
    try {
        field = ?.getField(variableName);
        try {
            resId = field.getInt(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return resId;

}