Programs & Examples On #Timeline

Time-based information displays and user interfaces. For the Facebook Timeline use [facebook-timeline] instead.

How do I create a timeline chart which shows multiple events? Eg. Metallica Band members timeline on wiki

A Stacked bar chart should suffice:

Setup data as follows

Name    Start       End         Duration (End - Start)
Fred    1/01/1981   1/06/1985    1612   
Bill    1/07/1985   1/11/2000    5602  
Joe     1/01/1980   1/12/2001    8005  
Jim     1/03/1999   1/01/2000    306  
  1. Plot Start and Duration as a stacked bar chart
  2. Set the X-Axis minimum to the desired start date
  3. Set the Fill Colour of thestart range to no fill
  4. Set the Fill of individual bars to suit

(example prepared in Excel 2010)

enter image description here

How to view file history in Git?

Many Git history browsers, including git log (and 'git log --graph'), gitk (in Tcl/Tk, part of Git), QGit (in Qt), tig (text mode interface to git, using ncurses), Giggle (in GTK+), TortoiseGit and git-cheetah support path limiting (e.g. gitk path/to/file).

Responsive timeline UI with Bootstrap3

"Timeline (responsive)" snippet:

This looks very, very close to what your example shows. The bootstrap snippet linked below covers all the bases you are looking for. I've been considering it myself, with the same requirements you have ( especially responsiveness ). This morphs well between screen sizes and devices.

You can fork this and use it as a great starting point for your specific expectations:


Here are two screenshots I took for you... wide and thin:

wide thin

How to create a timeline with LaTeX?

There is timeline.sty floating around.

The syntax is simpler than using tikz:

%%% In LaTeX:
%%% \begin{timeline}{length}(start,stop)
%%%   .
%%%   .
%%%   .
%%% \end{timeline}
%%%
%%% in plain TeX
%%% \timeline{length}(start,stop)
%%%   .
%%%   .
%%%   .
%%% \endtimeline
%%% in between the two, we may have:
%%% \item{date}{description}
%%% \item[sortkey]{date}{description}
%%% \optrule
%%%
%%% the options to timeline are:
%%%      length The amount of vertical space that the timeline should
%%%                use.
%%%      (start,stop) indicate the range of the timeline. All dates or
%%%                sortkeys should lie in the range [start,stop]
%%%
%%% \item without the sort key expects date to be a number (such as a
%%%      year).
%%% \item with the sort key expects the sort key to be a number; date
%%%      can be anything. This can be used for log scale time lines
%%%      or dates that include months or days.
%%% putting \optrule inside of the timeline environment will cause a
%%%      vertical rule to be drawn down the center of the timeline.

I've used python's datetime.data.toordinal to convert dates to 'sort keys' in the context of the package.

Make javascript alert Yes/No Instead of Ok/Cancel

"Confirm" in Javascript stops the whole process until it gets a mouse response on its buttons. If that is what you are looking for, you can refer jquery-ui but if you have nothing running behind your process while receiving the response and you control the flow programatically, take a look at this. You will have to hard-code everything by yourself but you have complete command over customization. https://www.w3schools.com/howto/howto_css_modals.asp

iOS Remote Debugging

I recommend Vorlon, works like weinre. I like the UI of Vorlon, and it support SSL, my application is in HTTPS, I tried weinre with ngrok, ghostlab and vorlon, only vorlon works fine.

How to deploy a React App on Apache web server

Before making the npm build,
1) Go to your React project root folder and open package.json.
2) Add "homepage" attribute to package.json

  • if you want to provide absolute path

    "homepage": "http://hostName.com/appLocation",
    "name": "react-app",
    "version": "1.1.0",
    
  • if you want to provide relative path

    "homepage": "./",
    "name": "react-app",
    

    Using relative path method may warn a syntax validation error in your IDE. But the build is made without any errors during compilation.

3) Save the package.json , and in terminal run npm run-script build
4) Copy the contents of build/ folder to your server directory.

PS: It is easy to use relative path method if you want to change the build file location in your server frequently.

What is the JUnit XML format specification that Hudson supports?

I've decided to post a new answer, because some existing answers are outdated or incomplete.

First of all: there is nothing like JUnit XML Format Specification, simply because JUnit doesn't produce any kind of XML or HTML report.

The XML report generation itself comes from the Ant JUnit task/ Maven Surefire Plugin/ Gradle (whichever you use for running your tests). The XML report format was first introduced by Ant and later adapted by Maven (and Gradle).

If somebody just needs an official XML format then:

  1. There exists a schema for a maven surefire-generated XML report and it can be found here: surefire-test-report.xsd.
  2. For an ant-generated XML there is a 3rd party schema available here (but it might be slightly outdated).

Hope it will help somebody.

Selecting an element in iFrame jQuery

var iframe = $('iframe'); // or some other selector to get the iframe
$('[tokenid=' + token + ']', iframe.contents()).addClass('border');

Also note that if the src of this iframe is pointing to a different domain, due to security reasons, you will not be able to access the contents of this iframe in javascript.

Taking multiple inputs from user in python

You could use the below to take multiple inputs separated by a keyword

a,b,c=raw_input("Please enter the age of 3 people in one line using commas\n").split(',')

Print page numbers on pages when printing html

This is what you want:

@page {
   @bottom-right {
    content: counter(page) " of " counter(pages);
   }
}

"Unable to find remote helper for 'https'" during git clone

If you are trying to clone then you could use the git transport

For example: git clone git://github.com/fog/fog.git

Vaio ~/Myworks/Hero $ git clone git://github.com/fog/fog.git

Initialized empty Git repository in /home/nthillaiarasu/Myworks/Hero/fog/.git/
remote: Counting objects: 41138, done.
remote: Compressing objects: 100% (13176/13176), done.
remote: Total 41138 (delta 27218), reused 40493 (delta 26708)
Receiving objects: 100% (41138/41138), 5.22 MiB | 58 KiB/s, done.
Resolving deltas: 100% (27218/27218), done

How can you tell when a layout has been drawn?

A really easy way is to simply call post() on your layout. This will run your code the next step, after your view has already been created.

YOUR_LAYOUT.post( new Runnable() {
    @Override
    public void run() {
        int width  = YOUR_LAYOUT.getMeasuredWidth();
        int height = YOUR_LAYOUT.getMeasuredHeight(); 
    }
});

Do AJAX requests retain PHP Session info?

One thing to watch out for though, particularly if you are using a framework, is to check if the application is regenerating session ids between requests - anything that depends explicitly on the session id will run into problems, although obviously the rest of the data in the session will unaffected.

If the application is regenerating session ids like this then you can end up with a situation where an ajax request in effect invalidates / replaces the session id in the requesting page.

Can I set the cookies to be used by a WKWebView?

This mistake i was doing is i was passing the whole url in domain attribute, it should be only domain name.

let cookie = HTTPCookie(properties: [
.domain: "example.com",
.path: "/",
.name: "MyCookieName",
.value: "MyCookieValue",
.secure: "TRUE",
])! 

webView.configuration.websiteDataStore.httpCookieStore.setCookie(cookie)

How to customize the configuration file of the official PostgreSQL Docker image?

The postgres:9.4 image you've inherited from declares a volume at /var/lib/postgresql/data. This essentially means you can't copy any files to that path in your image; the changes will be discarded.

You have a few choices:

  • You could just add your own configuration files as a volume at run-time with docker run -v postgresql.conf:/var/lib/postgresql/data/postgresql.conf .... However, I'm not sure exactly how that will interact with the existing volume.

  • You could copy the file over when the container is started. To do that, copy your file into the build at a location which isn't underneath the volume then call a script from the entrypoint or cmd which will copy the file to correct location and start postgres.

  • Clone the project behind the Postgres official image and edit the Dockerfile to add your own config file in before the VOLUME is declared (anything added before the VOLUME instruction is automatically copied in at run-time).

  • Pass all config changes in command option in docker-compose file

like:

services:
  postgres:
    ...  
    command:
      - "postgres"
      - "-c"
      - "max_connections=1000"
      - "-c"
      - "shared_buffers=3GB"
      - "-c"
      ...

How to reset a form using jQuery with .reset() method

http://jsfiddle.net/8zLLn/

  $('#configreset').click(function(){
        $('#configform')[0].reset();
  });

Put it in JS fiddle. Worked as intended.

So, none of the aforementioned issues are at fault here. Maybe you're having a conflicting ID issue? Is the click actually executing?

Edit: (because I'm a sad sack without proper commenting ability) It's not an issue directly with your code. It works fine when you take it out of the context of the page that you're currently using, so, instead of it being something with the particular jQuery/javascript & attributed form data, it has to be something else. I'd start bisecting the code around it out and try to find where it's going on. I mean, just to 'make sure', i suppose you could...

console.log($('#configform')[0]);

in the click function and make sure it's targeting the right form...

and if it is, it has to be something that's not listed here.

edit part 2: One thing you could try (if it's not targeting it correctly) is use "input:reset" instead of what you are using... also, i'd suggest because it's not the target that's incorrectly working to find out what the actual click is targeting. Just open up firebug/developer tools, whathave you, toss in

console.log($('#configreset'))

and see what pops up. and then we can go from there.

JavaScript private methods

I think such questions come up again and again because of the lack of understanding of the closures. ?losures is most important thing in JS. Every JS programmer have to feel the essence of it.

1. First of all we need to make separate scope (closure).

function () {

}

2. In this area, we can do whatever we want. And no one will know about it.

function () {
    var name,
        secretSkills = {
            pizza: function () { return new Pizza() },
            sushi: function () { return new Sushi() }
        }

    function Restaurant(_name) {
        name = _name
    }
    Restaurant.prototype.getFood = function (name) {
        return name in secretSkills ? secretSkills[name]() : null
    }
}

3. For the world to know about our restaurant class, we have to return it from the closure.

var Restaurant = (function () {
    // Restaurant definition
    return Restaurant
})()

4. At the end, we have:

var Restaurant = (function () {
    var name,
        secretSkills = {
            pizza: function () { return new Pizza() },
            sushi: function () { return new Sushi() }
        }

    function Restaurant(_name) {
        name = _name
    }
    Restaurant.prototype.getFood = function (name) {
        return name in secretSkills ? secretSkills[name]() : null
    }
    return Restaurant
})()

5. Also, this approach has potential for inheritance and templating

// Abstract class
function AbstractRestaurant(skills) {
    var name
    function Restaurant(_name) {
        name = _name
    }
    Restaurant.prototype.getFood = function (name) {
        return skills && name in skills ? skills[name]() : null
    }
    return Restaurant
}

// Concrete classes
SushiRestaurant = AbstractRestaurant({ 
    sushi: function() { return new Sushi() } 
})

PizzaRestaurant = AbstractRestaurant({ 
    pizza: function() { return new Pizza() } 
})

var r1 = new SushiRestaurant('Yo! Sushi'),
    r2 = new PizzaRestaurant('Dominos Pizza')

r1.getFood('sushi')
r2.getFood('pizza')

I hope this helps someone better understand this subject

Object of class DateTime could not be converted to string

$Date = $row['Received_date']->format('d/m/Y');

then it cast date object from given in database

How to display an image from a path in asp.net MVC 4 and Razor view?

Try this ,

<img src= "@Url.Content(Model.ImagePath)" alt="Sample Image" style="height:50px;width:100px;"/>

(or)

<img src="~/Content/img/@Url.Content(model =>model.ImagePath)" style="height:50px;width:100px;"/>

Bulk insert with SQLAlchemy ORM

The best answer I found so far was in sqlalchemy documentation:

http://docs.sqlalchemy.org/en/latest/faq/performance.html#i-m-inserting-400-000-rows-with-the-orm-and-it-s-really-slow

There is a complete example of a benchmark of possible solutions.

As shown in the documentation:

bulk_save_objects is not the best solution but it performance are correct.

The second best implementation in terms of readability I think was with the SQLAlchemy Core:

def test_sqlalchemy_core(n=100000):
    init_sqlalchemy()
    t0 = time.time()
    engine.execute(
        Customer.__table__.insert(),
            [{"name": 'NAME ' + str(i)} for i in xrange(n)]
    )

The context of this function is given in the documentation article.

Replace substring with another substring C++

Here is a solution using recursion that replaces all occurrences of a substring with another substring. This works no matter the size of the strings.

std::string ReplaceString(const std::string source_string, const std::string old_substring, const std::string new_substring)
{
    // Can't replace nothing.
    if (old_substring.empty())
        return source_string;

    // Find the first occurrence of the substring we want to replace.
    size_t substring_position = source_string.find(old_substring);

    // If not found, there is nothing to replace.
    if (substring_position == std::string::npos)
        return source_string;

    // Return the part of the source string until the first occurance of the old substring + the new replacement substring + the result of the same function on the remainder.
    return source_string.substr(0,substring_position) + new_substring + ReplaceString(source_string.substr(substring_position + old_substring.length(),source_string.length() - (substring_position + old_substring.length())), old_substring, new_substring);
}

Usage example:

std::string my_cpp_string = "This string is unmodified. You heard me right, it's unmodified.";
std::cout << "The original C++ string is:\n" << my_cpp_string << std::endl;
my_cpp_string = ReplaceString(my_cpp_string, "unmodified", "modified");
std::cout << "The final C++ string is:\n" << my_cpp_string << std::endl;

How to call getClass() from a static method in Java?

Suppose there is a Utility class, then sample code would be -

    URL url = Utility.class.getClassLoader().getResource("customLocation/".concat("abc.txt"));

CustomLocation - if any folder structure within resources otherwise remove this string literal.

How to plot all the columns of a data frame in R

The ggplot2 package takes a little bit of learning, but the results look really nice, you get nice legends, plus many other nice features, all without having to write much code.

require(ggplot2)
require(reshape2)
df <- data.frame(time = 1:10,
                 a = cumsum(rnorm(10)),
                 b = cumsum(rnorm(10)),
                 c = cumsum(rnorm(10)))
df <- melt(df ,  id.vars = 'time', variable.name = 'series')

# plot on same grid, each series colored differently -- 
# good if the series have same scale
ggplot(df, aes(time,value)) + geom_line(aes(colour = series))

# or plot on different plots
ggplot(df, aes(time,value)) + geom_line() + facet_grid(series ~ .)

enter image description here enter image description here

What is the correct way to represent null XML elements?

It depends on how you validate your XML. If you use XML Schema validation, the correct way of representing null values is with the xsi:nil attribute.

[Source]

Executing a shell script from a PHP script

Without really knowing the complexity of the setup, I like the sudo route. First, you must configure sudo to permit your webserver to sudo run the given command as root. Then, you need to have the script that the webserver shell_exec's(testscript) run the command with sudo.

For A Debian box with Apache and sudo:

  1. Configure sudo:

    • As root, run the following to edit a new/dedicated configuration file for sudo:

      visudo -f /etc/sudoers.d/Webserver
      

      (or whatever you want to call your file in /etc/sudoers.d/)

    • Add the following to the file:

      www-data ALL = (root) NOPASSWD: <executable_file_path>
      

      where <executable_file_path> is the command that you need to be able to run as root with the full path in its name(say /bin/chown for the chown executable). If the executable will be run with the same arguments every time, you can add its arguments right after the executable file's name to further restrict its use.

      For example, say we always want to copy the same file in the /root/ directory, we would write the following:

      www-data ALL = (root) NOPASSWD: /bin/cp /root/test1 /root/test2
      
  2. Modify the script(testscript):

    Edit your script such that sudo appears before the command that requires root privileges(say sudo /bin/chown ... or sudo /bin/cp /root/test1 /root/test2). Make sure that the arguments specified in the sudo configuration file exactly match the arguments used with the executable in this file. So, for our example above, we would have the following in the script:

    sudo /bin/cp /root/test1 /root/test2
    

If you are still getting permission denied, the script file and it's parent directories' permissions may not allow the webserver to execute the script itself. Thus, you need to move the script to a more appropriate directory and/or change the script and parent directory's permissions to allow execution by www-data(user or group), which is beyond the scope of this tutorial.

Keep in mind:

When configuring sudo, the objective is to permit the command in it's most restricted form. For example, instead of permitting the general use of the cp command, you only allow the cp command if the arguments are, say, /root/test1 /root/test2. This means that cp's arguments(and cp's functionality cannot be altered).

VirtualBox: mount.vboxsf: mounting failed with the error: No such device

My shared folder/clipboard stopped to work for some reason (probably due to a patch installation on my virtual machine).

sudo mount -t vboxsf Shared_Folder ~/SF/

Gave following result:

VirtualBox: mount.vboxsf: mounting failed with the error: No such device

The solution for me was to stop vboxadd and do a setup after that:

cd /opt/VBoxGuestAdditions-*/init  
sudo ./vboxadd setup

Understanding colors on Android (six characters)

If you provide 6 hex digits, that means RGB (2 hex digits for each value of red, green and blue).

If you provide 8 hex digits, it's an ARGB (2 hex digits for each value of alpha, red, green and blue respectively).

So by removing the final 55 you're changing from A=B4, R=55, G=55, B=55 (a mostly transparent grey), to R=B4, G=55, B=55 (a fully-non-transparent dusky pinky).

See the "Color" documentation for the supported formats.

Open Source Alternatives to Reflector?

I am currently working on an open-source disassembler / decompiler called Assembly Analyzer. It generates source code for methods, displays assembly metadata and resources, and allows you to walk through dependencies.

The project is hosted on CodePlex => http://asmanalyzer.codeplex.com/

Converting file size in bytes to human-readable string

Based on cocco's idea, here's a less compact -but hopefully more comprehensive- example.

<!DOCTYPE html>
<html>
<head>
<title>File info</title>

<script>
<!--
function fileSize(bytes) {
    var exp = Math.log(bytes) / Math.log(1024) | 0;
    var result = (bytes / Math.pow(1024, exp)).toFixed(2);

    return result + ' ' + (exp == 0 ? 'bytes': 'KMGTPEZY'[exp - 1] + 'B');
}

function info(input) {
    input.nextElementSibling.textContent = fileSize(input.files[0].size);
} 
-->
</script>
</head>

<body>
<label for="upload-file"> File: </label>
<input id="upload-file" type="file" onchange="info(this)">
<div></div>
</body>
</html> 

document.getElementByID is not a function

It's document.getElementById() and not document.getElementByID(). Check the casing for Id.

How do I add a tool tip to a span element?

In most browsers, the title attribute will render as a tooltip, and is generally flexible as to what sorts of elements it'll work with.

<span title="This will show as a tooltip">Mouse over for a tooltip!</span>
<a href="http://www.stackoverflow.com" title="Link to stackoverflow.com">stackoverflow.com</a>
<img src="something.png" alt="Something" title="Something">

All of those will render tooltips in most every browser.

How should I resolve java.lang.IllegalArgumentException: protocol = https host = null Exception?

Might help some else - I came here because I missed putting two // after http:. This is what I had:

http:/abc.my.domain.com:55555/update

printf a variable in C

As Shafik already wrote you need to use the right format because scanf gets you a char. Don't hesitate to look here if u aren't sure about the usage: http://www.cplusplus.com/reference/cstdio/printf/

Hint: It's faster/nicer to write x=x+1; the shorter way: x++;

Sorry for answering what's answered just wanted to give him the link - the site was really useful to me all the time dealing with C.

Random string generation with upper case letters and digits

you can now use a new library (python >= 3.6) chancepy here

from chancepy import Chance

random_string = Chance.string(length=10, pool="someLettersAndNumbers123")

Merge unequal dataframes and replace missing rows with 0

"all" option does not work anymore, The new parameter is;

x = pd.merge(df1, df2, how="outer")

Javascript add method to object

This all depends on how you're creating Foo, and how you intend to use .bar().

First, are you using a constructor-function for your object?

var myFoo = new Foo();

If so, then you can extend the Foo function's prototype property with .bar, like so:

function Foo () { /*...*/ }
Foo.prototype.bar = function () { /*...*/ };

var myFoo = new Foo();
myFoo.bar();

In this fashion, each instance of Foo now has access to the SAME instance of .bar.
To wit: .bar will have FULL access to this, but will have absolutely no access to variables within the constructor function:

function Foo () { var secret = 38; this.name = "Bob"; }
Foo.prototype.bar = function () { console.log(secret); };
Foo.prototype.otherFunc = function () { console.log(this.name); };

var myFoo = new Foo();
myFoo.otherFunc(); // "Bob";
myFoo.bar(); // error -- `secret` is undefined...
             // ...or a value of `secret` in a higher/global scope

In another way, you could define a function to return any object (not this), with .bar created as a property of that object:

function giveMeObj () {
    var private = 42,
        privateBar = function () { console.log(private); },
        public_interface = {
            bar : privateBar
        };

    return public_interface;
}

var myObj = giveMeObj();
myObj.bar(); // 42

In this fashion, you have a function which creates new objects.
Each of those objects has a .bar function created for them.
Each .bar function has access, through what is called closure, to the "private" variables within the function that returned their particular object.
Each .bar still has access to this as well, as this, when you call the function like myObj.bar(); will always refer to myObj (public_interface, in my example Foo).

The downside to this format is that if you are going to create millions of these objects, that's also millions of copies of .bar, which will eat into memory.

You could also do this inside of a constructor function, setting this.bar = function () {}; inside of the constructor -- again, upside would be closure-access to private variables in the constructor and downside would be increased memory requirements.

So the first question is:
Do you expect your methods to have access to read/modify "private" data, which can't be accessed through the object itself (through this or myObj.X)?

and the second question is: Are you making enough of these objects so that memory is going to be a big concern, if you give them each their own personal function, instead of giving them one to share?

For example, if you gave every triangle and every texture their own .draw function in a high-end 3D game, that might be overkill, and it would likely affect framerate in such a delicate system...

If, however, you're looking to create 5 scrollbars per page, and you want each one to be able to set its position and keep track of if it's being dragged, without letting every other application have access to read/set those same things, then there's really no reason to be scared that 5 extra functions are going to kill your app, assuming that it might already be 10,000 lines long (or more).

IIS7 URL Redirection from root to sub directory

You need to download this from Microsoft: http://www.microsoft.com/en-us/download/details.aspx?id=7435.

The tool is called "Microsoft URL Rewrite Module 2.0 for IIS 7" and is described as follows by Microsoft: "URL Rewrite Module 2.0 provides a rule-based rewriting mechanism for changing requested URL’s before they get processed by web server and for modifying response content before it gets served to HTTP clients"

How to check for registry value using VbScript

Set objShell = WScript.CreateObject("WScript.Shell") 
skey = "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{9A25302D-30C0-39D9-BD6F-21E6EC160475}\"
with CreateObject("WScript.Shell")
    on error resume next            ' turn off error trapping
    sValue = .regread(sKey)       ' read attempt
    bFound = (err.number = 0)     ' test for success
end with
if bFound then
    msgbox "exists"
else
  msgbox "not exists" 
End If

How to change the sender's name or e-mail address in mutt?

For a one time change you can do this:

export EMAIL='[email protected]'; mutt -s "Elvis is dead" [email protected]

What is The difference between ListBox and ListView

Listview derives from listbox control. One most important difference is listview uses the extended selection mode by default . listview also adds a property called view which enables you to customize the view in a richer way than a custom itemspanel. One real life example of listview with gridview is file explorer's details view. Listview with grid view is a less powerful data grid. After the introduction of datagrid control listview lost its importance.

What svn command would list all the files modified on a branch?

svn log -q -v shows paths and hides comments. All the paths are indented so you can search for lines starting with whitespace. Then pipe to cut and sort to tidy up:

svn log --stop-on-copy -q -v | grep '^[[:space:]]'| cut -c6- | sort -u

This gets all the paths mentioned on the branch since its branch point. Note it will list deleted and added, as well as modified files. I just used this to get the stuff I should worry about reviewing on a slightly messy branch from a new dev.

Showing loading animation in center of page while making a call to Action method in ASP .NET MVC

Another solution that it is similar to those already exposed here is this one. Just before the closing body tag place this html:

<div id="resultLoading" style="display: none; width: 100%; height: 100%; position: fixed; z-index: 10000; top: 0px; left: 0px; right: 0px; bottom: 0px; margin: auto;">
    <div style="width: 340px; height: 200px; text-align: center; position: fixed; top: 0px; left: 0px; right: 0px; bottom: 0px; margin: auto; z-index: 10; color: rgb(255, 255, 255);">
        <div class="uil-default-css">
            <img src="/images/loading-animation1.gif" style="max-width: 150px; max-height: 150px; display: block; margin-left: auto; margin-right: auto;" />
        </div>
        <div class="loader-text" style="display: block; font-size: 18px; font-weight: 300;">&nbsp;</div>
    </div>
    <div style="background: rgb(0, 0, 0); opacity: 0.6; width: 100%; height: 100%; position: absolute; top: 0px;"></div>
</div>

Finally, replace .loader-text element's content on the fly on every navigation event and turn on the #resultloading div, note that it is initially hidden.

var showLoader = function (text) {
    $('#resultLoading').show();
    $('#resultLoading').find('.loader-text').html(text);
};

jQuery(document).ready(function () {
    jQuery(window).on("beforeunload ", function () {
        showLoader('Loading, please wait...');
    });
});

This can be applied to any html based project with jQuery where you don't know which pages of your administration area will take too long to finish loading.

The gif image is 176x176px but you can use any transparent gif animation, please take into account that the image size is not important as it will be maxed to 150x150px.

Also, the function showLoader can be called on an element's click to perform an action that will further redirect the page, that is why it is provided ad an individual function. i hope this can also help anyone.

PANIC: Cannot find AVD system path. Please define ANDROID_SDK_ROOT (in windows 10)

Try to use the argument: -sysdir <Your_SDK_DIR> and then check whether the error message displayed.

See also: https://android.googlesource.com/platform/external/qemu/+/1a15692cded92d66dea1a51389a3c4b9e3b3631a/android/emulator/main-emulator.cpp

Check out these clip you will find out the reason:

// Sanity checks.
if (avdName) {
    if (!isCpuArchSupportedByRanchu(avdArch)) {
        APANIC("CPU Architecture '%s' is not supported by the QEMU2 emulator, (the classic engine is deprecated!)",
               avdArch);
    }
    std::string systemPath = getAvdSystemPath(avdName, sysDir);
    if (systemPath.empty()) {
        const char* env = getenv("ANDROID_SDK_ROOT");
        if (!env || !env[0]) {
            APANIC("Cannot find AVD system path. Please define "
                   "ANDROID_SDK_ROOT\n");
        } else {
            APANIC("Broken AVD system path. Check your ANDROID_SDK_ROOT "
                   "value [%s]!\n",
                   env);
        }
    }
}

Then if you see emulator: ERROR: can't find SDK installation directory, please check this solution. Android emulator errors with "emulator: ERROR: can't find SDK installation directory"

How to change indentation mode in Atom?

Changing language-specific configuration

I changed the default tab settings, and it still did not impact when I was editing my files, which were Python files. It also did not change when I modified the "*" setting in ~/.atom/config.cson . I don't have a good explanation for either of those.

However, when I added the following to my config.cson, I was able to change the tab in my Python files to 2 spaces:

'.source.python':
  editor:
    tabLength: 2

Thanks to this resource for the solution: Tab key not respecting tab length

How do you POST to a page using the PHP header() function?

The header function is used to send HTTP response headers back to the user (i.e. you cannot use it to create request headers.

May I ask why are you doing this? Why simulate a POST request when you can just right there and then act on the data someway? I'm assuming of course script.php resides on your server.

To create a POST request, open a up a TCP connection to the host using fsockopen(), then use fwrite() on the handler returned from fsockopen() with the same values you used in the header functions in the OP. Alternatively, you can use cURL.

trim left characters in sql server?

use "LEFT"

 select left('Hello World', 5)

or use "SUBSTRING"

 select substring('Hello World', 1, 5)

What happened to Lodash _.pluck?

Or try pure ES6 nonlodash method like this

const reducer = (array, object) => {
  array.push(object.a)
  return array
}

var objects = [{ 'a': 1 }, { 'a': 2 }];
objects.reduce(reducer, [])

After MySQL install via Brew, I get the error - The server quit without updating PID file

This is file permission problem. Check disk permissions and repair.

Osx => Cmd+Space => Disk Utilty => Verify Disk Permissions.

Verify completed after Repair Disk Permissions. mysql.server start command is worked succesfuly.

Spring - applicationContext.xml cannot be opened because it does not exist

You should keep your Spring files in another folder, marked as "source" (just like "src" or "resources").

WEB-INF is not a source folder, therefore it will not be included in the classpath (i.e. JUnit will not look for anything there).

Set maxlength in Html Textarea

try this

$(function(){
  $("textarea[maxlength]")
    .keydown(function(event){
       return !$(this).attr("maxlength") || this.value.length < $(this).attr("maxlength") || event.keyCode == 8 || event.keyCode == 46;
    })
    .keyup(function(event){
      var limit = $(this).attr("maxlength");

      if (!limit) return;

      if (this.value.length <= limit) return true;
      else {
        this.value = this.value.substr(0,limit);
        return false;
      }    
    });
});

For me works really perfect without jumping/showing additional characters; works exactly like maxlength on input

How to add header row to a pandas DataFrame

You can use names directly in the read_csv

names : array-like, default None List of column names to use. If file contains no header row, then you should explicitly pass header=None

Cov = pd.read_csv("path/to/file.txt", 
                  sep='\t', 
                  names=["Sequence", "Start", "End", "Coverage"])

How do I wait for a promise to finish before returning the variable of a function?

You're not actually using promises here. Parse lets you use callbacks or promises; your choice.

To use promises, do the following:

query.find().then(function() {
    console.log("success!");
}, function() {
    console.log("error");
});

Now, to execute stuff after the promise is complete, you can just execute it inside the promise callback inside the then() call. So far this would be exactly the same as regular callbacks.

To actually make good use of promises is when you chain them, like this:

query.find().then(function() {
    console.log("success!");

    return new Parse.Query(Obj).get("sOmE_oBjEcT");
}, function() {
    console.log("error");
}).then(function() {
    console.log("success on second callback!");
}, function() {
    console.log("error on second callback");
});

how do you view macro code in access?

You can try the following VBA code to export Macro contents directly without converting them to VBA first. Unlike Tables, Forms, Reports, and Modules, the Macros are in a container called Scripts. But they are there and can be exported and imported using SaveAsText and LoadFromText

Option Compare Database

Option Explicit

Public Sub ExportDatabaseObjects()
On Error GoTo Err_ExportDatabaseObjects

    Dim db As Database
    Dim d As Document
    Dim c As Container
    Dim sExportLocation As String

    Set db = CurrentDb()

    sExportLocation = "C:\SomeFolder\"
    Set c = db.Containers("Scripts")
    For Each d In c.Documents
        Application.SaveAsText acMacro, d.Name, sExportLocation & "Macro_" & d.Name & ".txt"
    Next d

An alternative object to use is as follows:

  For Each obj In Access.Application.CurrentProject.AllMacros
    Access.Application.SaveAsText acMacro, obj.Name, strFilePath & "\Macro_" & obj.Name & ".txt"
  Next

How can I inspect element in chrome when right click is disabled?

Press F12 to Inspect Element and Ctrl+U to View Page Source

How to create a directory if it doesn't exist using Node.js?

You can use node File System command fs.stat to check if dir exists and fs.mkdir to create a directory with callback, or fs.mkdirSync to create a directory without callback, like this example:

//first require fs
const fs = require('fs');

// Create directory if not exist (function)
const createDir = (path) => {
    // check if dir exist
    fs.stat(path, (err, stats) => {
        if (stats.isDirectory()) {
            // do nothing
        } else {
            // if the given path is not a directory, create a directory
            fs.mkdirSync(path);
        }
    });
};

Custom Adapter for List View

This code is easy to understand.

three_horizontal_text_views_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/leftTextView"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/centreTextView"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/rightTextView"/>

</LinearLayout>

ThreeStrings.java

public class ThreeStrings {
    private String left;
    private String right;
    private String centre;

    public ThreeStrings(String left, String right, String centre) {
        this.left = left;
        this.right = right;
        this.centre = centre;
    }
}

ThreeHorizontalTextViewsAdapter.java

public class ThreeHorizontalTextViewsAdapter extends ArrayAdapter<ThreeStrings> {

private int layoutResource;

public ThreeHorizontalTextViewsAdapter(Context context, int layoutResource, List<ThreeStrings> threeStringsList) {
    super(context, layoutResource, threeStringsList);
    this.layoutResource = layoutResource;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    View view = convertView;

    if (view == null) {
        LayoutInflater layoutInflater = LayoutInflater.from(getContext());
        view = layoutInflater.inflate(layoutResource, null);
    }

    ThreeStrings threeStrings = getItem(position);

    if (threeStrings != null) {
        TextView leftTextView = (TextView) view.findViewById(R.id.leftTextView);
        TextView rightTextView = (TextView) view.findViewById(R.id.rightTextView);
        TextView centreTextView = (TextView) view.findViewById(R.id.centreTextView);

        if (leftTextView != null) {
            leftTextView.setText(threeStrings.getLeft());
        }
        if (rightTextView != null) {
            rightTextView.setText(threeStrings.getRight());
        }
        if (centreTextView != null) {
            centreTextView.setText(threeStrings.getCentre());
        }
    }

    return view;
}
      }

main_layout.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="com.androidapplication.ListActivity">


    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/listView"></ListView>

</LinearLayout>

MainActivity.java

public class MainActivity extends Activity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        List<ThreeStrings> threeStringsList = new ArrayList<>();
        ThreeStrings threeStrings = new ThreeStrings("a", "b", "c");
        threeStringsList.add(threeStrings);        
        ListView listView = (ListView)findViewById(R.id.listView);
        ThreeHorizontalTextViewsAdapter threeHorizontalTextViewsAdapter = new ThreeHorizontalTextViewsAdapter(this, R.layout.three_horizontal_text_views_layout, threeStringsList);
        listView.setAdapter(threeHorizontalTextViewsAdapter);
      }
   //......}

How to correctly implement custom iterators and const_iterators?

There are plenty of good answers but I created a template header I use that is quite concise and easy to use.

To add an iterator to your class it is only necessary to write a small class to represent the state of the iterator with 7 small functions, of which 2 are optional:

#include <iostream>
#include <vector>
#include "iterator_tpl.h"

struct myClass {
  std::vector<float> vec;

  // Add some sane typedefs for STL compliance:
  STL_TYPEDEFS(float);

  struct it_state {
    int pos;
    inline void begin(const myClass* ref) { pos = 0; }
    inline void next(const myClass* ref) { ++pos; }
    inline void end(const myClass* ref) { pos = ref->vec.size(); }
    inline float& get(myClass* ref) { return ref->vec[pos]; }
    inline bool cmp(const it_state& s) const { return pos != s.pos; }

    // Optional to allow operator--() and reverse iterators:
    inline void prev(const myClass* ref) { --pos; }
    // Optional to allow `const_iterator`:
    inline const float& get(const myClass* ref) const { return ref->vec[pos]; }
  };
  // Declare typedef ... iterator;, begin() and end() functions:
  SETUP_ITERATORS(myClass, float&, it_state);
  // Declare typedef ... reverse_iterator;, rbegin() and rend() functions:
  SETUP_REVERSE_ITERATORS(myClass, float&, it_state);
};

Then you can use it as you would expect from an STL iterator:

int main() {
  myClass c1;
  c1.vec.push_back(1.0);
  c1.vec.push_back(2.0);
  c1.vec.push_back(3.0);

  std::cout << "iterator:" << std::endl;
  for (float& val : c1) {
    std::cout << val << " "; // 1.0 2.0 3.0
  }

  std::cout << "reverse iterator:" << std::endl;
  for (auto it = c1.rbegin(); it != c1.rend(); ++it) {
    std::cout << *it << " "; // 3.0 2.0 1.0
  }
}

I hope it helps.

Android JSONObject - How can I loop through a flat JSON object to get each key and value

Use the keys() iterator to iterate over all the properties, and call get() for each.

Iterator<String> iter = json.keys();
while (iter.hasNext()) {
    String key = iter.next();
    try {
        Object value = json.get(key);
    } catch (JSONException e) {
        // Something went wrong!
    }
}

Accept function as parameter in PHP

You can also use create_function to create a function as a variable and pass it around. Though, I like the feeling of anonymous functions better. Go zombat.

I do not want to inherit the child opacity from the parent in CSS

Instead of using opacity, set a background-color with rgba, where 'a' is the level of transparency.

So instead of:

background-color: rgb(0,0,255); opacity: 0.5;

use

background-color: rgba(0,0,255,0.5);

SQL query for extracting year from a date

just pass the columnName as parameter of YEAR

SELECT YEAR(ASOFDATE) from PSASOFDATE;

another is to use DATE_FORMAT

SELECT DATE_FORMAT(ASOFDATE, '%Y') from PSASOFDATE;

UPDATE 1

I bet the value is varchar with the format MM/dd/YYYY, it that's the case,

SELECT YEAR(STR_TO_DATE('11/15/2012', '%m/%d/%Y'));

LAST RESORT if all the queries fail

use SUBSTRING

SELECT SUBSTRING('11/15/2012', 7, 4)

Get push notification while App in foreground iOS

As mentioned above, you should use UserNotification.framework to achieve this. But for my purposes I have to show it in app anyway and wanted to have iOS 11 style, so I've created a small helper view, maybe would be useful for someone.

GitHub iOS 11 Push Notification View.

How to make/get a multi size .ico file?

Fresh answer 2018:

Step 1 Launch Microsoft Paint. Not Paint.Net but plain Paint

Step 2 Open the image you want to convert to icon format by clicking the “Paint” toolbar tab and selecting “Open.”

Step 3 Click the “Paint” tab, highlight the “Save As” option and select the “BMP picture” option. As 256-colored. There is a dropdown list.

Step 4 You have to open it in Paint.net now. Enter a file name for the icon and type “.ico” (without quotations) as the file extension. Select your preferred output folder for the icon and click “Save.”(still in bmp type) , exposing auto definition in saving parameters window.

This is a solution for those WHO DOESN'T WANT THE THIRD PARTY APPS TO GAIN PERMISSIONS ON THEIR COMP.
I use this simple way to create custom icons for folders on my desktop or documents.

HTML: Is it possible to have a FORM tag in each TABLE ROW in a XHTML valid way?

You just have to put the <form ... > tag before the <table> tag and the </form> at the end.

Hopte it helps.

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

When you say pair[0], that gives you ("a", 1). The thing in parentheses is a tuple, which, like a list, is a type of collection. So you can access the first element of that thing by specifying [0] or [1] after its name. So all you have to do to get the first element of the first element of pair is say pair[0][0]. Or if you want the second element of the third element, it's pair[2][1].

Oracle SQL - REGEXP_LIKE contains characters other than a-z or A-Z

if you want that not contains any of a-z and A-Z:

SELECT * FROM mytable WHERE NOT REGEXP_LIKE(column_1, '[A-Za-z]')

something like:

"98763045098" or "!%436%$7%$*#"

or other languages like persian, arabic and ... like this:

"???? ????"

Alternative Windows shells, besides CMD.EXE?

Try Clink. It's awesome, especially if you are used to bash keybindings and features.

(As already pointed out - there is a similar question: Is there a better Windows Console Window?)

How to measure elapsed time in Python?

Python 3 only:

Since time.clock() is deprecated as of Python 3.3, you will want to use time.perf_counter() for system-wide timing, or time.process_time() for process-wide timing, just the way you used to use time.clock():

import time

t = time.process_time()
#do some stuff
elapsed_time = time.process_time() - t

The new function process_time will not include time elapsed during sleep.

round() for float in C++

Best way to rounding off a floating value by "n" decimal places, is as following with in O(1) time:-

We have to round off the value by 3 places i.e. n=3.So,

float a=47.8732355;
printf("%.3f",a);

Angular exception: Can't bind to 'ngForIn' since it isn't a known native property

my solution was - just remove '*' character from the expression ^__^

<div ngFor="let talk in talks">

jQuery form input select by id

Why not just:

$('#b').click(function () {
    var val = $(this).val(); 
})

Or if you don't click it (and I guess you won't) and you will use submit button, you can use prev() function either.

add image to uitableview cell

Swift 5 solution

cell.imageView?.image = UIImage.init(named: "yourImageName")

How to convert a column number (e.g. 127) into an Excel column (e.g. AA)

In perl, for an input of 1 (A), 27 (AA), etc.

sub excel_colname {
  my ($idx) = @_;       # one-based column number
  --$idx;               # zero-based column index
  my $name = "";
  while ($idx >= 0) {
    $name .= chr(ord("A") + ($idx % 26));
    $idx   = int($idx / 26) - 1;
  }
  return scalar reverse $name;
}

How can I make a thumbnail <img> show a full size image when clicked?

Here is the Angular version of LightBox. Just Awesome :)

Note : I have put this answer hence No Js library has been mentioned under the Tags.

angular-bootstrap-lightbox

<ul ng-controller="GalleryCtrl">
  <li ng-repeat="image in images">
    <a ng-click="openLightboxModal($index)">
      <img ng-src="{{image.thumbUrl}}" class="img-thumbnail">
    </a>
  </li>
</ul>

When to use async false and async true in ajax function in jquery

  1. When async setting is set to false, a Synchronous call is made instead of an Asynchronous call.
  2. When the async setting of the jQuery AJAX function is set to true then a jQuery Asynchronous call is made. AJAX itself means Asynchronous JavaScript and XML and hence if you make it Synchronous by setting async setting to false, it will no longer be an AJAX call.
  3. for more information please refer this link

How can I find a file/directory that could be anywhere on linux command line?

To get rid of permission errors (and such), you can redirect stderr to nowhere

find / -name "something" 2>/dev/null

Remove all git files from a directory?

Unlike other source control systems like SVN or CVS, git stores all of its metadata in a single directory, rather than in every subdirectory of the project. So just delete .git from the root (or use a script like git-export) and you should be fine.

A fast way to delete all rows of a datatable at once

Just use dt.Clear()

Also you can set your TableAdapter/DataAdapter to clear before it fills with data.

Can I find events bound on an element with jQuery?

While this isn't exactly specific to jQuery selectors/objects, in FireFox Quantum 58.x, you can find event handlers on an element using the Dev tools:

  1. Right-click the element
  2. In the context menu, Click 'Inspect Element'
  3. If there is an 'ev' icon next to the element (yellow box), click on 'ev' icon
  4. Displays all events for that element and event handler

FF Quantum Dev Tools

error LNK2005: xxx already defined in MSVCRT.lib(MSVCR100.dll) C:\something\LIBCMT.lib(setlocal.obj)

You are mixing code that was compiled with /MD (use DLL version of CRT) with code that was compiled with /MT (use static CRT library). That cannot work, all source code files must be compiled with the same setting. Given that you use libraries that were pre-compiled with /MD, almost always the correct setting, you must compile your own code with this setting as well.

Project + Properties, C/C++, Code Generation, Runtime Library.

Beware that these libraries were probably compiled with an earlier version of the CRT, msvcr100.dll is quite new. Not sure if that will cause trouble, you may have to prevent the linker from generating a manifest. You must also make sure to deploy the DLLs you need to the target machine, including msvcr100.dll

Applying an ellipsis to multiline text

I came up with my own solution for this:

/*this JS code puts the ellipsis (...) at the end of multiline ellipsis elements
 *
 * to use the multiline ellipsis on an element give it the following CSS properties
 * line-height:xxx
 * height:xxx (must line-height * number of wanted lines)
 * overflow:hidden
 *
 * and have the class js_ellipsis
 * */

//do all ellipsis when jQuery loads
jQuery(document).ready(function($) {put_ellipsisses();});

//redo ellipsis when window resizes
var re_ellipsis_timeout;
jQuery( window ).resize(function() {
    //timeout mechanism prevents from chain calling the function on resize
    clearTimeout(re_ellipsis_timeout);
    re_ellipsis_timeout = setTimeout(function(){ console.log("re_ellipsis_timeout finishes"); put_ellipsisses(); }, 500);
});

//the main function
function put_ellipsisses(){
    jQuery(".js_ellipsis").each(function(){

        //remember initial text to be able to regrow when space increases
        var object_data=jQuery(this).data();
        if(typeof object_data.oldtext != "undefined"){
            jQuery(this).text(object_data.oldtext);
        }else{
            object_data.oldtext = jQuery(this).text();
            jQuery(this).data(object_data);
        }

        //truncate and ellipsis
        var clientHeight = this.clientHeight;
        var maxturns=100; var countturns=0;
        while (this.scrollHeight > clientHeight && countturns < maxturns) {
            countturns++;
            jQuery(this).text(function (index, text) {
                return text.replace(/\W*\s(\S)*$/, '...');
            });
        }
    });
}

How to set Java classpath in Linux?

You have to use ':' colon instead of ';' semicolon.

As it stands now you try to execute the jar file which has not the execute bit set, hence the Permission denied.

And the variable must be CLASSPATH not classpath.

How does String substring work in Swift

Came across this fairly short and simple way of achieving this.

var str = "Hello, World"
let arrStr = Array(str)
print(arrStr[0..<5]) //["H", "e", "l", "l", "o"]
print(arrStr[7..<12]) //["W", "o", "r", "l", "d"]
print(String(arrStr[0..<5])) //Hello
print(String(arrStr[7..<12])) //World

JPA: difference between @JoinColumn and @PrimaryKeyJoinColumn?

I normally differentiate these two via this diagram:

Use PrimaryKeyJoinColumn

enter image description here

Use JoinColumn

enter image description here

Is there a way to define a min and max value for EditText in Android?

There is something wrong in the accepted answer.

int input = Integer.parseInt(dest.toString() + source.toString());

If I move cursor into middle of text, then type something, then the above statement will produce wrong result. For example, type "12" first, then type "0" between 1 and 2, then the statement mentioned above will produce "120" instead of 102. I modified this statement to statements below:

String destString = dest.toString();
  String inputString = destString.substring(0, dstart) + source.toString() + destString.substring(dstart);
  int input = Integer.parseInt(inputString);

Cloud Firestore collection count

As with many questions, the answer is - It depends.

You should be very careful when handling large amounts of data on the front end. On top of making your front end feel sluggish, Firestore also charges you $0.60 per million reads you make.


Small collection (less than 100 documents)

Use with care - Frontend user experience may take a hit

Handling this on the front end should be fine as long as you are not doing too much logic with this returned array.

db.collection('...').get().then(snap => {
   size = snap.size // will return the collection size
});

Medium collection (100 to 1000 documents)

Use with care - Firestore read invocations may cost a lot

Handling this on the front end is not feasible as it has too much potential to slow down the users system. We should handle this logic server side and only return the size.

The drawback to this method is you are still invoking firestore reads (equal to the size of your collection), which in the long run may end up costing you more than expected.

Cloud Function:

...
db.collection('...').get().then(snap => {
    res.status(200).send({length: snap.size});
});

Front End:

yourHttpClient.post(yourCloudFunctionUrl).toPromise().then(snap => {
     size = snap.length // will return the collection size
})

Large collection (1000+ documents)

Most scalable solution


FieldValue.increment()

As of April 2019 Firestore now allows incrementing counters, completely atomically, and without reading the data prior. This ensures we have correct counter values even when updating from multiple sources simultaneously (previously solved using transactions), while also reducing the number of database reads we perform.


By listening to any document deletes or creates we can add to or remove from a count field that is sitting in the database.

See the firestore docs - Distributed Counters Or have a look at Data Aggregation by Jeff Delaney. His guides are truly fantastic for anyone using AngularFire but his lessons should carry over to other frameworks as well.

Cloud Function:

export const documentWriteListener = 
    functions.firestore.document('collection/{documentUid}')
    .onWrite((change, context) => {

    if (!change.before.exists) {
        // New document Created : add one to count

        db.doc(docRef).update({numberOfDocs: FieldValue.increment(1)});
    
    } else if (change.before.exists && change.after.exists) {
        // Updating existing document : Do nothing

    } else if (!change.after.exists) {
        // Deleting document : subtract one from count

        db.doc(docRef).update({numberOfDocs: FieldValue.increment(-1)});

    }

return;
});

Now on the frontend you can just query this numberOfDocs field to get the size of the collection.

TypeScript: correct way to do string equality?

If you know x and y are both strings, using === is not strictly necessary, but is still good practice.

Assuming both variables actually are strings, both operators will function identically. However, TS often allows you to pass an object that meets all the requirements of string rather than an actual string, which may complicate things.

Given the possibility of confusion or changes in the future, your linter is probably correct in demanding ===. Just go with that.

How do I attach events to dynamic HTML elements with jQuery?

I am adding a new answer to reflect changes in later jQuery releases. The .live() method is deprecated as of jQuery 1.7.

From http://api.jquery.com/live/

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().

For jQuery 1.7+ you can attach an event handler to a parent element using .on(), and pass the a selector combined with 'myclass' as an argument.

See http://api.jquery.com/on/

So instead of...

$(".myclass").click( function() {
    // do something
});

You can write...

$('body').on('click', 'a.myclass', function() {
    // do something
});

This will work for all a tags with 'myclass' in the body, whether already present or dynamically added later.

The body tag is used here as the example had no closer static surrounding tag, but any parent tag that exists when the .on method call occurs will work. For instance a ul tag for a list which will have dynamic elements added would look like this:

$('ul').on('click', 'li', function() {
    alert( $(this).text() );
});

As long as the ul tag exists this will work (no li elements need exist yet).

How to increase MySQL connections(max_connections)?

I had the same issue and I resolved it with MySQL workbench, as shown in the attached screenshot:

  1. in the navigator (on the left side), under the section "management", click on "Status and System variables",
  2. then choose "system variables" (tab at the top),
  3. then search for "connection" in the search field,
  4. and 5. you will see two fields that need to be adjusted to fit your needs (max_connections and mysqlx_max_connections).

Hope that helps!

The system does not allow me to upload pictures, instead please click on this link and you can see my screenshot...

Pip - Fatal error in launcher: Unable to create process using '"'

run this python code:

import pip
pip.main(['install','flask']) # replace flask with the name of module you want to install

If you need to install multiple modules from a requirements.txt file,

import pip
fo = open("C:/...../requirements.txt", "r")
inp = fo.read()
ls =inp.split()     

for i in ls:
    pip.main(['install',i])

Loop through all the files with a specific extension

I agree withe the other answers regarding the correct way to loop through the files. However the OP asked:

The code above doesn't work, do you know why?

Yes!

An excellent article What is the difference between test, [ and [[ ?] explains in detail that among other differences, you cannot use expression matching or pattern matching within the test command (which is shorthand for [ )


Feature            new test [[    old test [           Example

Pattern matching    = (or ==)    (not available)    [[ $name = a* ]] || echo "name does not start with an 'a': $name"

Regular Expression     =~        (not available)    [[ $(date) =~ ^Fri\ ...\ 13 ]] && echo "It's Friday the 13th!"
matching

So this is the reason your script fails. If the OP is interested in an answer with the [[ syntax (which has the disadvantage of not being supported on as many platforms as the [ command), I would be happy to edit my answer to include it.

EDIT: Any protips for how to format the data in the answer as a table would be helpful!

C++ wait for user input

a do while loop would be a nice way to wait for the user input. Like this:

int main() 
{

 do 
 {
   cout << '\n' << "Press a key to continue...";
 } while (cin.get() != '\n');

 return 0;
}

You can also use the function system('PAUSE') but I think this is a bit slower and platform dependent

crop text too long inside div

Why not use relative units?

.cropText {
    max-width: 20em;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

$lookup on ObjectId's in an array

Starting with MongoDB v3.4 (released in 2016), the $lookup aggregation pipeline stage can also work directly with an array. There is no need for $unwind any more.

This was tracked in SERVER-22881.

submitting a GET form with query string params and hidden params disappear

<form ... action="http:/www.blabla.com?a=1&b=2" method ="POST">
<input type="hidden" name="c" value="3" /> 
</form>

change the request method to' POST' instead of 'GET'.

JAX-WS client : what's the correct path to access the local WSDL?

Thanks a ton for Bhaskar Karambelkar's answer which explains in detail and fixed my issue. But also I would like to re phrase the answer in three simple steps for someone who is in a hurry to fix

  1. Make your wsdl local location reference as wsdlLocation= "http://localhost/wsdl/yourwsdlname.wsdl"
  2. Create a META-INF folder right under the src. Put your wsdl file/s in a folder under META-INF, say META-INF/wsdl
  3. Create an xml file jax-ws-catalog.xml under META-INF as below

    <catalog xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog" prefer="system"> <system systemId="http://localhost/wsdl/yourwsdlname.wsdl" uri="wsdl/yourwsdlname.wsdl" /> </catalog>

Now package your jar. No more reference to the local directory, it's all packaged and referenced within

"multiple target patterns" Makefile error

I also got this error (within the Eclipse-based STM32CubeIDE on Windows).

After double-clicking on the "multiple target patterns" error it showed a path to a .ld file. It turns out to be another "illegal character" problem. The offending character was the (wait for it): =

Heuristic of the week: use only [a..z] in your paths, as there are bound to be other illegal characters </vomit>.

The GNU make manual doesn't explicitly document this.

How to set a border for an HTML div tag

You need to set more fields then just border-width. The style basically puts the border on the page. Width controls the thickness, and color tells it what color to make the border.

border-style: solid; border-width:thin; border-color: #FFFFFF;

How to add title to seaborn boxplot

Seaborn box plot returns a matplotlib axes instance. Unlike pyplot itself, which has a method plt.title(), the corresponding argument for an axes is ax.set_title(). Therefore you need to call

sns.boxplot('Day', 'Count', data= gg).set_title('lalala')

A complete example would be:

import seaborn as sns
import matplotlib.pyplot as plt

tips = sns.load_dataset("tips")
sns.boxplot(x=tips["total_bill"]).set_title("LaLaLa")

plt.show()

Of course you could also use the returned axes instance to make it more readable:

ax = sns.boxplot('Day', 'Count', data= gg)
ax.set_title('lalala')
ax.set_ylabel('lololo')

Get parent directory of running script

I Hope this will help you.

echo getcwd().'<br>'; // getcwd() will return current working directory
echo dirname(getcwd(),1).'<br>';
echo dirname(getcwd(),2).'<br>';
echo dirname(getcwd(),3).'<br>';

Output :

C:\wamp64\www\public_html\step
C:\wamp64\www\public_html
C:\wamp64\www
C:\wamp64

Update query with PDO and MySQL

This has nothing to do with using PDO, it's just that you are confusing INSERT and UPDATE.

Here's the difference:

  • INSERT creates a new row. I'm guessing that you really want to create a new row.
  • UPDATE changes the values in an existing row, but if this is what you're doing you probably should use a WHERE clause to restrict the change to a specific row, because the default is that it applies to every row.

So this will probably do what you want:

$sql = "INSERT INTO `access_users`   
  (`contact_first_name`,`contact_surname`,`contact_email`,`telephone`) 
  VALUES (:firstname, :surname, :email, :telephone);
  ";

Note that I've also changed the order of columns; the order of your columns must match the order of values in your VALUES clause.

MySQL also supports an alternative syntax for INSERT:

$sql = "INSERT INTO `access_users`   
  SET `contact_first_name` = :firstname,
    `contact_surname` = :surname,
    `contact_email` = :email,
    `telephone` = :telephone
  ";

This alternative syntax looks a bit more like an UPDATE statement, but it creates a new row like INSERT. The advantage is that it's easier to match up the columns to the correct parameters.

How to deal with INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES without uninstall?

I had this problem trying to execute gradle task connectedDebugAndoidTest (or connectedAndroidTest) on Genymotion. Running it on normal emulator solved the problem.

C++ auto keyword. Why is it magic?

It's Magic is it's ability to reduce having to write code for every Variable Type passed into specific functions. Consider a Python similar print() function in it's C base.

#include <iostream>
#include <string>
#include <array>

using namespace std;

void print(auto arg) {
     cout<<arg<<" ";
}

int main()
{
  string f = "String";//tok assigned
  int x = 998;
  double a = 4.785;
  string b = "C++ Auto !";
//In an opt-code ASCII token stream would be iterated from tok's as:
  print(a);
  print(b);
  print(x);
  print(f);
}

What's the opposite of 'make install', i.e. how do you uninstall a library in Linux?

There is no standard unfortunately, this is one of the perils of installing from source. Some Makefiles will include an "uninstall", so

make uninstall

from the source directory may work. Otherwise, it may be a matter of manually undoing whatever the make install did.

make clean usually just cleans up the source directory - removing generated/compiled files and the like, probably not what you're after.

str_replace with array

Because str_replace() replaces left to right, it might replace a previously inserted value when doing multiple replacements.

    // Outputs F because A is replaced with B, then B is replaced with C, and so on...
    // Finally E is replaced with F, because of left to right replacements.
    $search  = array('A', 'B', 'C', 'D', 'E');
    $replace = array('B', 'C', 'D', 'E', 'F');
    $subject = 'A';
    echo str_replace($search, $replace, $subject);

Populate nested array in mongoose

That works for me:

 Project.find(query)
  .lean()
  .populate({ path: 'pages' })
  .exec(function(err, docs) {

    var options = {
      path: 'pages.components',
      model: 'Component'
    };

    if (err) return res.json(500);
    Project.populate(docs, options, function (err, projects) {
      res.json(projects);
    });
  });

Documentation: Model.populate

Disabling Controls in Bootstrap

<select id="message_tag">
<optgroup>
<option>
....
....
</option>
</optgroup>

here i just removed bootstrap css for only "select" element. using following css code.

#message_tag_chzn{
display: none;
}

 #message_tag{
  display: inline !important;
}

How to set custom favicon in Express?

In app.js:

app.use(express.static(path.join(__dirname, 'public')));

Assuming the icon resides in "/public/images/favicon.ico" add next link in html's head:

<link rel='icon' href='/images/favicon.ico' class='js-favicon'>

This worked fine in a project auto-generated with the command:

express my-project

Transpose a range in VBA

Something like this should do it for you.

Sub CombineColumns1()
    Dim xRng As Range
    Dim i As Long, j As Integer
    Dim xNextRow As Long
    Dim xTxt As String
    On Error Resume Next
    With ActiveSheet
        xTxt = .RangeSelection.Address
        Set xRng = Application.InputBox("please select the data range", "Kutools for Excel", xTxt, , , , , 8)
        If xRng Is Nothing Then Exit Sub
        j = xRng.Columns(1).Column
        For i = 4 To xRng.Columns.Count Step 3
            'Need to recalculate the last row, as some of the final columns may not have data in all rows
            xNextRow = .Cells(.Rows.Count, j).End(xlUp).Row + 1

            .Range(xRng.Cells(1, i), xRng.Cells(xRng.Rows.Count, i + 2)).Copy .Cells(xNextRow, j)
            .Range(xRng.Cells(1, i), xRng.Cells(xRng.Rows.Count, i + 2)).Clear
        Next
    End With
End Sub

You could do this too.

Sub TransposeFormulas()
    Dim vFormulas As Variant
    Dim oSel As Range
    If TypeName(Selection) <> "Range" Then
        MsgBox "Please select a range of cells first.", _
                vbOKOnly + vbInformation, "Transpose formulas"
        Exit Sub
    End If
    Set oSel = Selection
    vFormulas = oSel.Formula
    vFormulas = Application.WorksheetFunction.Transpose(vFormulas)
    oSel.Offset(oSel.Rows.Count + 2).Resize(oSel.Columns.Count, oSel.Rows.Count).Formula = vFormulas
End Sub

See this for more info.

http://bettersolutions.com/vba/arrays/transposing.htm

How to make link not change color after visited?

Something like this should work:

a, a:visited { 
    color:red; text-decoration:none; 
    }

Connection refused to MongoDB errno 111

One other option is to just repair your database like so (note: db0 directory should be pre-created first):

mongod --dbpath /var/lib/mongodb/ --repairpath /var/lib/mongodb/db0

This is also an acceptable option in production environments...

change text of button and disable button in iOS

[myButton setTitle: @"myTitle" forState: UIControlStateNormal];

Use UIControlStateNormal to set your title.

There are couple of states that UIbuttons provide, you can have a look:

[myButton setTitle: @"myTitle" forState: UIControlStateApplication];
[myButton setTitle: @"myTitle" forState: UIControlStateHighlighted];
[myButton setTitle: @"myTitle" forState: UIControlStateReserved];
[myButton setTitle: @"myTitle" forState: UIControlStateSelected];
[myButton setTitle: @"myTitle" forState: UIControlStateDisabled];

CSS Positioning Elements Next to each other

If you want them to be displayed side by side, why is sideContent the child of mainContent? make them siblings then use:

float:left; display:inline; width: 49%;

on both of them.

#mainContent, #sideContent {float:left; display:inline; width: 49%;}

Localhost not working in chrome and firefox

In case the browser LAN proxy setting solution doesn't work for you:

As mentioned in this similar Q&A How to solve ERR_CONNECTION_REFUSED when trying to connect to localhost running IISExpress - Error 502 (Cannot debug from Visual Studio)?

Simply changing the port number of your web project can be a quick fix.

enter image description here

How to connect Bitbucket to Jenkins properly

I had this problem and it turned out the issue was that I had named my repository with CamelCase. Bitbucket automatically changes the URL of your repository to be all lower case and that gets sent to Jenkins in the webhook. Jenkins then searches for projects with a matching repository. If you, like me, have CamelCase in your repository URL in your project configuration you will be able to check out code, but the pattern matching on the webhook request will fail.

Just change your repo URL to be all lower case instead of CamelCase and the pattern match should find your project.

How to set component default props on React component

For a function type prop you can use the following code:

AddAddressComponent.defaultProps = {
    callBackHandler: () => {}
};

AddAddressComponent.propTypes = {
    callBackHandler: PropTypes.func,
};

How to turn off Wifi via ADB?

All these input keyevent combinations are SO android/hardware dependent, it's a pain.

However, I finally found the combination for my old android 4.1 device :

adb shell am start -a android.intent.action.MAIN -n com.android.settings/.wifi.WifiSettings
adb shell "input keyevent KEYCODE_DPAD_LEFT;input keyevent KEYCODE_DPAD_RIGHT;input keyevent KEYCODE_DPAD_CENTER"

ng-repeat :filter by single field

my way is this

subjcts is

[{"id":"1","title":"GFATM"},{"id":"2","title":"Court Case"},{"id":"3","title":"Renewal\/Validity"},{"id":"4","title":"Change of Details"},{"id":"5","title":"Student Query"},{"id":"6","title":"Complains"}]

sub is a Input field or whatever you like

Displaying like this

<div ng-if="x.id === sub" ng-repeat=" x in subjcts">{{x.title}}</div>

You need to install postgresql-server-dev-X.Y for building a server-side extension or libpq-dev for building a client-side application

For Python 3, I did:

sudo apt install python3-dev postgresql postgresql-contrib python3-psycopg2 libpq-dev

and then I was able to do:

pip3 install psycopg2

Deleting folders in python recursively

Here is a recursive solution:

def clear_folder(dir):
    if os.path.exists(dir):
        for the_file in os.listdir(dir):
            file_path = os.path.join(dir, the_file)
            try:
                if os.path.isfile(file_path):
                    os.unlink(file_path)
                else:
                    clear_folder(file_path)
                    os.rmdir(file_path)
            except Exception as e:
                print(e)

How to get PID by process name?

you can also use pgrep, in prgep you can also give pattern for match

import subprocess
child = subprocess.Popen(['pgrep','program_name'], stdout=subprocess.PIPE, shell=True)
result = child.communicate()[0]

you can also use awk with ps like this

ps aux | awk '/name/{print $2}'

Xcode - ld: library not found for -lPods

I had the same problem

pod install and pod update on command line resolve my problem

Adding attributes to an XML node

You can use the Class XmlAttribute.

Eg:

XmlAttribute attr = xmlDoc.CreateAttribute("userName");
attr.Value = "Tushar";

node.Attributes.Append(attr);

location.host vs location.hostname and cross-browser compatibility?

interactive link anatomy

As a little memo: the interactive link anatomy

--

In short (assuming a location of http://example.org:8888/foo/bar#bang):

  • hostname gives you example.org
  • host gives you example.org:8888

How to zip a file using cmd line?

Not exactly zipping, but you can compact files in Windows with the compact command:

compact /c /s:<directory or file>

And to uncompress:

compact /u /s:<directory or file>

NOTE: These commands only mark/unmark files or directories as compressed in the file system. They do not produces any kind of archive (like zip, 7zip, rar, etc.)

what is the difference between OLE DB and ODBC data sources?

ODBC:- Only for relational databases (Sql Server, Oracle etc)

OLE DB:- For both relational and non-relational databases. (Oracle, Sql-Server, Excel, raw files, etc)

<button> vs. <input type="button" />. Which to use?

Use button from input element if you want to create button in a form. And use button tag if you want to create button for an action.

C compile error: "Variable-sized object may not be initialized"

For C++ separate declaration and initialization like this..

int a[n][m] ;
a[n][m]= {0};

How do I escape special characters in MySQL?

You can use mysql_real_escape_string. mysql_real_escape_string() does not escape % and _, so you should escape MySQL wildcards (% and _) separately.

How can I force a long string without any blank to be wrapped?

just setting width and adding float worked for me :-)

width:100%;
float:left;

Android: ProgressDialog.show() crashes with getApplicationContext

I am using Android version 2.1 with API Level 7. I faced with this (or similar) problem and solved by using this:

Dialog dialog = new Dialog(this);

instead of this:

Dialog dialog = new Dialog(getApplicationContext());

Hope this helps :)

Using floats with sprintf() in embedded C

use the %f modifier:

sprintf (str, "adc_read = %f\n", adc_read);

For instance:

#include <stdio.h>

int main (void) 
{
    float x = 2.5;
    char y[200];

    sprintf(y, "x = %f\n", x);
    printf(y);
    return 0;
}

Yields this:

x = 2.500000

How to remove outliers from a dataset

Adding to @sefarkas' suggestion and using quantile as cut-offs, one could explore the following option:

newdata <- subset(mydata,!(mydata$var > quantile(mydata$var, probs=c(.01, .99))[2] | mydata$var < quantile(mydata$var, probs=c(.01, .99))[1]) ) 

This will remove the points points beyond the 99th quantile. Care should be taken like what aL3Xa was saying about keeping outliers. It should be removed only for getting an alternative conservative view of the data.

How to use classes from .jar files?

You need to put the .jar file into your classpath when compiling/running your code. Then you just use standard imports of the classes in the .jar.

What does it mean "No Launcher activity found!"

You have not included Launcher intent filter in activity you want to appear first, so it does not know which activity to start when application launches, for this tell the system by including launcher filter intent in manifest.xml

Config Error: This configuration section cannot be used at this path

The error says that the configuration section is locked at the parent level. So it will not be directly 1 config file which will resolve the issue, we need to go through the hierarchy of the config files to see the inheritance Check the below link to go through the File hierarchy and inheritance in IIS

https://msdn.microsoft.com/en-us/library/ms178685.aspx

So you need to check for the app config settings in the below order

  1. ApplicationHost.config in C:windows\system32\inetsrv\config. Change the overrideModeDefault attribute to be Allow.
  2. ApplicationName.config or web.config in the applications directory
  3. Web.config in the root directory.
  4. Web.config in the specific website (My issue was found at this place).
  5. Web.config of the root web (server's configuration)
  6. machine.config of the machine (Root's web.config and machine.config can be found at - systemroot\MicrosoftNET\Framework\versionNumber\CONFIG\Machine.config)

Go carefully through all these configs in the order of 1 to 6 and you should find it.

How to concatenate strings in django templates?

In my project I did it like this:

@register.simple_tag()
def format_string(string: str, *args: str) -> str:
    """
    Adds [args] values to [string]
    String format [string]: "Drew %s dad's %s dead."
    Function call in template: {% format_string string "Dodd's" "dog's" %}
    Result: "Drew Dodd's dad's dog's dead."
    """
    return string % args

Here, the string you want concatenate and the args can come from the view, for example.

In template and using your case:

{% format_string 'shop/%s/base.html' shop_name as template %}
{% include template %}

The nice part is that format_string can be reused for any type of string formatting in templates

@HostBinding and @HostListener: what do they do and what are they for?

Another nice thing about @HostBinding is that you can combine it with @Input if your binding relies directly on an input, eg:

@HostBinding('class.fixed-thing')
@Input()
fixed: boolean;

How to get the current time in Python

You can use time.strftime():

>>> from time import gmtime, strftime
>>> strftime("%Y-%m-%d %H:%M:%S", gmtime())
'2009-01-05 22:14:39'

Disable Transaction Log

If this is only for dev machines in order to save space then just go with simple recovery mode and you’ll be doing fine.

On production machines though I’d strongly recommend that you keep the databases in full recovery mode. This will ensure you can do point in time recovery if needed.

Also – having databases in full recovery mode can help you to undo accidental updates and deletes by reading transaction log. See below or more details.

How can I rollback an UPDATE query in SQL server 2005?

Read the log file (*.LDF) in sql server 2008

If space is an issue on production machines then just create frequent transaction log backups.

How to change the color of progressbar in C# .NET 3.5?

Vertical Bar UP For Down in red color :

using System;
using System.Windows.Forms;
using System.Drawing;



public class VerticalProgressBar : ProgressBar
{


    protected override CreateParams CreateParams
    {
        get
        {
            CreateParams cp = base.CreateParams;
            cp.Style |= 0x04;
            return cp;

        }
    }
    private SolidBrush brush = null;

    public VerticalProgressBar()
    {
        this.SetStyle(ControlStyles.UserPaint, true);
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        if (brush == null || brush.Color != this.ForeColor)
            brush = new SolidBrush(this.ForeColor);

        Rectangle rec = new Rectangle(0, 0, this.Width, this.Height);
        if (ProgressBarRenderer.IsSupported)
        ProgressBarRenderer.DrawVerticalBar(e.Graphics, rec);
        rec.Height = (int)(rec.Height * ((double)Value / Maximum)) - 4;
        rec.Width = rec.Width - 4;
        e.Graphics.FillRectangle(brush, 2, 2, rec.Width, rec.Height);

    } 
}

Display all post meta keys and meta values of the same post ID in wordpress

WordPress have the function get_metadata this get all meta of object (Post, term, user...)

Just use

get_metadata( 'post', 15 );

jQuery UI accordion that keeps multiple sections open?

Simple: active the accordion to a class, and then create divs with this, like multiples instances of accordion.

Like this:

JS

$(function() {
    $( ".accordion" ).accordion({
        collapsible: true,
        clearStyle: true,
        active: false,
    })
});

HTML

<div class="accordion">
    <h3>Title</h3>
    <p>lorem</p>
</div>
<div class="accordion">
    <h3>Title</h3>
    <p>lorem</p>
</div>
<div class="accordion">
    <h3>Title</h3>
    <p>lorem</p>
</div>

https://jsfiddle.net/sparhawk_odin/pm91whz3/

Remove an element from a Bash array

What I do is:

array="$(echo $array | tr ' ' '\n' | sed "/itemtodelete/d")"

BAM, that item is removed.

Ideal way to cancel an executing AsyncTask

With reference to Yanchenko's answer on 29 April '10: Using a 'while(running)' approach is neat when your code under 'doInBackground' has to be executed multiple times during every execution of the AsyncTask. If your code under 'doInBackground' has to be executed only once per execution of the AsyncTask, wrapping all your code under 'doInBackground' in a 'while(running)' loop will not stop the background code (background thread) from running when the AsyncTask itself is cancelled, because the 'while(running)' condition will only be evaluated once all the code inside the while loop has been executed at least once. You should thus either (a.) break up your code under 'doInBackground' into multiple 'while(running)' blocks or (b.) perform numerous 'isCancelled' checks throughout your 'doInBackground' code, as explained under "Cancelling a task" at https://developer.android.com/reference/android/os/AsyncTask.html.

For option (a.) one can thus modify Yanchenko's answer as follows:

public class MyTask extends AsyncTask<Void, Void, Void> {

private volatile boolean running = true;

//...

@Override
protected void onCancelled() {
    running = false;
}

@Override
protected Void doInBackground(Void... params) {

    // does the hard work

    while (running) {
        // part 1 of the hard work
    }

    while (running) {
        // part 2 of the hard work
    }

    // ...

    while (running) {
        // part x of the hard work
    }
    return null;
}

// ...

For option (b.) your code in 'doInBackground' will look something like this:

public class MyTask extends AsyncTask<Void, Void, Void> {

//...

@Override
protected Void doInBackground(Void... params) {

    // part 1 of the hard work
    // ...
    if (isCancelled()) {return null;}

    // part 2 of the hard work
    // ...
    if (isCancelled()) {return null;}

    // ...

    // part x of the hard work
    // ...
    if (isCancelled()) {return null;}
}

// ...

Prevent Sequelize from outputting SQL to the console on execution of query?

If 'config/config.json' file is used then add 'logging': false to the config.json in this case under development configuration section.

  // file config/config.json
  {
      {
      "development": {
        "username": "username",
        "password": "password",
        "database": "db_name",
        "host": "127.0.0.1",
        "dialect": "mysql",
        "logging": false
      },
      "test": {
    ...
   }

How to debug external class library projects in visual studio?

Assume the path of

Project A

C:\Projects\ProjectA

Project B

C:\Projects\ProjectB

and the dll of ProjectB is in

C:\Projects\ProjectB\bin\Debug\

To debug into ProjectB from ProjectA, do the following

  1. Copy B's dll with dll's .PDB to the ProjectA's compiling directory.
  2. Now debug ProjectA. When code reaches the part where you need to call dll's method or events etc while debugging, press F11 to step into the dll's code.

NOTE : DO NOT MISS TO COPY THE .PDB FILE

Maven2 property that indicates the parent directory

I've found a solution to solve this problem: use ${parent.relativePath}

<parent>
    <artifactId>xxx</artifactId>
    <groupId>xxx</groupId>
    <version>1.0-SNAPSHOT</version>
    <relativePath>..</relativePath>
</parent>
<build>
    <filters>
        <filter>${parent.relativePath}/src/main/filters/filter-${env}.properties</filter>
    </filters>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
        </resource>
    </resources>
</build>

How to select where ID in Array Rails ActiveRecord without exception

If it is just avoiding the exception you are worried about, the "find_all_by.." family of functions works without throwing exceptions.

Comment.find_all_by_id([2, 3, 5])

will work even if some of the ids don't exist. This works in the

user.comments.find_all_by_id(potentially_nonexistent_ids)

case as well.

Update: Rails 4

Comment.where(id: [2, 3, 5])

SQL Server loop - how do I loop through a set of records

Just another approach if you are fine using temp tables.I have personally tested this and it will not cause any exception (even if temp table does not have any data.)

CREATE TABLE #TempTable
(
    ROWID int identity(1,1) primary key,
    HIERARCHY_ID_TO_UPDATE int,
)

--create some testing data
--INSERT INTO #TempTable VALUES(1)
--INSERT INTO #TempTable VALUES(2)
--INSERT INTO #TempTable VALUES(4)
--INSERT INTO #TempTable VALUES(6)
--INSERT INTO #TempTable VALUES(8)

DECLARE @MAXID INT, @Counter INT

SET @COUNTER = 1
SELECT @MAXID = COUNT(*) FROM #TempTable

WHILE (@COUNTER <= @MAXID)
BEGIN
    --DO THE PROCESSING HERE 
    SELECT @HIERARCHY_ID_TO_UPDATE = PT.HIERARCHY_ID_TO_UPDATE
    FROM #TempTable AS PT
    WHERE ROWID = @COUNTER

    SET @COUNTER = @COUNTER + 1
END


IF (OBJECT_ID('tempdb..#TempTable') IS NOT NULL)
BEGIN
    DROP TABLE #TempTable
END

jquery remove "selected" attribute of option?

It's something in the way jQuery translates to IE8, not necessarily the browser itself.

I was able to work around by going old school and breaking out of jQuery for one line:

document.getElementById('myselect').selectedIndex = -1;

jQuery find file extension (from string)

You can use a combination of substring and lastIndexOf

Sample

var fileName = "test.jpg";
var fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1); 

Httpd returning 503 Service Unavailable with mod_proxy for Tomcat 8

On CentOS Linux release 7.5.1804, we were able to make this work by editing /etc/selinux/config and changing the setting of SELINUX like so:

SELINUX=disabled

Change the current directory from a Bash script

Putting the above together, you can make an alias

alias your_cmd=". your_cmd"

if you don't want to write the leading "." each time you want to source your script to the shell environment, or if you simply don't want to remember that must be done for the script to work correctly.

Set date input field's max date to today

I also had same issue .I build it trough this way.I used struts 2 framework.

  <script type="text/javascript">

  $(document).ready(function () {
  var year = (new Date).getFullYear();
  $( "#effectiveDateId" ).datepicker({dateFormat: "mm/dd/yy", maxDate: 
  0});

  });


  </script>

        <s:textfield name="effectiveDate" cssClass="input-large" 
   key="label.warrantRateMappingToPropertyTypeForm.effectiveDate" 
   id="effectiveDateId" required="true"/>

This worked for me.

Concatenate multiple node values in xpath

for $d in $doc/element2/element3 return fn:string-join(fn:data($d/element()), ".").
$doc stores the Xml.

How to convert Integer to int?

Since you say you're using Java 5, you can use setInt with an Integer due to autounboxing: pstmt.setInt(1, tempID) should work just fine. In earlier versions of Java, you would have had to call .intValue() yourself.

The opposite works as well... assigning an int to an Integer will automatically cause the int to be autoboxed using Integer.valueOf(int).

ASP.net vs PHP (What to choose)

This is impossible to answer and has been brought up many many times before. Do a search, read those threads, then pick the framework you and your team have experience with.

How to resize an image to fit in the browser window?

width: 100%;
overflow: hidden;

I believe that should do the trick.

jQuery - Trigger event when an element is removed from the DOM

This is how to create a jQuery live remove listener:

$(document).on('DOMNodeRemoved', function(e)
{
  var $element = $(e.target).find('.element');
  if ($element.length)
  {
    // do anything with $element
  }
});

Or:

$(document).on('DOMNodeRemoved', function(e)
{
  $(e.target).find('.element').each(function()
  {
    // do anything with $(this)
  }
});

MIME types missing in IIS 7 for ASP.NET - 404.17

Fix:

I chose the "ISAPI & CGI Restrictions" after clicking the server name (not the site name) in IIS Manager, and right clicked the "ASP.NET v4.0.30319" lines and chose "Allow".

After turning on ASP.NET from "Programs and Features > Turn Windows features on or off", you must install ASP.NET from the Windows command prompt. The MIME types don't ever show up, but after doing this command, I noticed these extensions showed up under the IIS web site "Handler Mappings" section of IIS Manager.

C:\>cd C:\Windows\Microsoft.NET\Framework64\v4.0.30319

C:\Windows\Microsoft.NET\Framework64\v4.0.30319>dir aspnet_reg*
 Volume in drive C is Windows
 Volume Serial Number is 8EE6-5DD0

 Directory of C:\Windows\Microsoft.NET\Framework64\v4.0.30319

03/18/2010  08:23 PM            19,296 aspnet_regbrowsers.exe
03/18/2010  08:23 PM            36,696 aspnet_regiis.exe
03/18/2010  08:23 PM           102,232 aspnet_regsql.exe
               3 File(s)        158,224 bytes
               0 Dir(s)  34,836,508,672 bytes free

C:\Windows\Microsoft.NET\Framework64\v4.0.30319>aspnet_regiis.exe -i
Start installing ASP.NET (4.0.30319).
.....
Finished installing ASP.NET (4.0.30319).

C:\Windows\Microsoft.NET\Framework64\v4.0.30319>

However, I still got this error. But if you do what I mentioned for the "Fix", this will go away.

HTTP Error 404.2 - Not Found
The page you are requesting cannot be served because of the ISAPI and CGI Restriction list settings on the Web server.

Map enum in JPA with fixed values?

The problem is, I think, that JPA was never incepted with the idea in mind that we could have a complex preexisting Schema already in place.

I think there are two main shortcomings resulting from this, specific to Enum:

  1. The limitation of using name() and ordinal(). Why not just mark a getter with @Id, the way we do with @Entity?
  2. Enum's have usually representation in the database to allow association with all sorts of metadata, including a proper name, a descriptive name, maybe something with localization etc. We need the easy of use of an Enum combined with the flexibility of an Entity.

Help my cause and vote on JPA_SPEC-47

Would this not be more elegant than using a @Converter to solve the problem?

// Note: this code won't work!!
// it is just a sample of how I *would* want it to work!
@Enumerated
public enum Language {
  ENGLISH_US("en-US"),
  ENGLISH_BRITISH("en-BR"),
  FRENCH("fr"),
  FRENCH_CANADIAN("fr-CA");
  @ID
  private String code;
  @Column(name="DESCRIPTION")
  private String description;

  Language(String code) {
    this.code = code;
  }

  public String getCode() {
    return code;
  }

  public String getDescription() {
    return description;
  }
}

How to make full screen background in a web page

its very simple use this css (replace image.jpg with your background image)

body{height:100%;
   width:100%;
   background-image:url(image.jpg);/*your background image*/  
   background-repeat:no-repeat;/*we want to have one single image not a repeated one*/  
   background-size:cover;/*this sets the image to fullscreen covering the whole screen*/  
   /*css hack for ie*/     
   filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.image.jpg',sizingMethod='scale');
   -ms-filter:"progid:DXImageTransform.Microsoft.AlphaImageLoader(src='image.jpg',sizingMethod='scale')";
}

How would I stop a while loop after n amount of time?

Try this module: http://pypi.python.org/pypi/interruptingcow/

from interruptingcow import timeout
try:
    with timeout(60*5, exception=RuntimeError):
        while True:
            test = 0
            if test == 5:
                break
            test = test - 1
except RuntimeError:
    pass

How can I simulate an array variable in MySQL?

Rather than Saving data as a array or in one row only you should be making diffrent rows for every value received. This will make it much simpler to understand rather than putting all together.

How do you underline a text in Android XML?

There are different ways to achieve underlined text in an Android TextView.

1.<u>This is my underlined text</u> or

I just want to underline <u>this</u> word

2.You can do the same programmatically.

`textView.setPaintFlags(textView.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);`

3.It can be done by creating a SpannableString and then setting it as the TextView text property

SpannableString text = new SpannableString("Voglio sottolineare solo questa parola");
text.setSpan(new UnderlineSpan(), 25, 6, 0);
textView.setText(text);

Handlebars.js Else If

in handlebars first register a function like below

Handlebars.registerHelper('ifEquals', function(arg1, arg2, options) {
    return (arg1 == arg2) ? options.fn(this) : options.inverse(this);
});

you can register more than one function . to add another function just add like below

Handlebars.registerHelper('calculate', function(operand1, operator, operand2) {
    let result;
    switch (operator) {
        case '+':
            result = operand1 + operand2;            
            break;
        case '-':
            result = operand1 - operand2;            
            break;
        case '*':
            result = operand1 * operand2;            
            break;
        case '/':
            result = operand1 / operand2;            
            break;
    }

    return Number(result);
});

and in HTML page just include the conditions like

    {{#ifEquals day "mon"}}
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
      //html code goes here
    </html>
   {{else ifEquals day "sun"}}
    <html>
     //html code goes here
    </html>
   {{else}}
     //html code goes here
   {{/ifEquals}}

What does 'wb' mean in this code, using Python?

The wb indicates that the file is opened for writing in binary mode.

When writing in binary mode, Python makes no changes to data as it is written to the file. In text mode (when the b is excluded as in just w or when you specify text mode with wt), however, Python will encode the text based on the default text encoding. Additionally, Python will convert line endings (\n) to whatever the platform-specific line ending is, which would corrupt a binary file like an exe or png file.

Text mode should therefore be used when writing text files (whether using plain text or a text-based format like CSV), while binary mode must be used when writing non-text files like images.

References:

https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files https://docs.python.org/3/library/functions.html#open

is there any PHP function for open page in new tab

Use the target attribute on your anchor tag with the _blank value.

Example:

<a href="http://google.com" target="_blank">Click Me!</a>

Facebook Graph API v2.0+ - /me/friends returns empty, or only friends who also use my application

In v2.0 of the Graph API, calling /me/friends returns the person's friends who also use the app.

In addition, in v2.0, you must request the user_friends permission from each user. user_friends is no longer included by default in every login. Each user must grant the user_friends permission in order to appear in the response to /me/friends. See the Facebook upgrade guide for more detailed information, or review the summary below.

If you want to access a list of non-app-using friends, there are two options:

  1. If you want to let your people tag their friends in stories that they publish to Facebook using your App, you can use the /me/taggable_friends API. Use of this endpoint requires review by Facebook and should only be used for the case where you're rendering a list of friends in order to let the user tag them in a post.

  2. If your App is a Game AND your Game supports Facebook Canvas, you can use the /me/invitable_friends endpoint in order to render a custom invite dialog, then pass the tokens returned by this API to the standard Requests Dialog.

In other cases, apps are no longer able to retrieve the full list of a user's friends (only those friends who have specifically authorized your app using the user_friends permission). This has been confirmed by Facebook as 'by design'.

For apps wanting allow people to invite friends to use an app, you can still use the Send Dialog on Web or the new Message Dialog on iOS and Android.

UPDATE: Facebook have published an FAQ on these changes here: https://developers.facebook.com/docs/apps/faq which explain all the options available to developers in order to invite friends etc.

Exit codes in Python

Operating system commands have exit codes. Look for Linux exit codes to see some material on this. The shell uses the exit codes to decide if the program worked, had problems, or failed. There are some efforts to create standard (or at least commonly-used) exit codes. See this Advanced Shell Script posting.

Web Application Problems (web.config errors) HTTP 500.19 with IIS7.5 and ASP.NET v2

Make sure all of your IIS features are properly enabled.

  • Open Windows Features (Turn Windows features on or off).
  • Scroll down to Internet Information Services

  • Open the World Wide Web plus box drop down

  • Open the Application Development Features plus box drop down
  • Manually check all of the subsequent check boxes, then click ok

enter image description here

Is there a CSS selector for elements containing certain text?

If you don't create the DOM yourself (e.g. in a userscript) you can do the following with pure JS:

_x000D_
_x000D_
for ( td of document.querySelectorAll('td') ) {_x000D_
  console.debug("text:", td, td.innerText)_x000D_
  td.setAttribute('text', td.innerText)_x000D_
}_x000D_
for ( td of document.querySelectorAll('td[text="male"]') )_x000D_
  console.debug("male:", td, td.innerText)
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>Peter</td>_x000D_
    <td>male</td>_x000D_
    <td>34</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Susanne</td>_x000D_
    <td>female</td>_x000D_
    <td>12</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Console output

text: <td> Peter
text: <td> male
text: <td> 34
text: <td> Susanne
text: <td> female
text: <td> 12
male: <td text="male"> male

Regular Expression to reformat a US phone number in Javascript

_x000D_
_x000D_
var x = '301.474.4062';_x000D_
    _x000D_
x = x.replace(/\D+/g, '')_x000D_
     .replace(/(\d{3})(\d{3})(\d{4})/, '($1) $2-$3');_x000D_
_x000D_
alert(x);
_x000D_
_x000D_
_x000D_

How to globally replace a forward slash in a JavaScript string?

This is Christopher Lincolns idea but with correct code:

function replace(str,find,replace){
    if (find != ""){
        str = str.toString();
        var aStr = str.split(find);
        for(var i = 0; i < aStr.length; i++) {
            if (i > 0){
                str = str + replace + aStr[i];
            }else{
                str = aStr[i];
            }
        }
    }
    return str;
}

Example Usage:

var somevariable = replace('//\\\/\/sdfas/\/\/\\\////','\/sdf','replacethis\');

Javascript global string replacement is unecessarily complicated. This function solves that problem. There is probably a small performance impact, but I'm sure its negligable.

Heres an alternative function, looks much cleaner, but is on average about 25 to 20 percent slower than the above function:

function replace(str,find,replace){
    if (find !== ""){
        str = str.toString().split(find).join(replace);
    }
    return str;
}

How to split the filename from a full path in batch?

@echo off
Set filename="C:\Documents and Settings\All Users\Desktop\Dostips.cmd"
call :expand %filename%
:expand
set filename=%~nx1
echo The name of the file is %filename%
set folder=%~dp1
echo It's path is %folder%

How to set Navigation Drawer to be opened from right to left

the main issue with the following error:

no drawer view found with absolute gravity LEFT

is that, you defined the

android:layout_gravity="right"

for list-view in right, but try to open the drawer from left, by calling this function:

mDrawerToggle.syncState();

and clicking on hamburger icon!

just comment the above function and try to handle open/close of menu like @Rudi said!

How to pass a vector to a function?

found = binarySearch(first, last, search4, &random);

Notice the &.

How to replace existing value of ArrayList element in Java

If you are unaware of the position to replace, use list iterator to find and replace element ListIterator.set(E e)

ListIterator<String> iterator = list.listIterator();
while (iterator.hasNext()) {
     String next = iterator.next();
     if (next.equals("Two")) {
         //Replace element
         iterator.set("New");
     }
 }

How to do parallel programming in Python?

This can be done very elegantly with Ray.

To parallelize your example, you'd need to define your functions with the @ray.remote decorator, and then invoke them with .remote.

import ray

ray.init()

# Define the functions.

@ray.remote
def solve1(a):
    return 1

@ray.remote
def solve2(b):
    return 2

# Start two tasks in the background.
x_id = solve1.remote(0)
y_id = solve2.remote(1)

# Block until the tasks are done and get the results.
x, y = ray.get([x_id, y_id])

There are a number of advantages of this over the multiprocessing module.

  1. The same code will run on a multicore machine as well as a cluster of machines.
  2. Processes share data efficiently through shared memory and zero-copy serialization.
  3. Error messages are propagated nicely.
  4. These function calls can be composed together, e.g.,

    @ray.remote
    def f(x):
        return x + 1
    
    x_id = f.remote(1)
    y_id = f.remote(x_id)
    z_id = f.remote(y_id)
    ray.get(z_id)  # returns 4
    
  5. In addition to invoking functions remotely, classes can be instantiated remotely as actors.

Note that Ray is a framework I've been helping develop.

MD5 is 128 bits but why is it 32 characters?

Those are hexidecimal digits, not characters. One digit = 4 bits.

How to get file_get_contents() to work with HTTPS?

To allow https wrapper:

  • the php_openssl extension must exist and be enabled
  • allow_url_fopen must be set to on

In the php.ini file you should add this lines if not exists:

extension=php_openssl.dll

allow_url_fopen = On

How to zoom in/out an UIImage object when user pinches screen?

Here is a solution I've used before that does not require you to use the UIWebView.

- (UIImage *)scaleAndRotateImage(UIImage *)image
{
    int kMaxResolution = 320; // Or whatever

    CGImageRef imgRef = image.CGImage;

    CGFloat width = CGImageGetWidth(imgRef);
    CGFloat height = CGImageGetHeight(imgRef);


    CGAffineTransform transform = CGAffineTransformIdentity;
    CGRect bounds = CGRectMake(0, 0, width, height);
    if (width > kMaxResolution || height > kMaxResolution) {
        CGFloat ratio = width/height;
        if (ratio > 1) {
            bounds.size.width = kMaxResolution;
            bounds.size.height = bounds.size.width / ratio;
        }
        else {
            bounds.size.height = kMaxResolution;
            bounds.size.width = bounds.size.height * ratio;
        }
    }

    CGFloat scaleRatio = bounds.size.width / width;
    CGSize imageSize = CGSizeMake(CGImageGetWidth(imgRef), CGImageGetHeight(imgRef));
    CGFloat boundHeight;
    UIImageOrientation orient = image.imageOrientation;
    switch(orient) {

        case UIImageOrientationUp: //EXIF = 1
            transform = CGAffineTransformIdentity;
            break;

        case UIImageOrientationUpMirrored: //EXIF = 2
            transform = CGAffineTransformMakeTranslation(imageSize.width, 0.0);
            transform = CGAffineTransformScale(transform, -1.0, 1.0);
            break;

        case UIImageOrientationDown: //EXIF = 3
            transform = CGAffineTransformMakeTranslation(imageSize.width, imageSize.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;

        case UIImageOrientationDownMirrored: //EXIF = 4
            transform = CGAffineTransformMakeTranslation(0.0, imageSize.height);
            transform = CGAffineTransformScale(transform, 1.0, -1.0);
            break;

        case UIImageOrientationLeftMirrored: //EXIF = 5
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeTranslation(imageSize.height, imageSize.width);
            transform = CGAffineTransformScale(transform, -1.0, 1.0);
            transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
            break;

        case UIImageOrientationLeft: //EXIF = 6
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeTranslation(0.0, imageSize.width);
            transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
            break;

        case UIImageOrientationRightMirrored: //EXIF = 7
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeScale(-1.0, 1.0);
            transform = CGAffineTransformRotate(transform, M_PI / 2.0);
            break;

        case UIImageOrientationRight: //EXIF = 8
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeTranslation(imageSize.height, 0.0);
            transform = CGAffineTransformRotate(transform, M_PI / 2.0);
            break;

        default:
            [NSException raise:NSInternalInconsistencyException format:@"Invalid image orientation"];

    }

    UIGraphicsBeginImageContext(bounds.size);

    CGContextRef context = UIGraphicsGetCurrentContext();

    if (orient == UIImageOrientationRight || orient == UIImageOrientationLeft) {
        CGContextScaleCTM(context, -scaleRatio, scaleRatio);
        CGContextTranslateCTM(context, -height, 0);
    }
    else {
        CGContextScaleCTM(context, scaleRatio, -scaleRatio);
        CGContextTranslateCTM(context, 0, -height);
    }

    CGContextConcatCTM(context, transform);

    CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, width, height), imgRef);
    UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return imageCopy;
}

The article can be found on Apple Support at: http://discussions.apple.com/message.jspa?messageID=7276709#7276709

Can You Get A Users Local LAN IP Address Via JavaScript?

As it turns out, the recent WebRTC extension of HTML5 allows javascript to query the local client IP address. A proof of concept is available here: http://net.ipcalf.com

This feature is apparently by design, and is not a bug. However, given its controversial nature, I would be cautious about relying on this behaviour. Nevertheless, I think it perfectly and appropriately addresses your intended purpose (revealing to the user what their browser is leaking).

What is the Python equivalent of Matlab's tic and toc functions?

The absolute best analog of tic and toc would be to simply define them in python.

def tic():
    #Homemade version of matlab tic and toc functions
    import time
    global startTime_for_tictoc
    startTime_for_tictoc = time.time()

def toc():
    import time
    if 'startTime_for_tictoc' in globals():
        print "Elapsed time is " + str(time.time() - startTime_for_tictoc) + " seconds."
    else:
        print "Toc: start time not set"

Then you can use them as:

tic()
# do stuff
toc()

Loop through a comma-separated shell variable

Another solution not using IFS and still preserving the spaces:

$ var="a bc,def,ghij"
$ while read line; do echo line="$line"; done < <(echo "$var" | tr ',' '\n')
line=a bc
line=def
line=ghij

Change values of select box of "show 10 entries" of jquery datatable

enter image description here pageLength: 50,

worked for me Thanks

Versions for reference

jquery-3.3.1.js

/1.10.19/js/jquery.dataTables.min.js

/buttons/1.5.2/js/dataTables.buttons.min.js

html vertical align the text inside input type button

If your button weren't floated, you could use vertical-align:middle; to center the text inside it. After lots of experimentation, this was the only solution I could find that worked in IE without changing markup. (in Chrome, button text seems to be automatically centered without this hack).

But you use a float:left which forces the element to be a block element (your display:inline-block is ignored), whcih in turn prevents vertical-align from working because vertical-align doesn't work inside a block element.

So you have three choices:

  • stop using floats in this form, and use inline and inline-block elements to simulate floating.
  • as @stefan notes above, use another element like an <a> and use javascript to submit the form.
  • accept that in IE your buttons will be off by 1px vertically.

What's the difference between window.location and document.location in JavaScript?

window.location is the more reliably consistent of the two, considering older browsers.

int value under 10 convert to string two digit number

The accepted answer is good and fast:

i.ToString("00")

or

i.ToString("000")

If you need more complexity, String.Format is worth a try:

var str1 = "";
var str2 = "";
for (int i = 1; i < 100; i++)
{
    str1 = String.Format("{0:00}", i);
    str2 = String.Format("{0:000}", i);
}

For the i = 10 case:

str1: "10"
str2: "010"

I use this, for example, to clear the text on particular Label Controls on my form by name:

private void EmptyLabelArray()
{
    var fmt = "Label_Row{0:00}_Col{0:00}";
    for (var rowIndex = 0; rowIndex < 100; rowIndex++)
    {
        for (var colIndex = 0; colIndex < 100; colIndex++)
        {
            var lblName = String.Format(fmt, rowIndex, colIndex);
            foreach (var ctrl in this.Controls)
            {
                var lbl = ctrl as Label;
                if ((lbl != null) && (lbl.Name == lblName))
                {
                    lbl.Text = null;
                }
            }
        }
    }
}

Access host database from a docker container

From Docker 17.06 onwards, a special Mac-only DNS name is available in docker containers that resolves to the IP address of the host. It is:

docker.for.mac.localhost

The documentation is here: https://docs.docker.com/docker-for-mac/networking/#httphttps-proxy-support

How to enable local network users to access my WAMP sites?

You must have the Apache process (httpd.exe) allowed through firewall (recommended).

Or disable your firewall on LAN (just to test, not recommended).

Example with Wamp (with Apache activated):

  1. Check if Wamp is published locally if it is, continue;
  2. Access Control Panel
  3. Click "Firewall"
  4. Click "Allow app through firewall"
  5. Click "Allow some app"
  6. Find and choose C:/wamp64/bin/apache2/bin/httpd.exe
  7. Restart Wamp

Now open the browser in another host of your network and access your Apache server by IP (e.g. 192.168.0.5). You can discover your local host IP by typing ipconfig on your command prompt.

It works

Navigation bar show/hide

Here is a very quick and simple solution:

self.navigationController.hidesBarsOnTap = YES;

This will work on single tap instead of double tap. Also it will change the behavior for the navigation controller even after pushing or popping the current view controller.

You can always modify this behavior in your controller within the viewWillAppear: and viewWillDisappear: actions if you would like to set the behavior only for a single view controller.

Here is the documentation:

Why can a function modify some arguments as perceived by the caller, but not others?

Python is copy by value of reference. An object occupies a field in memory, and a reference is associated with that object, but itself occupies a field in memory. And name/value is associated with a reference. In python function, it always copy the value of the reference, so in your code, n is copied to be a new name, when you assign that, it has a new space in caller stack. But for the list, the name also got copied, but it refer to the same memory(since you never assign the list a new value). That is a magic in python!

What are the differences between C, C# and C++ in terms of real-world applications?

For raw speed, use C. For power, use C++. For .NET compatibility, use C#.

They're all pretty complex as languages go; C through decades of gradual accretion, C++ through years of more rapid enhancement, and C# through the power of Microsoft.

MySQL error 1241: Operand should contain 1 column(s)

Just remove the ( and the ) on your SELECT statement:

insert into table2 (Name, Subject, student_id, result)
select Name, Subject, student_id, result
from table1;

Nested Recycler view height doesn't wrap its content

This answer is based on the solution given by Denis Nek. It solves the problem of not taking decorations like dividers into account.

public class WrappingRecyclerViewLayoutManager extends LinearLayoutManager {

public WrappingRecyclerViewLayoutManager(Context context)    {
    super(context, VERTICAL, false);
}

public WrappingRecyclerViewLayoutManager(Context context, int orientation, boolean reverseLayout)    {
    super(context, orientation, reverseLayout);
}

private int[] mMeasuredDimension = new int[2];

@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {
    final int widthMode = View.MeasureSpec.getMode(widthSpec);
    final int heightMode = View.MeasureSpec.getMode(heightSpec);
    final int widthSize = View.MeasureSpec.getSize(widthSpec);
    final int heightSize = View.MeasureSpec.getSize(heightSpec);
    int width = 0;
    int height = 0;
    for (int i = 0; i < getItemCount(); i++) {
        measureScrapChild(recycler, i,
                View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
                mMeasuredDimension);
        if (getOrientation() == HORIZONTAL) {
            width = width + mMeasuredDimension[0];
            if (i == 0) {
                height = mMeasuredDimension[1];
            }
        } else {
            height = height + mMeasuredDimension[1];
            if (i == 0) {
                width = mMeasuredDimension[0];
            }
        }
    }
    switch (widthMode) {
        case View.MeasureSpec.EXACTLY:
            width = widthSize;
        case View.MeasureSpec.AT_MOST:
        case View.MeasureSpec.UNSPECIFIED:
    }

    switch (heightMode) {
        case View.MeasureSpec.EXACTLY:
            height = heightSize;
        case View.MeasureSpec.AT_MOST:
        case View.MeasureSpec.UNSPECIFIED:
    }

    setMeasuredDimension(width, height);
}

private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec, int heightSpec, int[] measuredDimension) {
    View view = recycler.getViewForPosition(position);
    if (view != null) {
        RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
        int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec, getPaddingLeft() + getPaddingRight(), p.width);
        int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec, getPaddingTop() + getPaddingBottom(), p.height);
        view.measure(childWidthSpec, childHeightSpec);
        Rect outRect = new Rect();
        calculateItemDecorationsForChild(view, outRect);
        measuredDimension[0] = view.getMeasuredWidth() + p.leftMargin + p.rightMargin;
        measuredDimension[1] = view.getMeasuredHeight() + p.bottomMargin + p.topMargin + outRect.bottom + outRect.top;
        recycler.recycleView(view);
    }
}

}

How do I select child elements of any depth using XPath?

//form/descendant::input[@type='submit']

Display A Popup Only Once Per User

The code to show only one time the popup (Bootstrap Modal in the case) :

modal.js

 $(document).ready(function() {
     if (Cookies('pop') == null) {
         $('#ModalIdName').modal('show');
         Cookies('pop', '365');
     }
 });

Here is the full code snipet for Rails :

Add the script above to your js repo (in Rails : app/javascript/packs)

In Rails we have a specific packing way for script, so :

  1. Download the js-cookie plugin (needed to work with Javascript Cokkies) https://github.com/js-cookie/js-cookie (the name should be : 'js.cookie.js')

    /*!
     * JavaScript Cookie v2.2.0
     * https://github.com/js-cookie/js-cookie
     *
     * Copyright 2006, 2015 Klaus Hartl & Fagner Brack
     * Released under the MIT license
     */
    ;(function (factory) {
      var registeredInModuleLoader = false;
      if (typeof define === 'function' && define.amd) {
        define(factory);
        registeredInModul
     ...
    
  2. Add //= require js.cookie to application.js

It will works perfectly for 365 days!

git add, commit and push commands in one?

While I agree with Wayne Werner on his doubts, this is technically an option:

git config alias.acp '! git commit -a -m "commit" && git push'

Which defines an alias that runs commit and push. Use it as git acp. Please be aware that such "shell" aliases are always run from the root of your git repository.

Another option might be to write a post-commit hook that does the push.

Oh, by the way, you indeed can pass arguments to shell aliases. If you want to pass a custom commit message, instead use:

git config alias.acp '! acp() { git commit -a -m "$1" && git push ; } ; acp'

(Of course, now, you will need to give a commit message: git acp "My message goes here!")

How to calculate the IP range when the IP address and the netmask is given?

Input: 192.168.0.1/25

The mask is this part: /25

To find the network address do the following:

  • Subtract the mask from the ip length (32 - mask) = 32 - 25 = 7 and take those bits from the right

  • In the given ip address I.e: 192.168.0.1 in binary is: 11111111 11111111 00000000 00000001 Now, taking 7 bits from right '0' 1111111 11111111 00000000 00000000 Which in decimal is: 192.168.0.0 (this is the network address)

To find first valid/usable ip address add +1 to network address I.e: 192.168.0.1

To find the last/broadcast address the procedure is same as that of finding network address but here you have to make (32-mask) bits from right to '1'

I.e: 11111111 11111111 00000000 01111111 Which in decimal is 192.168.0.127

To find the last valid/usable ip address subtract 1 from the broadcast address I.e: 192.168.0.126

Explicitly set column value to null SQL Developer

Use Shift+Del.

More info: Shift+Del combination key set a field to null when you filled a field by a value and you changed your decision and you want to make it null. It is useful and I amazed from the other answers that give strange solutions.