Programs & Examples On #Cfpdf

how can I login anonymously with ftp (/usr/bin/ftp)?

Anonymous FTP usage is covered by RFC 1635: How to Use Anonymous FTP:

What is Anonymous FTP?

Anonymous FTP is a means by which archive sites allow general access to their archives of information. These sites create a special account called "anonymous".

Traditionally, this special anonymous user account accepts any string as a password, although it is common to use either the password "guest" or one's electronic mail (e-mail) address. Some archive sites now explicitly ask for the user's e-mail address and will not allow login with the "guest" password. Providing an e-mail address is a courtesy that allows archive site operators to get some idea of who is using their services.

These are general recommendations, though. Each FTP server may have its own guidelines.

For sample use of the ftp command on anonymous FTP access, see appendix A:

atlas.arc.nasa.gov% ftp naic.nasa.gov
Connected to naic.nasa.gov.
220 naic.nasa.gov FTP server (Wed May 4 12:15:15 PDT 1994) ready.
Name (naic.nasa.gov:amarine): anonymous
331 Guest login ok, send your complete e-mail address as password.
Password:
230-----------------------------------------------------------------
230-Welcome to the NASA Network Applications and Info Center Archive
230-
230-     Access to NAIC's online services is also available through:
230-
230-        Gopher         - naic.nasa.gov (port 70)
230-    World-Wide-Web - http://naic.nasa.gov/naic/naic-home.html
230-
230-        If you experience any problems please send email to
230-
230-                    [email protected]
230-
230-                 or call +1 (800) 858-9947
230-----------------------------------------------------------------
230-
230-Please read the file README
230-  it was last modified on Fri Dec 10 13:06:33 1993 - 165 days ago
230 Guest login ok, access restrictions apply.
ftp> cd files/rfc
250-Please read the file README.rfc
250-  it was last modified on Fri Jul 30 16:47:29 1993 - 298 days ago
250 CWD command successful.
ftp> get rfc959.txt
200 PORT command successful.
150 Opening ASCII mode data connection for rfc959.txt (147316 bytes).
226 Transfer complete.
local: rfc959.txt remote: rfc959.txt
151249 bytes received in 0.9 seconds (1.6e+02 Kbytes/s)
ftp> quit
221 Goodbye.
atlas.arc.nasa.gov%

See also the example session at the University of Edinburgh site.

jQuery to loop through elements with the same class

You could use the jQuery $each method to loop through all the elements with class testimonial. i => is the index of the element in collection and val gives you the object of that particular element and you can use "val" to further access the properties of your element and check your condition.

$.each($('.testimonal'), function(i, val) { 
    if(your condition){
       //your action
    }
});

How to create a 100% screen width div inside a container in bootstrap?

The reason why your full-width-div doesn't stretch 100% to your screen it's because of its parent "container" which occupies only about 80% of the screen.

If you want to make it stretch 100% to the screen either you make the "full-width-div" position fixed or use the "container-fluid" class instead of "container".

see Bootstrap 3 docs: http://getbootstrap.com/css/#grid

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

The answer from Alexander refers to complete docs...

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

Is it possible to install Xcode 10.2 on High Sierra (10.13.6)?

You don't need to run Xcode 10.2 for iOS 12.2 support. You just need access to the appropriate folder in DeviceSupport.

A possible solution is

  • Download Xcode 10.2 from a direkt link (not from App Store).
  • Rename it for example to Xcode102.
  • Put it into /Applications. It's possible to have multiple Xcode versions in the same directory.
  • Create a symbolic link in Terminal.app to have access to the 12.2 device support folder in Xcode 10.2

    ln -s /Applications/Xcode102.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/12.2\ \(16E226\) /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport
    

You can move Xcode 10.2 to somewhere else but then you have to adjust the path.

Now Xcode 10.1 supports devices running iOS 12.2

how to open Jupyter notebook in chrome on windows

In the windows when we open jupyter notebook in command prompt we can see the instructions in first 10 lines in that there is one instruction- "to open notebook, open this file in browser file://C:/Users/{username}/appdata/roaming/jupyetr/runtime/nbserver-xywz-open.html " , open this html with browser of your choice.

How to call Stored Procedures with EntityFramework?

Basically you just have to map the procedure to the entity using Stored Procedure Mapping.

Once mapped, you use the regular method for adding an item in EF, and it will use your stored procedure instead.

Please see: This Link for a walkthrough. The result will be adding an entity like so (which will actually use your stored procedure)

using (var ctx = new SchoolDBEntities())
        {
            Student stud = new Student();
            stud.StudentName = "New sp student";
            stud.StandardId = 262;

            ctx.Students.Add(stud);
            ctx.SaveChanges();
        }

How to filter a dictionary according to an arbitrary condition function?

dict((k, v) for k, v in points.items() if all(x < 5 for x in v))

You could choose to call .iteritems() instead of .items() if you're in Python 2 and points may have a lot of entries.

all(x < 5 for x in v) may be overkill if you know for sure each point will always be 2D only (in that case you might express the same constraint with an and) but it will work fine;-).

"commence before first target. Stop." error

It's a simple Mistake while adding a new file you just have to make sure that \ is added to the file before and the new file remain as it is eg.

Check Out what to do if i want to add a new file named customer.cc

Mixing a PHP variable with a string literal

Example:

$test = "chees";
"${test}y";

It will output:

cheesy

It is exactly what you are looking for.

Add all files to a commit except a single file?

Try this:

git checkout -- main/dontcheckmein.txt

Spring Boot Java Config Set Session Timeout

  • Spring Boot version 1.0: server.session.timeout=1200
  • Spring Boot version 2.0: server.servlet.session.timeout=10m
    NOTE: If a duration suffix is not specified, seconds will be used.

json.net has key method?

Just use x["error_msg"]. If the property doesn't exist, it returns null.

Slide up/down effect with ng-show and ng-animate

This is actually pretty easy to do. All you have to do is change the css.

Here's a fiddle with a very simple fade animation: http://jsfiddle.net/elthrasher/sNpjH/

To make it into a sliding animation, I first had to put my element in a box (that's the slide-container), then I added another element to replace the one that was leaving, just because I thought it would look nice. Take it out and the example will still work.

I changed the animation css from 'fade' to 'slide' but please note that these are the names I gave it. I could have written slide animation css named 'fade' or anything else for that matter.

The important part is what's in the css. Here's the original 'fade' css:

.fade-hide, .fade-show {
    -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
    -moz-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
    -o-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
    transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
}
.fade-hide {
    opacity:1;
}
.fade-hide.fade-hide-active {
    opacity:0;
}
.fade-show {
    opacity:0;
}
.fade-show.fade-show-active {
    opacity:1;
}

This code changes the opacity of the element from 0 (completely transparent) to 1 (completely opaque) and back again. The solution is to leave opacity alone and instead change the top (or left, if you want to move left-right).

.slide-hide, .slide-show {
    -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s;
    -moz-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s;
    -o-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s;
    transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s;
}
.slide-hide {
    position: relative;
    top: 0;
}
.slide-hide.slide-hide-active {
    position: absolute;
    top: -100px;
}
.slide-show {
    position: absolute;
    top: 100px;
}
.slide-show.slide-show-active {
    position: relative;
    top: 0px;
}

I'm also changing from relative to absolute positioning so only one of the elements takes up space in the container at a time.

Here's the finished product: http://jsfiddle.net/elthrasher/Uz2Dk/. Hope this helps!

Python pip install module is not found. How to link python to pip location?

For the sake of anyone also using visual studio from a windows environment:

I realized that I could see my module installed when i ran pip install

py pip install [moduleName] 
py pip list

However debugging in visual studio was getting "module not found". Oddly, i was successfully running import [moduleName] when i ran the interpreter in powershell.

Reason:

visual studio was using the wrong interpreter at: C:\Users\[username]\AppData\Local\Programs\Python\Python37\

What I REALLY wanted was visual studio to use the virtualenv that i setup for my project. To do this, right click Python Environments in "solution explorer", select Add Virtual Environment..., and then select the folder where you created your virtual environment. enter image description here Then, under project settings, under the General tab, select your virtual environment in the dropdown.

enter image description here

Now visual studio should be using the same interpreter and everything should play nice!

How can I execute a python script from an html button?

I've done exactly this on Windows. I have a local .html page that I use as a "dashboard" for all my current work. In addition to the usual links, I've been able to add clickable links that open MS-Word documents, Excel spreadsheets, open my IDE, ssh to servers, etc. It is a little involved but here's how I did it ...

First, update the Windows registry. Your browser handles usual protocols like http, https, ftp. You can define your own protocol and a handler to be invoked when a link of that protocol-type is clicked. Here's the config (run with regedit)

[HKEY_CLASSES_ROOT\mydb]
@="URL:MyDB Document"
"URL Protocol"=""

[HKEY_CLASSES_ROOT\mydb\shell]
@="open"

[HKEY_CLASSES_ROOT\mydb\shell\open]

[HKEY_CLASSES_ROOT\mydb\shell\open\command]
@="wscript C:\_opt\Dashboard\Dashboard.vbs \"%1\""

With this, when I have a link like <a href="mydb:open:ProjectX.docx">ProjectX</a>, clicking it will invoke C:\_opt\Dashboard\Dashboard.vbs passing it the command line parameter open:ProjectX.docx. My VBS code looks at this parameter and does the necessary thing (in this case, because it ends in .docx, it invokes MS-Word with ProjectX.docx as the parameter to it.

Now, I've written my handler in VBS only because it is very old code (like 15+ years). I haven't tried it, but you might be able to write a Python handler, Dashboard.py, instead. I'll leave it up to you to write your own handler. For your scripts, your link could be href="mydb:runpy:whatever.py" (the runpy: prefix tells your handle to run with Python).

Can't use Swift classes inside Objective-C

XCode 11.3.1:

When I want to use an Swift inner class in a objc code, it does not compile for ther error "undefined symbol"(for bother inner class and outer class), I checked the generated "-swift.h" header and both classes are there.

After trying for hours I convert the inner class to a normal class and it compiles.

I clean the project, delete the DerivedData folder and it compiles.

Merge r brings error "'by' must specify uniquely valid columns"

This is what I tried for a right outer join [as per my requirement]:

m1 <- merge(x=companies, y=rounds2, by.x=companies$permalink, 
            by.y=rounds2$company_permalink, all.y=TRUE)
# Error in fix.by(by.x, x) : 'by' must specify uniquely valid columns
m1 <- merge(x=companies, y=rounds2, by.x=c("permalink"), 
            by.y=c("company_permalink"), all.y=TRUE)

This worked.

Counting number of occurrences in column?

=arrayformula(if(isblank(B2:B),iferror(1/0),mmult(sign(B2:B=TRANSPOSE(A2:A)),A2:A)))

I got this from a good tutorial - can't remember the title - probably about using MMult

Is there a Python equivalent to Ruby's string interpolation?

Since Python 2.6.X you might want to use:

"my {0} string: {1}".format("cool", "Hello there!")

How do I copy an entire directory of files into an existing directory using Python?

Here is my version of the same task::

import os, glob, shutil

def make_dir(path):
    if not os.path.isdir(path):
        os.mkdir(path)


def copy_dir(source_item, destination_item):
    if os.path.isdir(source_item):
        make_dir(destination_item)
        sub_items = glob.glob(source_item + '/*')
        for sub_item in sub_items:
            copy_dir(sub_item, destination_item + '/' + sub_item.split('/')[-1])
    else:
        shutil.copy(source_item, destination_item)

Is there a real solution to debug cordova apps

Just want to add that you can debug android apps using Genymotion. It's WAY faster then the stock android emulator.

How to display a content in two-column layout in LaTeX?

Use two minipages.

\begin{minipage}[position]{width}
  text
 \end{minipage}

pandas: find percentile stats of a given column

assume series s

s = pd.Series(np.arange(100))

Get quantiles for [.1, .2, .3, .4, .5, .6, .7, .8, .9]

s.quantile(np.linspace(.1, 1, 9, 0))

0.1     9.9
0.2    19.8
0.3    29.7
0.4    39.6
0.5    49.5
0.6    59.4
0.7    69.3
0.8    79.2
0.9    89.1
dtype: float64

OR

s.quantile(np.linspace(.1, 1, 9, 0), 'lower')

0.1     9
0.2    19
0.3    29
0.4    39
0.5    49
0.6    59
0.7    69
0.8    79
0.9    89
dtype: int32

What uses are there for "placement new"?

I've seen it used as a slight performance hack for a "dynamic type" pointer (in the section "Under the Hood"):

But here is the tricky trick I used to get fast performance for small types: if the value being held can fit inside of a void*, I don't actually bother allocating a new object, I force it into the pointer itself using placement new.

How do I find the length of an array?

A good solution that uses generics:

template <typename T,unsigned S>
inline unsigned arraysize(const T (&v)[S]) { return S; }

Then simply call arraysize(_Array); to get the length of the array.

Source

Vue is not defined

Sometimes the problem may be if you import that like this:

const Vue = window.vue;

this may overwrite the original Vue reference.

Display all dataframe columns in a Jupyter Python Notebook

I recommend setting the display options inside a context manager so that it only affects a single output. I usually prefer "pretty" html-output, and define a function force_show_all(df) for displaying the DataFrame df:

from IPython.core.display import display, HTML

def force_show_all(df):
    with pd.option_context('display.max_rows', None, 'display.max_columns', None, 'display.width', None):
        display(HTML(df.to_html()))

# ... now when you're ready to fully display df:
force_show_all(df)

As others have mentioned, please be cautious to only call this on a reasonably-sized dataframe.

How to pass a user / password in ansible command

As mentioned before you can use --extra-vars (-e) , but instead of specifying the pwd on the commandline so it doesn't end up in the history files you can save it to an environment variable. This way it also goes away when you close the session.

read -s PASS
ansible windows -i hosts -m win_ping -e "ansible_password=$PASS"

How to determine whether a Pandas Column contains a particular value

Or use Series.tolist or Series.any:

>>> s = pd.Series(list('abc'))
>>> s
0    a
1    b
2    c
dtype: object
>>> 'a' in s.tolist()
True
>>> (s=='a').any()
True

Series.tolist makes a list about of a Series, and the other one i am just getting a boolean Series from a regular Series, then checking if there are any Trues in the boolean Series.

Javascript objects: get parent

No. There is no way of knowing which object it came from.

s and obj.subObj both simply have references to the same object.

You could also do:

var obj = { subObj: {foo: 'hello world'} };
var obj2 = {};
obj2.subObj = obj.subObj;
var s = obj.subObj;

You now have three references, obj.subObj, obj2.subObj, and s, to the same object. None of them is special.

Regex to get NUMBER only from String

The answers above are great. If you are in need of parsing all numbers out of a string that are nonconsecutive then the following may be of some help:

string input = "1-205-330-2342";
string result = Regex.Replace(input, @"[^\d]", "");
Console.WriteLine(result); // >> 12053302342

Visual Studio Code Automatic Imports

2018 now. You don't need any extensions for auto-imports in Javascript (as long as you have checkjs: true in your jsconfig.json file) and TypeScript.

There are two types of auto imports: the add missing import quick fix which shows up as a lightbulb on errors:

enter image description here

And the auto import suggestions. These show up a suggestion items as you type. Accepting an auto import suggestion automatically adds the import at the top of the file

enter image description here

Both should work out of the box with JavaScript and TypeScript. If auto imports still do not work for you, please open an issue

Responsive width Facebook Page Plugin

Like others, I've found that the plugin can be made (via JS) to shrink when the container shrinks, but afterwards will not grow when it expands.

The issue is that the original FB.XFBML.parse() creates a set of child nodes with fixed styles in the document tree, and later invocations will not properly clean out the old nodes. If you do it yourself in your code, all is well.

Facebook HTML (I merely added ID elements to what Facebook provided, to avoid any selector accidents):

<div id="divFacebookFeed" class="fb-page" data-href="..." ...>
    <blockquote id="bqNoFeed" cite="(your URL)" class="fb-xfbml-parse-ignore">
        <a href="(your URL)">Your Site</a>
    </blockquote>
</div>

...JQuery code to resize the widget to 500px and preserve the inner fallback element:

var bq = $('#bqNoFeed').detach();
var fbdiv = $('#divFacebookFeed');

fbdiv.attr('data-width', 500);
fbdiv.empty();
fbdiv.append(bq);
FB.XFBML.parse();

How can javascript upload a blob?

Try this

var fd = new FormData();
fd.append('fname', 'test.wav');
fd.append('data', soundBlob);
$.ajax({
    type: 'POST',
    url: '/upload.php',
    data: fd,
    processData: false,
    contentType: false
}).done(function(data) {
       console.log(data);
});

You need to use the FormData API and set the jQuery.ajax's processData and contentType to false.

hide div tag on mobile view only?

The solution given didn't work for me on the desktop, it just showed both divs, although the mobile only showed the mobile div. So I did a little search and found the min-width option. I updated my code to the following and it works fine now :)

CSS:

    @media all and (min-width: 480px) {
    .deskContent {display:block;}
    .phoneContent {display:none;}
}

@media all and (max-width: 479px) {
    .deskContent {display:none;}
    .phoneContent {display:block;}
}

HTML:

<div class="deskContent">Content for desktop</div>
<div class="phoneContent">Content for mobile</div>

NULL value for int in Update statement

By using NULL without any quotes.

UPDATE `tablename` SET `fieldName` = NULL;

How to get JSON from URL in JavaScript?

With Chrome, Firefox, Safari, Edge, and Webview you can natively use the fetch API which makes this a lot easier, and much more terse.

If you need support for IE or older browsers, you can also use the fetch polyfill.

let url = 'https://example.com';

fetch(url)
.then(res => res.json())
.then((out) => {
  console.log('Checkout this JSON! ', out);
})
.catch(err => { throw err });

MDN: Fetch API

Even though Node.js does not have this method built-in, you can use node-fetch which allows for the exact same implementation.

How to extract numbers from string in c?

Make a state machine that operates on one basic principle: is the current character a number.

  • When transitioning from non-digit to digit, you initialize your current_number := number.
  • when transitioning from digit to digit, you "shift" the new digit in:
    current_number := current_number * 10 + number;
  • when transitioning from digit to non-digit, you output the current_number
  • when from non-digit to non-digit, you do nothing.

Optimizations are possible.

Is there any way to have a fieldset width only be as wide as the controls in them?

Use display: inline-block, though you need to wrap it inside a DIV to keep it from actually displaying inline. Tested in Safari.

<style type="text/css">
    .fieldset-auto-width {
         display: inline-block;
    }
</style>
<div>
  <fieldset class="fieldset-auto-width">
      <legend>Blah</legend>
      ...
  </fieldset>
</div>

How to style dt and dd so they are on the same line?

_x000D_
_x000D_
dl {_x000D_
  width: 100%;_x000D_
  overflow: hidden;_x000D_
  background: #ff0;_x000D_
  padding: 0;_x000D_
  margin: 0_x000D_
}_x000D_
dt {_x000D_
  float: left;_x000D_
  width: 50%;_x000D_
  /* adjust the width; make sure the total of both is 100% */_x000D_
  background: #cc0;_x000D_
  padding: 0;_x000D_
  margin: 0_x000D_
}_x000D_
dd {_x000D_
  float: left;_x000D_
  width: 50%;_x000D_
  /* adjust the width; make sure the total of both is 100% */_x000D_
  background: #dd0_x000D_
  padding: 0;_x000D_
  margin: 0_x000D_
}
_x000D_
<dl>_x000D_
  <dt>Mercury</dt>_x000D_
  <dd>Mercury (0.4 AU from the Sun) is the closest planet to the Sun and the smallest planet.</dd>_x000D_
  <dt>Venus</dt>_x000D_
  <dd>Venus (0.7 AU) is close in size to Earth, (0.815 Earth masses) and like Earth, has a thick silicate mantle around an iron core.</dd>_x000D_
  <dt>Earth</dt>_x000D_
  <dd>Earth (1 AU) is the largest and densest of the inner planets, the only one known to have current geological activity.</dd>_x000D_
</dl>
_x000D_
_x000D_
_x000D_

Node.js Hostname/IP doesn't match certificate's altnames

A slightly updated answer (since I ran into this problem in different circumstances.)

When you connect to a server using SSL, the first thing the server does is present a certificate which says "I am api.dropbox.com." The certificate has a "subject" and the subject has a "CN" (short for "common name".) The certificate may also have one or more "subjectAltNames". When node.js connects to a server, node.js fetches this certificate, and then verifies that the domain name it thinks it's connecting to (api.dropbox.com) matches either the subject's CN or one of the altnames. Note that, in node 0.10.x, if you connect using an IP, the IP address has to be in the altnames - node.js will not try to verify the IP against the CN.

Setting the rejectUnauthorized flag to false will get around this check, but first of all if the server is giving you different credentials than you are expecting, something fishy is going on, and second this will also bypass other checks - it's not a good idea if you're connecting over the Internet.

If you are using node >= 0.11.x, you can also specify a checkServerIdentity: function(host, cert) function to the tls module, which should return undefined if you want to allow the connection and throw an exception otherwise (although I don't know if request will proxy this flag through to tls for you.) It can be handy to declare such a function and console.log(host, cert); to figure out what the heck is going on.

How to call a method in another class of the same package?

By calling method

public class a 
{
    void sum(int i,int k)
    {
        System.out.println("THe sum of the number="+(i+k));
    }
}
class b
{
    public static void main(String[] args)
    {
        a vc=new a();
        vc.sum(10 , 20);
    }
}

Best way to check for null values in Java?

If at all you going to check with double equal "==" then check null with object ref like

if(null == obj) 

instead of

if(obj == null)

because if you mistype single equal if(obj = null) it will return true (assigning object returns success (which is 'true' in value).

How can I hide/show a div when a button is clicked?

This works:

_x000D_
_x000D_
     function showhide(id) {_x000D_
        var e = document.getElementById(id);_x000D_
        e.style.display = (e.style.display == 'block') ? 'none' : 'block';_x000D_
     }
_x000D_
    <!DOCTYPE html>_x000D_
    <html>   _x000D_
    <body>_x000D_
    _x000D_
     <a href="javascript:showhide('uniquename')">_x000D_
      Click to show/hide._x000D_
     </a>_x000D_
    _x000D_
     <div id="uniquename" style="display:none;">_x000D_
      <p>Content goes here.</p>_x000D_
     </div>_x000D_
    _x000D_
    </body>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

How to remove numbers from a string?

Just want to add since it might be of interest to someone, that you may think about the problem the other way as well. I am not sure if that is of interest here, but I find it relevant.

What I mean by the other way is to say "strip anything that aren't what I am looking for, i.e. if you only want the 'ding' you could say:

var strippedText = ("1 ding ?").replace(/[^a-zA-Z]/g, '');

Which basically mean "remove anything which is nog a,b,c,d....Z (any letter).

How to force cp to overwrite without confirmation

cp -u ...
cp --update ...

also works.

Laravel 5 Application Key

For me the problem was in that I had not yet ran composer update for this new project/fork. The command failed silently, nothing happened.

After running composer update it worked.

What are CN, OU, DC in an LDAP search?

What are CN, OU, DC?

From RFC2253 (UTF-8 String Representation of Distinguished Names):

String  X.500 AttributeType
------------------------------
CN      commonName
L       localityName
ST      stateOrProvinceName
O       organizationName
OU      organizationalUnitName
C       countryName
STREET  streetAddress
DC      domainComponent
UID     userid


What does the string from that query mean?

The string ("CN=Dev-India,OU=Distribution Groups,DC=gp,DC=gl,DC=google,DC=com") is a path from an hierarchical structure (DIT = Directory Information Tree) and should be read from right (root) to left (leaf).

It is a DN (Distinguished Name) (a series of comma-separated key/value pairs used to identify entries uniquely in the directory hierarchy). The DN is actually the entry's fully qualified name.

Here you can see an example where I added some more possible entries.
The actual path is represented using green.

LDAP tree

The following paths represent DNs (and their value depends on what you want to get after the query is run):

  • "DC=gp,DC=gl,DC=google,DC=com"
  • "OU=Distribution Groups,DC=gp,DC=gl,DC=google,DC=com"
  • "OU=People,DC=gp,DC=gl,DC=google,DC=com"
  • "OU=Groups,DC=gp,DC=gl,DC=google,DC=com"
  • "CN=QA-Romania,OU=Distribution Groups,DC=gp,DC=gl,DC=google,DC=com"
  • "CN=Dev-India,OU=Distribution Groups,DC=gp,DC=gl,DC=google,DC=com"
  • "CN=Diana Anton,OU=People,DC=gp,DC=gl,DC=google,DC=com"

How to Lock the data in a cell in excel using vba

Try using the Worksheet.Protect method, like so:

Sub ProtectActiveSheet()
    Dim ws As Worksheet
    Set ws = ActiveSheet
    ws.Protect DrawingObjects:=True, Contents:=True, _
        Scenarios:=True, Password="SamplePassword"
End Sub

You should, however, be concerned about including the password in your VBA code. You don't necessarily need a password if you're only trying to put up a simple barrier that keeps a user from making small mistakes like deleting formulas, etc.

Also, if you want to see how to do certain things in VBA in Excel, try recording a Macro and looking at the code it generates. That's a good way to get started in VBA.

Disable vertical scroll bar on div overflow: auto

overflow: auto;
overflow-y: hidden;

For IE8: -ms-overflow-y: hidden;

Or Else :

To hide X:

<div style="height:150x; width:450px; overflow-x:hidden; overflow-y: scroll; padding-bottom:10px;"></div>

To hide Y:

<div style="height:150px; width:450px; overflow-x:scroll ; overflow-y: hidden; padding-bottom:10px;"></div>

How to add images in select list?

My solution is to use FontAwesome and then add library images as text! You just need the Unicodes and they are found here: FontAwesome Reference File forUnicodes

Here is an example state filter:

<select name='state' style='height: 45px; font-family:Arial, FontAwesome;'>
<option value=''>&#xf039; &nbsp; All States</option>
<option value='enabled' style='color:green;'>&#xf00c; &nbsp; Enabled</option>
<option value='paused' style='color:orange;'>&#xf04c; &nbsp; Paused</option>
<option value='archived' style='color:red;'>&#xf023; &nbsp; Archived</option>
</select>

Note the font-family:Arial, FontAwesome; is required to be assigned in style for select like given in the example!

Is there a way to override class variables in Java?

Yes. But as the variable is concerned it is overwrite (Giving new value to variable. Giving new definition to the function is Override). Just don't declare the variable but initialize (change) in the constructor or static block.

The value will get reflected when using in the blocks of parent class

if the variable is static then change the value during initialization itself with static block,

class Son extends Dad {
    static { 
       me = "son"; 
    }
}

or else change in constructor.

You can also change the value later in any blocks. It will get reflected in super class

Java Equivalent of C# async/await?

There is no equivalent of C# async/await in Java at the language level. A concept known as Fibers aka cooperative threads aka lightweight threads could be an interesting alternative. You can find Java libraries providing support for fibers.

Java libraries implementing Fibers

You can read this article (from Quasar) for a nice introduction to fibers. It covers what threads are, how fibers can be implemented on the JVM and has some Quasar specific code.

Query to select data between two dates with the format m/d/yyyy

select * from xxx where dates between '2012-10-10' and '2012-10-12'

I always use YYYY-MM-DD in my views and never had any issue. Plus, it is readable and non equivocal.
You should be aware that using BETWEEN might not return what you expect with a DATETIME field, since it would eliminate records dated '2012-10-12 08:00' for example.
I would rather use where dates >= '2012-10-10' and dates < '2012-10-13' (lower than next day)

How to use Apple's new .p8 certificate for APNs in firebase console

So, After taking a while I figured out that the old push certificate generating service also exists.

You get two options:

  • Apple Push Notification Authentication Key (Sandbox & Production)
  • Apple Push Notification service SSL (Sandbox & Production)

Those who want to achieve the old style .p12 certificate can get it from second option. I have not used the first option yet as most of the third-party push notification service providers still need the .p12 format certificate.

Sample image of the push notification service

Easiest way to convert int to string in C++

Use:

#include<iostream>
#include<string>

std::string intToString(int num);

int main()
{
    int integer = 4782151;

    std::string integerAsStr = intToString(integer);

    std::cout << "integer = " << integer << std::endl;
    std::cout << "integerAsStr = " << integerAsStr << std::endl;

    return 0;
}

std::string intToString(int num)
{
    std::string numAsStr;
    bool isNegative = num < 0;
    if(isNegative) num*=-1;

    do
    {
       char toInsert = (num % 10) + 48;
       numAsStr.insert(0, 1, toInsert);

       num /= 10;
    }while (num);
  
    return isNegative? numAsStr.insert(0, 1, '-') : numAsStr;
}

python-dev installation error: ImportError: No module named apt_pkg

This happened to me on Ubuntu 18.04.2 after I tried to install Python3.7 from the deadsnakes repo.

Solution was this

1) cd /usr/lib/python3/dist-packages/

2) sudo ln -s apt_pkg.cpython-36m-x86_64-linux-gnu.so apt_pkg.so

What's the correct way to communicate between controllers in AngularJS?

I liked the way how $rootscope.emit was used to achieve intercommunication. I suggest the clean and performance effective solution without polluting global space.

module.factory("eventBus",function (){
    var obj = {};
    obj.handlers = {};
    obj.registerEvent = function (eventName,handler){
        if(typeof this.handlers[eventName] == 'undefined'){
        this.handlers[eventName] = [];  
    }       
    this.handlers[eventName].push(handler);
    }
    obj.fireEvent = function (eventName,objData){
       if(this.handlers[eventName]){
           for(var i=0;i<this.handlers[eventName].length;i++){
                this.handlers[eventName][i](objData);
           }

       }
    }
    return obj;
})

//Usage:

//In controller 1 write:
eventBus.registerEvent('fakeEvent',handler)
function handler(data){
      alert(data);
}

//In controller 2 write:
eventBus.fireEvent('fakeEvent','fakeData');

C - reading command line parameters

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

int main(int argc, char **argv) {
  int i, parameter = 0;
  if (argc >= 2) {
    /* there is 1 parameter (or more) in the command line used */
    /* argv[0] may point to the program name */
    /* argv[1] points to the 1st parameter */
    /* argv[argc] is NULL */
    parameter = atoi(argv[1]); /* better to use strtol */
    if (parameter > 0) {
      for (i = 0; i < parameter; i++) printf("%d ", i);
    } else {
      fprintf(stderr, "Please use a positive integer.\n");
    }
  }
  return 0;
}

Converting datetime.date to UTC timestamp in Python

the question is a little confused. timestamps are not UTC - they're a Unix thing. the date might be UTC? assuming it is, and if you're using Python 3.2+, simple-date makes this trivial:

>>> SimpleDate(date(2011,1,1), tz='utc').timestamp
1293840000.0

if you actually have the year, month and day you don't need to create the date:

>>> SimpleDate(2011,1,1, tz='utc').timestamp
1293840000.0

and if the date is in some other timezone (this matters because we're assuming midnight without an associated time):

>>> SimpleDate(date(2011,1,1), tz='America/New_York').timestamp
1293858000.0

[the idea behind simple-date is to collect all python's date and time stuff in one consistent class, so you can do any conversion. so, for example, it will also go the other way:

>>> SimpleDate(1293858000, tz='utc').date
datetime.date(2011, 1, 1)

]

Headers and client library minor version mismatch

I got same php warring in my wordpress site...

Err: Warning: mysql_connect(): Headers and client library minor version mismatch. Headers:50547 Library:50628 in /home/lhu/public_html/innovacarrentalschennai.com/wp-includes/wp-db.php on line 1515

Cause: I updated wp 4.2 to 4.5 version (PHP and MySql mismatch )

I changed wp-db.php on line 1515

$this->dbh = mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );

to

if ( WP_DEBUG ) {
    $this->dbh = mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );
} else {
    $this->dbh = @mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );
}

Its got without warring err on my wordpress site

Making the main scrollbar always visible

html {
    overflow: -moz-scrollbars-vertical; 
    overflow-y: scroll;
}

This make the scrollbar always visible and only active when needed.

Update: If the above does not work the just using this may.

html {
    overflow-y:scroll;
}

Check if url contains string with JQuery

if(window.location.href.indexOf("?added-to-cart=555") >= 0)

It's window.location.href, not window.location.

Removing "http://" from a string

Something like this ought to do:

$url = preg_replace("|^.+?://|", "", $url); 

Removes everything up to and including the ://

Access denied; you need (at least one of) the SUPER privilege(s) for this operation

Another useful trick is to invoke mysqldump with the option --set-gtid-purged=OFF which does not write the following lines to the output file:

SET @@SESSION.SQL_LOG_BIN= 0;
SET @@GLOBAL.GTID_PURGED=/*!80000 '+'*/ '';
SET @@SESSION.SQL_LOG_BIN = @MYSQLDUMP_TEMP_LOG_BIN;

not sure about the DEFINER one.

OpenSSL and error in reading openssl.conf file

Just try to run openssl.exe as administrator.

How to implement band-pass Butterworth filter with Scipy.signal.butter

For a bandpass filter, ws is a tuple containing the lower and upper corner frequencies. These represent the digital frequency where the filter response is 3 dB less than the passband.

wp is a tuple containing the stop band digital frequencies. They represent the location where the maximum attenuation begins.

gpass is the maximum attenutation in the passband in dB while gstop is the attentuation in the stopbands.

Say, for example, you wanted to design a filter for a sampling rate of 8000 samples/sec having corner frequencies of 300 and 3100 Hz. The Nyquist frequency is the sample rate divided by two, or in this example, 4000 Hz. The equivalent digital frequency is 1.0. The two corner frequencies are then 300/4000 and 3100/4000.

Now lets say you wanted the stopbands to be down 30 dB +/- 100 Hz from the corner frequencies. Thus, your stopbands would start at 200 and 3200 Hz resulting in the digital frequencies of 200/4000 and 3200/4000.

To create your filter, you'd call buttord as

fs = 8000.0
fso2 = fs/2
N,wn = scipy.signal.buttord(ws=[300/fso2,3100/fso2], wp=[200/fs02,3200/fs02],
   gpass=0.0, gstop=30.0)

The length of the resulting filter will be dependent upon the depth of the stop bands and the steepness of the response curve which is determined by the difference between the corner frequency and stopband frequency.

Using :before CSS pseudo element to add image to modal

http://caniuse.com/#search=::after

::after and ::before with content are better to use as they're supported in every major browser other than Internet Explorer at least 5 versions back. Internet Explorer has complete support in version 9+ and partial support in version 8.

Is this what you're looking for?

.Modal::after{
  content:url('blackCarrot.png'); /* with class ModalCarrot ??*/
  position:relative; /*or absolute*/
  z-index:100000; /*a number that's more than the modal box*/
  left:-50px;
  top:10px;
}

.ModalCarrot{
   position:absolute;
   left:50%;
   margin-left:-8px;
   top:-16px;
}

If not, can you explain a little better?

or you could use jQuery, like Joshua said:

$(".Modal").before("<img src='blackCarrot.png' class='ModalCarrot' />");

OSX - How to auto Close Terminal window after the "exit" command executed.

If this is a Mac you type 'exit' then press return.

Node.js Write a line into a .txt file

Inserting data into the middle of a text file is not a simple task. If possible, you should append it to the end of your file.

The easiest way to append data some text file is to use build-in fs.appendFile(filename, data[, options], callback) function from fs module:

var fs = require('fs')
fs.appendFile('log.txt', 'new data', function (err) {
  if (err) {
    // append failed
  } else {
    // done
  }
})

But if you want to write data to log file several times, then it'll be best to use fs.createWriteStream(path[, options]) function instead:

var fs = require('fs')
var logger = fs.createWriteStream('log.txt', {
  flags: 'a' // 'a' means appending (old data will be preserved)
})

logger.write('some data') // append string to your file
logger.write('more data') // again
logger.write('and more') // again

Node will keep appending new data to your file every time you'll call .write, until your application will be closed, or until you'll manually close the stream calling .end:

logger.end() // close string

What is the difference between instanceof and Class.isAssignableFrom(...)?

Talking in terms of performance :

TL;DR

Use isInstance or instanceof which have similar performance. isAssignableFrom is slightly slower.

Sorted by performance:

  1. isInstance
  2. instanceof (+ 0.5%)
  3. isAssignableFrom (+ 2.7%)

Based on a benchmark of 2000 iterations on JAVA 8 Windows x64, with 20 warmup iterations.

In theory

Using a soft like bytecode viewer we can translate each operator into bytecode.

In the context of:

package foo;

public class Benchmark
{
  public static final Object a = new A();
  public static final Object b = new B();

  ...

}

JAVA:

b instanceof A;

Bytecode:

getstatic foo/Benchmark.b:java.lang.Object
instanceof foo/A

JAVA:

A.class.isInstance(b);

Bytecode:

ldc Lfoo/A; (org.objectweb.asm.Type)
getstatic foo/Benchmark.b:java.lang.Object
invokevirtual java/lang/Class isInstance((Ljava/lang/Object;)Z);

JAVA:

A.class.isAssignableFrom(b.getClass());

Bytecode:

ldc Lfoo/A; (org.objectweb.asm.Type)
getstatic foo/Benchmark.b:java.lang.Object
invokevirtual java/lang/Object getClass(()Ljava/lang/Class;);
invokevirtual java/lang/Class isAssignableFrom((Ljava/lang/Class;)Z);

Measuring how many bytecode instructions are used by each operator, we could expect instanceof and isInstance to be faster than isAssignableFrom. However, the actual performance is NOT determined by the bytecode but by the machine code (which is platform dependent). Let's do a micro benchmark for each of the operators.

The benchmark

Credit: As advised by @aleksandr-dubinsky, and thanks to @yura for providing the base code, here is a JMH benchmark (see this tuning guide):

class A {}
class B extends A {}

public class Benchmark {

    public static final Object a = new A();
    public static final Object b = new B();

    @Benchmark
    @BenchmarkMode(Mode.Throughput)
    @OutputTimeUnit(TimeUnit.MICROSECONDS)
    public boolean testInstanceOf()
    {
        return b instanceof A;
    }

    @Benchmark
    @BenchmarkMode(Mode.Throughput)
    @OutputTimeUnit(TimeUnit.MICROSECONDS)
    public boolean testIsInstance()
    {
        return A.class.isInstance(b);
    }

    @Benchmark
    @BenchmarkMode(Mode.Throughput)
    @OutputTimeUnit(TimeUnit.MICROSECONDS)
    public boolean testIsAssignableFrom()
    {
        return A.class.isAssignableFrom(b.getClass());
    }

    public static void main(String[] args) throws RunnerException {
        Options opt = new OptionsBuilder()
                .include(TestPerf2.class.getSimpleName())
                .warmupIterations(20)
                .measurementIterations(2000)
                .forks(1)
                .build();

        new Runner(opt).run();
    }
}

Gave the following results (score is a number of operations in a time unit, so the higher the score the better):

Benchmark                       Mode   Cnt    Score   Error   Units
Benchmark.testIsInstance        thrpt  2000  373,061 ± 0,115  ops/us
Benchmark.testInstanceOf        thrpt  2000  371,047 ± 0,131  ops/us
Benchmark.testIsAssignableFrom  thrpt  2000  363,648 ± 0,289  ops/us

Warning

  • the benchmark is JVM and platform dependent. Since there are no significant differences between each operation, it might be possible to get a different result (and maybe different order!) on a different JAVA version and/or platforms like Solaris, Mac or Linux.
  • the benchmark compares the performance of "is B an instance of A" when "B extends A" directly. If the class hierarchy is deeper and more complex (like B extends X which extends Y which extends Z which extends A), results might be different.
  • it is usually advised to write the code first picking one of the operators (the most convenient) and then profile your code to check if there are a performance bottleneck. Maybe this operator is negligible in the context of your code, or maybe...
  • in relation to the previous point, instanceof in the context of your code might get optimized more easily than an isInstance for example...

To give you an example, take the following loop:

class A{}
class B extends A{}

A b = new B();

boolean execute(){
  return A.class.isAssignableFrom(b.getClass());
  // return A.class.isInstance(b);
  // return b instanceof A;
}

// Warmup the code
for (int i = 0; i < 100; ++i)
  execute();

// Time it
int count = 100000;
final long start = System.nanoTime();
for(int i=0; i<count; i++){
   execute();
}
final long elapsed = System.nanoTime() - start;

Thanks to the JIT, the code is optimized at some point and we get:

  • instanceof: 6ms
  • isInstance: 12ms
  • isAssignableFrom : 15ms

Note

Originally this post was doing its own benchmark using a for loop in raw JAVA, which gave unreliable results as some optimization like Just In Time can eliminate the loop. So it was mostly measuring how long did the JIT compiler take to optimize the loop: see Performance test independent of the number of iterations for more details

Related questions

Difference between @Before, @BeforeClass, @BeforeEach and @BeforeAll

Difference between each annotation are :

+-------------------------------------------------------------------------------------------------------+
¦                                       Feature                            ¦   Junit 4    ¦   Junit 5   ¦
¦--------------------------------------------------------------------------+--------------+-------------¦
¦ Execute before all test methods of the class are executed.               ¦ @BeforeClass ¦ @BeforeAll  ¦
¦ Used with static method.                                                 ¦              ¦             ¦
¦ For example, This method could contain some initialization code          ¦              ¦             ¦
¦-------------------------------------------------------------------------------------------------------¦
¦ Execute after all test methods in the current class.                     ¦ @AfterClass  ¦ @AfterAll   ¦
¦ Used with static method.                                                 ¦              ¦             ¦
¦ For example, This method could contain some cleanup code.                ¦              ¦             ¦
¦-------------------------------------------------------------------------------------------------------¦
¦ Execute before each test method.                                         ¦ @Before      ¦ @BeforeEach ¦
¦ Used with non-static method.                                             ¦              ¦             ¦
¦ For example, to reinitialize some class attributes used by the methods.  ¦              ¦             ¦
¦-------------------------------------------------------------------------------------------------------¦
¦ Execute after each test method.                                          ¦ @After       ¦ @AfterEach  ¦
¦ Used with non-static method.                                             ¦              ¦             ¦
¦ For example, to roll back database modifications.                        ¦              ¦             ¦
+-------------------------------------------------------------------------------------------------------+

Most of annotations in both versions are same, but few differs.

Reference

Order of Execution.

Dashed box -> optional annotation.

enter image description here

Add data to JSONObject

In order to have this result:

{"aoColumnDefs":[{"aTargets":[0],"aDataSort":[0,1]},{"aTargets":[1],"aDataSort":[1,0]},{"aTargets":[2],"aDataSort":[2,3,4]}]}

that holds the same data as:

  {
    "aoColumnDefs": [
     { "aDataSort": [ 0, 1 ], "aTargets": [ 0 ] },
     { "aDataSort": [ 1, 0 ], "aTargets": [ 1 ] },
     { "aDataSort": [ 2, 3, 4 ], "aTargets": [ 2 ] }
   ]
  }

you could use this code:

    JSONObject jo = new JSONObject();
    Collection<JSONObject> items = new ArrayList<JSONObject>();

    JSONObject item1 = new JSONObject();
    item1.put("aDataSort", new JSONArray(0, 1));
    item1.put("aTargets", new JSONArray(0));
    items.add(item1);
    JSONObject item2 = new JSONObject();
    item2.put("aDataSort", new JSONArray(1, 0));
    item2.put("aTargets", new JSONArray(1));
    items.add(item2);
    JSONObject item3 = new JSONObject();
    item3.put("aDataSort", new JSONArray(2, 3, 4));
    item3.put("aTargets", new JSONArray(2));
    items.add(item3);

    jo.put("aoColumnDefs", new JSONArray(items));

    System.out.println(jo.toString());

SCCM 2012 application install "Failed" in client Software Center

The execmgr.log will show the commandline and ccmcache folder used for installation. Typically, required apps don't show on appenforce.log and some clients will have outdated appenforce or no ppenforce.log files. execmgr.log also shows required hidden uninstall actions as well.

You may want to save the blog link. I still reference it from time to time.

How to pip install a package with min and max version range?

You can do:

$ pip install "package>=0.2,<0.3"

And pip will look for the best match, assuming the version is at least 0.2, and less than 0.3.

This also applies to pip requirements files. See the full details on version specifiers in PEP 440.

Execute ssh with password authentication via windows command prompt

Windows Solution

  1. Install PuTTY
  2. Press Windows-Key + R
  3. Enter putty.exe -ssh [username]@[hostname] -pw [password]

How to get element-wise matrix multiplication (Hadamard product) in numpy?

For elementwise multiplication of matrix objects, you can use numpy.multiply:

import numpy as np
a = np.array([[1,2],[3,4]])
b = np.array([[5,6],[7,8]])
np.multiply(a,b)

Result

array([[ 5, 12],
       [21, 32]])

However, you should really use array instead of matrix. matrix objects have all sorts of horrible incompatibilities with regular ndarrays. With ndarrays, you can just use * for elementwise multiplication:

a * b

If you're on Python 3.5+, you don't even lose the ability to perform matrix multiplication with an operator, because @ does matrix multiplication now:

a @ b  # matrix multiplication

How to update core-js to core-js@3 dependency?

For ng9 upgraders:

npm i -g core-js@^3

..then:

npm cache clean -f

..followed by:

npm i

ArrayList filter

write your self a filter function

 public List<T> filter(Predicate<T> criteria, List<T> list) {
        return list.stream().filter(criteria).collect(Collectors.<T>toList());
 }

And then use

    list = new Test().filter(x -> x > 2, list);

This is the most neat version in Java, but needs JDK 1.8 to support lambda calculus

Why does 2 mod 4 = 2?

Modulo (mod, %) is the Remainder operator.

2%2 = 0 (2/2 = 1 remainder 0)
1%2 = 1 (1/2 = 0 remainder 1)
4%2 = 0 (4/2 = 2 remainder 0)
5%2 = 1 (5/2 = 2 remainder 1)

internet explorer 10 - how to apply grayscale filter?

Inline SVG can be used in IE 10 and 11 and Edge 12.

I've created a project called gray which includes a polyfill for these browsers. The polyfill switches out <img> tags with inline SVG: https://github.com/karlhorky/gray

To implement, the short version is to download the jQuery plugin at the GitHub link above and add after jQuery at the end of your body:

<script src="/js/jquery.gray.min.js"></script>

Then every image with the class grayscale will appear as gray.

<img src="/img/color.jpg" class="grayscale">

You can see a demo too if you like.

How to add data validation to a cell using VBA

Use this one:

Dim ws As Worksheet
Dim range1 As Range, rng As Range
'change Sheet1 to suit
Set ws = ThisWorkbook.Worksheets("Sheet1")

Set range1 = ws.Range("A1:A5")
Set rng = ws.Range("B1")

With rng.Validation
    .Delete 'delete previous validation
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
        Formula1:="='" & ws.Name & "'!" & range1.Address
End With

Note that when you're using Dim range1, rng As range, only rng has type of Range, but range1 is Variant. That's why I'm using Dim range1 As Range, rng As Range.
About meaning of parameters you can read is MSDN, but in short:

  • Type:=xlValidateList means validation type, in that case you should select value from list
  • AlertStyle:=xlValidAlertStop specifies the icon used in message boxes displayed during validation. If user enters any value out of list, he/she would get error message.
  • in your original code, Operator:= xlBetween is odd. It can be used only if two formulas are provided for validation.
  • Formula1:="='" & ws.Name & "'!" & range1.Address for list data validation provides address of list with values (in format =Sheet!A1:A5)

How to stop execution after a certain time in Java?

Depends on what the while loop is doing. If there is a chance that it will block for a long time, use TimerTask to schedule a task to set a stopExecution flag, and also .interrupt() your thread.

With just a time condition in the loop, it could sit there forever waiting for input or a lock (then again, may not be a problem for you).

Using NSLog for debugging

The proper way of using NSLog, as the warning tries to explain, is the use of a formatter, instead of passing in a literal:

Instead of:

NSString *digit = [[sender titlelabel] text];
NSLog(digit);

Use:

NSString *digit = [[sender titlelabel] text];
NSLog(@"%@",digit);

It will still work doing that first way, but doing it this way will get rid of the warning.

How to 'bulk update' with Django?

If you want to set the same value on a collection of rows, you can use the update() method combined with any query term to update all rows in one query:

some_list = ModelClass.objects.filter(some condition).values('id')
ModelClass.objects.filter(pk__in=some_list).update(foo=bar)

If you want to update a collection of rows with different values depending on some condition, you can in best case batch the updates according to values. Let's say you have 1000 rows where you want to set a column to one of X values, then you could prepare the batches beforehand and then only run X update-queries (each essentially having the form of the first example above) + the initial SELECT-query.

If every row requires a unique value there is no way to avoid one query per update. Perhaps look into other architectures like CQRS/Event sourcing if you need performance in this latter case.

swift UITableView set rowHeight

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
            var height:CGFloat = CGFloat()
            if indexPath.row == 1 {
                height = 150
            }
            else {
                height = 50
            }

            return height
        }

Using FolderBrowserDialog in WPF application

You need to add a reference to System.Windows.Forms.dll, then use the System.Windows.Forms.FolderBrowserDialog class.

Adding using WinForms = System.Windows.Forms; will be helpful.

Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0

CR has changed the Version No of Assemblies. The Old Version is 13.0.2000.0 (this is a incompatible version problem). The New Version is 13.0.3500.0 or 13.0.4000.0 - this is for my test case of Visual Studio 2019 and .net 4.7.2 and Window Server 2019. You need to open all your projects, Remove the old dll reference and add the new references. Then build the application again.

I learnt from source:

enter image description here

TO remove: Right click on an assembly under references to remove it.

enter image description here

This is where the error comes from - it is exactly what the error message outputs:

error message:

Could not load file or assembly ... The located assembly's manifest definition does not match the assembly reference ...

location error message referring to:

"C:\Visual-Studio-2019-Proj\Proj Windows Inventory\Proj Windows Inventory\obj\x86\Debug\Press HDL Windows Inventory.exe.manifest"

And it looks like this:

-The older version of .net 3.5 and CReports version="13.0.2000.0" and VS2012:

<dependentAssembly dependencyType="install" allowDelayedBinding="true" codebase="CrystalDecisions.CrystalReports.Engine.dll" size="372736">
      <assemblyIdentity name="CrystalDecisions.CrystalReports.Engine" version="13.0.2000.0" publicKeyToken="692FBEA5521E1304" language="neutral" processorArchitecture="msil" />

-The newer version of .net 4.7.2 and CReport version="13.0.4000.0" and VS2019:

<dependentAssembly dependencyType="install" allowDelayedBinding="true" codebase="CrystalDecisions.CrystalReports.Engine.dll" size="373248">
      <assemblyIdentity name="CrystalDecisions.CrystalReports.Engine" version="13.0.4000.0" publicKeyToken="692FBEA5521E1304" language="neutral" processorArchitecture="msil" />

org.hibernate.hql.internal.ast.QuerySyntaxException: table is not mapped

In my case I just forgot to add nativeQuery = true

@Query( value = "some sql query ...", nativeQuery = true)

For Spring Boot with Spring Data JPA

How to merge multiple dicts with same key or different key?

assuming all keys are always present in all dicts:

ds = [d1, d2]
d = {}
for k in d1.iterkeys():
    d[k] = tuple(d[k] for d in ds)

Note: In Python 3.x use below code:

ds = [d1, d2]
d = {}
for k in d1.keys():
  d[k] = tuple(d[k] for d in ds)

and if the dic contain numpy arrays:

ds = [d1, d2]
d = {}
for k in d1.keys():
  d[k] = np.concatenate(list(d[k] for d in ds))

How to keep two folders automatically synchronized?

I use this free program to synchronize local files and directories: https://github.com/Fitus/Zaloha.sh. The repository contains a simple demo as well.

The good point: It is a bash shell script (one file only). Not a black box like other programs. Documentation is there as well. Also, with some technical talents, you can "bend" and "integrate" it to create the final solution you like.

How to access the last value in a vector?

Package data.table includes last function

library(data.table)
last(c(1:10))
# [1] 10

jQuery multiselect drop down menu

I've used jQuery MultiSelect for implementing multiselect drop down menu with checkbox. You can see the implementation guide from here - Multi-select Dropdown List with Checkbox

Implementation is very simple, need only using the following code.

$('#transactionType').multiselect({
    columns: 1,
    placeholder: 'Select Transaction Type'
});

How to save Excel Workbook to Desktop regardless of user?

Not sure if this is still relevant, but I use this way

Public bEnableEvents As Boolean
Public bclickok As Boolean
Public booRestoreErrorChecking As Boolean   'put this at the top of the module

 Private Declare Function apiGetComputerName Lib "kernel32" Alias _
"GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long
Private Declare Function apiGetUserName Lib "advapi32.dll" Alias _
"GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long

Function GetUserID() As String
' Returns the network login name
On Error Resume Next
Dim lngLen As Long, lngX As Long
Dim strUserName As String
strUserName = String$(254, 0)
lngLen = 255
lngX = apiGetUserName(strUserName, lngLen)
If lngX <> 0 Then
    GetUserID = Left$(strUserName, lngLen - 1)
Else
    GetUserID = ""
End If
Exit Function
End Function

This next bit I save file as PDF, but can change to suit

Public Sub SaveToDesktop()
Dim LoginName As String
LoginName = UCase(GetUserID)

ChDir "C:\Users\" & LoginName & "\Desktop\"
Debug.Print LoginName
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
    "C:\Users\" & LoginName & "\Desktop\MyFileName.pdf", Quality:=xlQualityStandard, _
    IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
    True
End Sub

NameError: name 'python' is not defined

When you run the Windows Command Prompt, and type in python, it starts the Python interpreter.

Typing it again tries to interpret python as a variable, which doesn't exist and thus won't work:

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Users\USER>python
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> python
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'python' is not defined
>>> print("interpreter has started")
interpreter has started
>>> quit() # leave the interpreter, and go back to the command line

C:\Users\USER>

If you're not doing this from the command line, and instead running the Python interpreter (python.exe or IDLE's shell) directly, you are not in the Windows Command Line, and python is interpreted as a variable, which you have not defined.

Tuple unpacking in for loops

[i for i in enumerate(['a','b','c'])]

Result:

[(0, 'a'), (1, 'b'), (2, 'c')]

How to retrieve available RAM from Windows command line?

Use wmic computersystem get TotalPhysicalMemory. E.g.:

C:\>wmic computersystem get TotalPhysicalMemory
TotalPhysicalMemory
4294500352

How to get rid of "Unnamed: 0" column in a pandas DataFrame?

You can do the following with Unnamed Columns:

  1. Delete unnamed columns
  2. Rename them (if you want to use them)

file.csv

,A,B,C
0,1,2,3
1,4,5,6
2,7,8,9

#read file df = pd.read_csv('file.csv')

Method 1: Delete Unnamed Columns

# delete one by one like column is 'Unnamed: 0' so use it's name
df.drop('Unnamed: 0', axis=1, inplace=True)

#delete all Unnamed Columns in a single code of line using regex
df.drop(df.filter(regex="Unnamed"),axis=1, inplace=True)

Method 2: Rename Unnamed Columns

df.rename(columns = {'Unnamed: 0':'Name'}, inplace = True)

If you want to write out with a blank header as in the input file, just choose 'Name' above to be ''.

Binding a list in @RequestParam

Subscribing what basil said in a comment to the question itself, if method = RequestMethod.GET you can use @RequestParam List<String> groupVal.

Then calling the service with the list of params is as simple as:

API_URL?groupVal=kkk,ccc,mmm

How to load an external webpage into a div of a html page

Using simple html,

 <div> 
    <object type="text/html" data="http://validator.w3.org/" width="800px" height="600px" style="overflow:auto;border:5px ridge blue">
    </object>
 </div>

Or jquery,

<script>
        $("#mydiv")
            .html('<object data="http://your-website-domain"/>');
</script>

JSFIDDLE DEMO

How do I abort/cancel TPL Tasks?

You should not try to do this directly. Design your tasks to work with a CancellationToken, and cancel them this way.

In addition, I would recommend changing your main thread to function via a CancellationToken as well. Calling Thread.Abort() is a bad idea - it can lead to various problems that are very difficult to diagnose. Instead, that thread can use the same Cancellation that your tasks use - and the same CancellationTokenSource can be used to trigger the cancellation of all of your tasks and your main thread.

This will lead to a far simpler, and safer, design.

android EditText - finished typing event

Better way, you can also use EditText onFocusChange listener to check whether user has done editing: (Need not rely on user pressing the Done or Enter button on Soft keyboard)

 ((EditText)findViewById(R.id.youredittext)).setOnFocusChangeListener(new OnFocusChangeListener() {

    @Override
    public void onFocusChange(View v, boolean hasFocus) {

      // When focus is lost check that the text field has valid values.

      if (!hasFocus) { {
         // Validate youredittext
      }
    }
 });

Note : For more than one EditText, you can also let your class implement View.OnFocusChangeListener then set the listeners to each of you EditText and validate them as below

((EditText)findViewById(R.id.edittext1)).setOnFocusChangeListener(this);
((EditText)findViewById(R.id.edittext2)).setOnFocusChangeListener(this);

    @Override
    public void onFocusChange(View v, boolean hasFocus) {

      // When focus is lost check that the text field has valid values.

      if (!hasFocus) {
        switch (view.getId()) {
           case R.id.edittext1:
                 // Validate EditText1
                 break;
           case R.id.edittext2:
                 // Validate EditText2
                 break;
        }
      }
    }

Java IOException "Too many open files"

You're obviously not closing your file descriptors before opening new ones. Are you on windows or linux?

How to restore default perspective settings in Eclipse IDE

The solution that worked for me. Delete this folder:

workspace/.metadata/.plugins/org.eclipse.e4.workbench

NSNotificationCenter addObserver in Swift

In swift 3, Xcode 8.2:- checking battery state level

//Add observer
NotificationCenter.default.addObserver(self, selector: #selector(batteryStateDidChange), name: NSNotification.Name.UIDeviceBatteryStateDidChange, object: nil)


 //Fired when battery level changes

 func batteryStateDidChange(notification: NSNotification){
        //perform manipulation here
    }

How do browser cookie domains work?

I tested all the cases in the latest Chrome, Firefox, Safari in 2019.

Response to Added:

  • Will a cookie for .example.com be available for www.example.com? YES
  • Will a cookie for .example.com be available for example.com? YES
  • Will a cookie for example.com be available for www.example.com? NO, Domain without wildcard only matches itself.
  • Will a cookie for example.com be available for anotherexample.com? NO
  • Will www.example.com be able to set cookie for example.com? NO, it will be able to set cookie for '.example.com', but not 'example.com'.
  • Will www.example.com be able to set cookie for www2.example.com? NO. But it can set cookie for .example.com, which www2.example.com can access.
  • Will www.example.com be able to set cookie for .com? NO

Order by in Inner Join

Add an ORDER BY ONE.ID ASC at the end of your first query.

By default there is no ordering.

How do I get the command-line for an Eclipse run configuration?

I found a solution on Stack Overflow for Java program run configurations which also works for JUnit run configurations.

You can get the full command executed by your configuration on the Debug tab, or more specifically the Debug view.

  1. Run your application
  2. Go to your Debug perspective
  3. There should be an entry in there (in the Debug View) for the app you've just executed
  4. Right-click the node which references java.exe or javaw.exe and select Properties In the dialog that pops up you'll see the Command Line which includes all jars, parameters, etc

Are the PUT, DELETE, HEAD, etc methods available in most web browsers?

No. The HTML 5 spec mentions:

The method and formmethod content attributes are enumerated attributes with the following keywords and states:

The keyword get, mapping to the state GET, indicating the HTTP GET method. The GET method should only request and retrieve data and should have no other effect.

The keyword post, mapping to the state POST, indicating the HTTP POST method. The POST method requests that the server accept the submitted form's data to be processed, which may result in an item being added to a database, the creation of a new web page resource, the updating of the existing page, or all of the mentioned outcomes.

The keyword dialog, mapping to the state dialog, indicating that submitting the form is intended to close the dialog box in which the form finds itself, if any, and otherwise not submit.

The invalid value default for these attributes is the GET state

I.e. HTML forms only support GET and POST as HTTP request methods. A workaround for this is to tunnel other methods through POST by using a hidden form field which is read by the server and the request dispatched accordingly.

However, GET, POST, PUT and DELETE are supported by the implementations of XMLHttpRequest (i.e. AJAX calls) in all the major web browsers (IE, Firefox, Safari, Chrome, Opera).

Action Image MVC3 Razor

I have joined the answer from Lucas and "ASP.NET MVC Helpers, Merging two object htmlAttributes together" and plus controllerName to following code:

// Sample usage in CSHTML

 @Html.ActionImage("Edit",
       "EditController"
        new { id = MyId },
       "~/Content/Images/Image.bmp",
       new { width=108, height=129, alt="Edit" })

And the extension class for the code above:

using System.Collections.Generic;
using System.Reflection;
using System.Web.Mvc;

namespace MVC.Extensions
{
    public static class MvcHtmlStringExt
    {
        // Extension method
        public static MvcHtmlString ActionImage(
          this HtmlHelper html,
          string action,
          string controllerName,
          object routeValues,
          string imagePath,
          object htmlAttributes)
        {
            //https://stackoverflow.com/questions/4896439/action-image-mvc3-razor
            var url = new UrlHelper(html.ViewContext.RequestContext);

            // build the <img> tag
            var imgBuilder = new TagBuilder("img");
            imgBuilder.MergeAttribute("src", url.Content(imagePath));

            var dictAttributes = htmlAttributes.ToDictionary();

            if (dictAttributes != null)
            {
                foreach (var attribute in dictAttributes)
                {
                    imgBuilder.MergeAttribute(attribute.Key, attribute.Value.ToString(), true);
                }
            }                        

            string imgHtml = imgBuilder.ToString(TagRenderMode.SelfClosing);

            // build the <a> tag
            var anchorBuilder = new TagBuilder("a");
            anchorBuilder.MergeAttribute("href", url.Action(action, controllerName, routeValues));
            anchorBuilder.InnerHtml = imgHtml; // include the <img> tag inside            
            string anchorHtml = anchorBuilder.ToString(TagRenderMode.Normal);

            return MvcHtmlString.Create(anchorHtml);
        }

        public static IDictionary<string, object> ToDictionary(this object data)
        {
            //https://stackoverflow.com/questions/6038255/asp-net-mvc-helpers-merging-two-object-htmlattributes-together

            if (data == null) return null; // Or throw an ArgumentNullException if you want

            BindingFlags publicAttributes = BindingFlags.Public | BindingFlags.Instance;
            Dictionary<string, object> dictionary = new Dictionary<string, object>();

            foreach (PropertyInfo property in
                     data.GetType().GetProperties(publicAttributes))
            {
                if (property.CanRead)
                {
                    dictionary.Add(property.Name, property.GetValue(data, null));
                }
            }
            return dictionary;
        }
    }
}

Receiver not registered exception error?

Be careful, when you register by

LocalBroadcastManager.getInstance(this).registerReceiver()

you can't unregister by

 unregisterReceiver()

you must use

LocalBroadcastManager.getInstance(this).unregisterReceiver()

or app will crash, log as follow:

09-30 14:00:55.458 19064-19064/com.jialan.guangdian.view E/AndroidRuntime: FATAL EXCEPTION: main Process: com.jialan.guangdian.view, PID: 19064 java.lang.RuntimeException: Unable to stop service com.google.android.exoplayer.demo.player.PlayService@141ba331: java.lang.IllegalArgumentException: Receiver not registered: com.google.android.exoplayer.demo.player.PlayService$PlayStatusReceiver@19538584 at android.app.ActivityThread.handleStopService(ActivityThread.java:2941) at android.app.ActivityThread.access$2200(ActivityThread.java:148) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1395) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5310) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696) Caused by: java.lang.IllegalArgumentException: Receiver not registered: com.google.android.exoplayer.demo.player.PlayService$PlayStatusReceiver@19538584 at android.app.LoadedApk.forgetReceiverDispatcher(LoadedApk.java:769) at android.app.ContextImpl.unregisterReceiver(ContextImpl.java:1794) at android.content.ContextWrapper.unregisterReceiver(ContextWrapper.java:510) at com.google.android.exoplayer.demo.player.PlayService.onDestroy(PlayService.java:542) at android.app.ActivityThread.handleStopService(ActivityThread.java:2924) at android.app.ActivityThread.access$2200(ActivityThread.java:148)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1395)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:135)  at android.app.ActivityThread.main(ActivityThread.java:5310)  at java.lang.reflect.Method.invoke(Native Method)  at java.lang.reflect.Method.invoke(Method.java:372)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696) 

Check existence of directory and create if doesn't exist

I know this question was asked a while ago, but in case useful, the here package is really helpful for not having to reference specific file paths and making code more portable. It will automatically define your working directory as the one that your .Rproj file resides in, so the following will often suffice without having to define the file path to your working directory:

library(here)

if (!dir.exists(here(outputDir))) {dir.create(here(outputDir))}

Win32Exception (0x80004005): The wait operation timed out

I tried the other answers here as well as a few others. I even stopped and restarted the SQL services. Nothing worked.

However, restarting my computer did work.

How can I make a clickable link in an NSAttributedString?

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:strSomeTextWithLinks];

NSDictionary *linkAttributes = @{NSForegroundColorAttributeName: [UIColor redColor],   
                                 NSUnderlineColorAttributeName: [UIColor blueColor],
                                 NSUnderlineStyleAttributeName: @(NSUnderlinePatternSolid)};

customTextView.linkTextAttributes = linkAttributes; // customizes the appearance of links
textView.attributedText = attributedString;

KEY POINTS:

  • Make sure that you enable "Selectable" behavior of the UITextView in XIB.
  • Make sure that you disable "Editable" behavior of the UITextView in XIB.

How read Doc or Docx file in java?

Here is the code of ReadDoc/docx.java: This will read a dox/docx file and print its content to the console. you can customize it your way.

import java.io.*;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;

public class ReadDocFile
{
    public static void main(String[] args)
    {
        File file = null;
        WordExtractor extractor = null;
        try
        {

            file = new File("c:\\New.doc");
            FileInputStream fis = new FileInputStream(file.getAbsolutePath());
            HWPFDocument document = new HWPFDocument(fis);
            extractor = new WordExtractor(document);
            String[] fileData = extractor.getParagraphText();
            for (int i = 0; i < fileData.length; i++)
            {
                if (fileData[i] != null)
                    System.out.println(fileData[i]);
            }
        }
        catch (Exception exep)
        {
            exep.printStackTrace();
        }
    }
}

Store List to session

Yes. Which platform are you writing for? ASP.NET C#?

List<string> myList = new List<string>();
Session["var"] = myList;

Then, to retrieve:

myList = (List<string>)Session["var"];

Printing the last column of a line in a file

You can do all of it in awk:

<file awk '$1 ~ /A1/ {m=$NF} END {print m}'

Upload video files via PHP and save them in appropriate folder and have a database entry

PHP file (name is upload.php)    

<?php
    // =============  File Upload Code d  ===========================================
    $target_dir = "uploaded/";

    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    $uploadOk = 1;
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

    // Check if file already exists
    if (file_exists($target_file)) {
        echo "Sorry, file already exists.";
        $uploadOk = 0;
    }

     // Check file size -- Kept for 500Mb
    if ($_FILES["fileToUpload"]["size"] > 500000000) {
        echo "Sorry, your file is too large.";
        $uploadOk = 0;
    }

    // Allow certain file formats
    if($imageFileType != "wmv" && $imageFileType != "mp4" && $imageFileType != "avi" && $imageFileType != "MP4") {
        echo "Sorry, only wmv, mp4 & avi files are allowed.";
        $uploadOk = 0;
    }

    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
        echo "Sorry, your file was not uploaded.";
    // if everything is ok, try to upload file
    } else {
        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
            echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }
    // ===============================================  File Upload Code u  ==========================================================


    // =============  Connectivity for DATABASE d ===================================
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "test";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } 
    else

    $vidname = $_FILES["fileToUpload"]["name"] . "";
    $vidsize = $_FILES["fileToUpload"]["size"] . "";
    $vidtype = $_FILES["fileToUpload"]["type"] . "";

    $sql = "INSERT INTO videos (name, size, type) VALUES ('$vidname','$vidsize','$vidtype')";

    if ($conn->query($sql) === TRUE) {} 
    else {
        echo "Error: " . $sql . "<br>" . $conn->error;
        }

    $conn->close();
    // =============  Connectivity for DATABASE u ===================================

    ?>

SqlException from Entity Framework - New transaction is not allowed because there are other threads running in the session

I am much late to the party but today I faced the same error and how I resolved was simple. My scenario was similar to this given code I was making DB transactions inside of nested for-each loops.

The problem is as a Single DB transaction takes a little bit time longer than for-each loop so once the earlier transaction is not complete then the new traction throws an exception, so the solution is to create a new object in the for-each loop where you are making a db transaction.

For the above mentioned scenarios the solution will be like this:

foreach (RivWorks.Model.Negotiation.AutoNegotiationDetails companyFeedDetail in companyFeedDetailList)
                {
private RivWorks.Model.Negotiation.RIV_Entities _dbRiv = RivWorks.Model.Stores.RivEntities(AppSettings.RivWorkEntities_connString);
                    if (companyFeedDetail.FeedSourceTable.ToUpper() == "AUTO")
                    {
                        var company = (from a in _dbRiv.Company.Include("Product") where a.CompanyId == companyFeedDetail.CompanyId select a).First();
                        foreach (RivWorks.Model.NegotiationAutos.Auto sourceProduct in client.Auto)
                        {
                            foreach (RivWorks.Model.Negotiation.Product targetProduct in company.Product)
                            {
                                if (targetProduct.alternateProductID == sourceProduct.AutoID)
                                {
                                    found = true;
                                    break;
                                }
                            }
                            if (!found)
                            {
                                var newProduct = new RivWorks.Model.Negotiation.Product();
                                newProduct.alternateProductID = sourceProduct.AutoID;
                                newProduct.isFromFeed = true;
                                newProduct.isDeleted = false;
                                newProduct.SKU = sourceProduct.StockNumber;
                                company.Product.Add(newProduct);
                            }
                        }
                        _dbRiv.SaveChanges();  // ### THIS BREAKS ### //
                    }
                }

Empty or Null value display in SSRS text boxes

Either in SQL or in report code (as per adolf garlic's function suggestion)

At this moment in time, I'd do it in the report. I have very few reports against a busy OLTP server and an underwhelmed report server. If I had a different mix I'd do it in SQL.

Either way is acceptable...

Kubernetes service external ip pending

If you are using Minikube, there is a magic command!

$ minikube tunnel

Hopefully someone can save a few minutes with this.

Reference link https://minikube.sigs.k8s.io/docs/handbook/accessing/#using-minikube-tunnel

How to get local server host and port in Spring Boot?

For Spring 2

val hostName = InetAddress.getLocalHost().hostName

var webServerPort: Int = 0
@Configuration
class ApplicationListenerWebServerInitialized : ApplicationListener<WebServerInitializedEvent> {
    override fun onApplicationEvent(event: WebServerInitializedEvent) {
        webServerPort = event.webServer.port
    }
}

then you can use also webServerPort from anywhere...

Foreign key referring to primary keys across multiple tables?

Technically possible. You would probably reference employees_ce in deductions and employees_sn. But why don't you merge employees_sn and employees_ce? I see no reason why you have two table. No one to many relationship. And (not in this example) many columns.

If you do two references for one column, an employee must have an entry in both tables.

Xcode error "Could not find Developer Disk Image"

This error is shown when your Xcode installation is too old and the related device you are using is updated to latest version.

There are multiple ways to solve this issues.

1. Update your Xcode installation.

This is by far the simplest method. Just update your Xcode installation to the latest stable version and things would start working again.

Note: Please update your OS as well if Xcode doesn't support your current OS. Which brings us to...

2. Manually copying Device Disk Image. No update needed.

This is the clever way around. You don't have to update your Xcode installation or your OS for this.

First open the XCode.dmg and select Show Package Contents.

Phase 1: Getting the downloaded Xcode ready.

Steps:

  1. Download the latest Xcode.dmg from Developer portal.
  2. Select the downloaded Xcode.dmg and right click on it.
  3. In the options, select Open With ? DiskImageMounter.
  4. Now in Finder, open the Xcode disk.
  5. In the disk, right click on Xcode.
  6. Select Show Package Contents.

Now, a new finder window opens. Follow the instructions below to copy the disk image.

Phase 2: Copying the Developer Disk Image.

Steps:

  1. In the new finder, go to Contents.
  2. Inside Contents, Go to Developer.
  3. Inside Developer, go to Platform.
    Now select the desired platform. For our purpose, we are going to update iOS disk image only.
  4. Inside Platform, go to Device Support.
  5. Inside Device Support, you'll find a lot of disk images. This includes the latest device disk images as well.
  6. Copy all the folders inside Device Support. Select all and then copy.

Note: For step 6, You can copy the disk image you want to copy as well, i.e. copy the latest only. It's the last folder in the hierarchy here.

This ends the Phase 2, Copying the disk image. Now in the next phase, we will update the developer disk image of our Xcode installed on our device.

Phase 3: Upadting the Xcode's developer disk image.

Now, close all the finder windows for faster operation and less confusion.

We are now going to update our Xcode's disk image for iOS Platform.

Steps:

  1. Close the Xcode application if it is open.
  2. Open a new finder window.
  3. Select the primary partition if you have multiple partitions.
  4. Go to Applications.
  5. Find XCode and right click on it.
  6. Select Show Package Contents.

Finder window updates or opens a new window with Contents as the main directory.

  1. Select Contents.
  2. Inside Contents, select Developer.
  3. Now, select Platforms.
    1. Now, select iPhoneOS.platform.
    2. Inside iPhoneOS.platform, go to Device Support.
    3. Inside Device Support, select all the files and Move to Trash.

Note: SKIP step 12 if you copied only the latest disk image i.e. the last folder in the hierarchy.


Now, Paste the developer disk image we copied from Phase 2 here.

  1. Final Step, right click and Paste here.

If everything worked properly, your Xcode has new developer disk image. Close the finder now, and open Xcode. The error should be gone by now.

Reminder: Don't forget to unmount the Xcode now from finder as well.

Check a radio button with javascript

I was able to select (check) a radio input button by using this Javascript code in Firefox 72, within a Web Extension option page to LOAD the value:

var reloadItem = browser.storage.sync.get('reload_mode');
reloadItem.then((response) => {
    if (response["reload_mode"] == "Periodic") {
        document.querySelector('input[name=reload_mode][value="Periodic"]').click();
    } else if (response["reload_mode"] == "Page Bottom") {
        document.querySelector('input[name=reload_mode][value="Page Bottom"]').click();
    } else {
        document.querySelector('input[name=reload_mode][value="Both"]').click();
    }
});

Where the associated code to SAVE the value was:

reload_mode: document.querySelector('input[name=reload_mode]:checked').value

Given HTML like the following:

    <input type="radio" id="periodic" name="reload_mode" value="Periodic">
    <label for="periodic">Periodic</label><br>
    <input type="radio" id="bottom" name="reload_mode" value="Page Bottom">
    <label for="bottom">Page Bottom</label><br>
    <input type="radio" id="both" name="reload_mode" value="Both">
    <label for="both">Both</label></br></br>

How can I import Swift code to Objective-C?

Here's what to do:

  1. Create a new Project in Objective-C

  2. Create a new .swift file  

    • A popup window will appear and ask "Would You like to configure an Objective-C bridging Header".
    • Choose Yes.
  3. Click on your Xcode Project file

  4. Click on Build Settings

  5. Find the Search bar and search for Defines Module.

  6. Change value to Yes.

  7. Search Product Module Name.

  8. Change the value to the name of your project.

  9. In App delegate, add the following : #import "YourProjectName-Swift.h"


Note: Whenever you want to use your Swift file you must be import following line :

#import "YourProjectName-Swift.h"

How to fix apt-get: command not found on AWS EC2?

Try replacing apt-get with yum as Amazon Linux based AMI uses the yum command instead of apt-get.

What is the difference between JavaScript and jQuery?

jQuery is a JavaScript library, that can be used for communicating (selecting html elements, attaching event listeners, animations etc.) with the DOM, creating and consuming AJAX requests, as well as other things in a more easier way rather than using plain JavaScript. jQuery is written in JavaScript. It should be mentioned that browsers parse only HTML, CSS and JavaScript files. Hence, all JavaScript libraries/frameworks (jQuery, Knockout, Angular) are written in JavaScript or in languages like TypeScript that transconpiles to JavaScript (e.g. Angular 2). They provide you the opportunity to write less lines of codes or to create interfaces following patterns like MVC (e.g. Angular), MVVM (e.g. Knockout) as well as other patterns, but under the hood, they are all result in a JavaScript file.

An example in order to understand why using jQuery you write less do more is the following.

Let we have the following input element

<input id="button1" type="button" value="clickMe"/> 

Also, let that we want when someone clicks on the button to be notified through an alert box showing to the user a 'Hello' message.

If we had to do this using plain JavaScript, we would have written the following:

document.getElementById("button1")
        .addEventListener('click', function(){ 
            alert("Hello");
        });

On the other hand, if we were using jQuery, we would had achieved the same result by just writing this:

$('#button1').click(function(){ 
    alert("Hello"); 
});

Using jQuery makes things more clear than using plain JavaScript for the same purpose. (write less do more is jQuery's moto)

Furthermore, jQuery handles pretty well the theme of browser compatibility, you can use their API pretty easily without wondering too much as if you should do in case of using plain JavaScript.

Below I have added snippets for the code above:

_x000D_
_x000D_
document.getElementById("button1")_x000D_
        .addEventListener('click', function(){ _x000D_
            alert("Hello");_x000D_
        });
_x000D_
<input id="button1" type="button" value="clickMe"/>
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
$('#button1').click(function(){ alert("Hello"); });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input id="button1" type="button" value="clickMe"/>
_x000D_
_x000D_
_x000D_

SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known

In my case, everything was set up correctly, but my Docker infrastructure needed more RAM. I'm using Docker for Mac, where default RAM was around 1 GB, and as MySQL uses around 1.5Gb of RAM ( and probably was crashing ??? ), changing the Docker RAM utilization level to 3-4 Gb solved the issue.

"The remote certificate is invalid according to the validation procedure." using Gmail SMTP server

A little late to the party, but if you are looking for a solution like Yury's the following code will help you identify if the issue is related to a self-sign certificate and, if so ignore the self-sign error. You could obviously check for other SSL errors if you so desired.

The code we use (courtesy of Microsoft - http://msdn.microsoft.com/en-us/library/office/dd633677(v=exchg.80).aspx) is as follows:

  private static bool CertificateValidationCallBack(
         object sender,
         System.Security.Cryptography.X509Certificates.X509Certificate certificate,
         System.Security.Cryptography.X509Certificates.X509Chain chain,
         System.Net.Security.SslPolicyErrors sslPolicyErrors)
    {
  // If the certificate is a valid, signed certificate, return true.
  if (sslPolicyErrors == System.Net.Security.SslPolicyErrors.None)
  {
    return true;
  }

  // If there are errors in the certificate chain, look at each error to determine the cause.
  if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors) != 0)
  {
    if (chain != null && chain.ChainStatus != null)
    {
      foreach (System.Security.Cryptography.X509Certificates.X509ChainStatus status in chain.ChainStatus)
      {
        if ((certificate.Subject == certificate.Issuer) &&
           (status.Status == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.UntrustedRoot))
        {
          // Self-signed certificates with an untrusted root are valid. 
          continue;
        }
        else
        {
          if (status.Status != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError)
          {
            // If there are any other errors in the certificate chain, the certificate is invalid,
         // so the method returns false.
            return false;
          }
        }
      }
    }

    // When processing reaches this line, the only errors in the certificate chain are 
// untrusted root errors for self-signed certificates. These certificates are valid
// for default Exchange server installations, so return true.
    return true;
  }
  else
  {
 // In all other cases, return false.
    return false;
  }
}

Proper use of mutexes in Python

You have to unlock your Mutex at sometime...

JavaScript implementation of Gzip

We just released pako https://github.com/nodeca/pako , port of zlib to javascript. I think that's now the fastest js implementation of deflate / inflate / gzip / ungzip. Also, it has democratic MIT licence. Pako supports all zlib options and it's results are binary equal.

Example:

var inflate = require('pako/lib/inflate').inflate; 
var text = inflate(zipped, {to: 'string'});

Convert integer into its character equivalent, where 0 => a, 1 => b, etc

There you go: (a-zA-Z)

function codeToChar( number ) {
  if ( number >= 0 && number <= 25 ) // a-z
    number = number + 97;
  else if ( number >= 26 && number <= 51 ) // A-Z
    number = number + (65-26);
  else
    return false; // range error
  return String.fromCharCode( number );
}

input: 0-51, or it will return false (range error);

OR:

var codeToChar = function() {
  var abc = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
  return function( code ) {
    return abc[code];
  };
})();

returns undefined in case of range error. NOTE: the array will be created only once and because of closure it will be available for the the new codeToChar function. I guess it's even faster then the first method (it's just a lookup basically).

Finding row index containing maximum value using R

How about the following, where y is the name of your matrix and you are looking for the maximum in the entire matrix:

row(y)[y==max(y)]

if you want to extract the row:

y[row(y)[y==max(y)],] # this returns unsorted rows.

To return sorted rows use:

y[sort(row(y)[y==max(y)]),]

The advantage of this approach is that you can change the conditional inside to anything you need. Also, using col(y) and location of the hanging comma you can also extract columns.

y[,col(y)[y==max(y)]]

To find just the row for the max in a particular column, say column 2 you could use:

seq(along=y[,2])[y[,2]==max(y[,2])]

again the conditional is flexible to look for different requirements.

See Phil Spector's excellent "An introduction to S and S-Plus" Chapter 5 for additional ideas.

Switch: Multiple values in one case?

In C# 7 it's possible to use a when clause in a case statement.

int age = 12;
switch (age) 
{
  case int i when i >=1 && i <= 8:
    System.Console.WriteLine("You are only " + age + " years old. You must be kidding right. Please fill in your *real* age.");
    break;
  case int i when i >=9 && i <= 15:
    System.Console.WriteLine("You are only " + age + " years old. That's too young!");
    break;
  case int i when i >=16 && i <= 100:
    System.Console.WriteLine("You are " + age + " years old. Perfect.");
    break;
  default:
    System.Console.WriteLine("You an old person.");
    break;
}

Create an Android GPS tracking application

Basically you need following things to make location detector android app

Now if you write each of these module yourself then it needs much time and efforts. So it would be better to use ready resources that are being maintained already.

Using all these resources, you will be able to create an flawless android location detection app.

1. Location Listening

You will first need to listen for current location of user. You can use any of below libraries to quick start.

Google Play Location Samples

This library provide last known location, location updates

Location Manager

With this library you just need to provide a Configuration object with your requirements, and you will receive a location or a fail reason with all the stuff are described above handled.

Live Location Sharing

Use this open source repo of the Hypertrack Live app to build live location sharing experience within your app within a few hours. HyperTrack Live app helps you share your Live Location with friends and family through your favorite messaging app when you are on the way to meet up. HyperTrack Live uses HyperTrack APIs and SDKs.

2. Markers Library

Google Maps Android API utility library

  • Marker clustering — handles the display of a large number of points
  • Heat maps — display a large number of points as a heat map
  • IconGenerator — display text on your Markers
  • Poly decoding and encoding — compact encoding for paths, interoperability with Maps API web services
  • Spherical geometry — for example: computeDistance, computeHeading, computeArea
  • KML — displays KML data
  • GeoJSON — displays and styles GeoJSON data

3. Polyline Libraries

DrawRouteMaps

If you want to add route maps feature in your apps you can use DrawRouteMaps to make you work more easier. This is lib will help you to draw route maps between two point LatLng.

trail-android

Simple, smooth animation for route / polylines on google maps using projections. (WIP)

Google-Directions-Android

This project allows you to calculate the direction between two locations and display the route on a Google Map using the Google Directions API.

A map demo app for quick start with maps

Skipping Iterations in Python

For this specific use-case using try..except..else is the cleanest solution, the else clause will be executed if no exception was raised.

NOTE: The else clause must follow all except clauses

for i in iterator:
    try:
        # Do something.
    except:
        # Handle exception
    else:
        # Continue doing something

Doctrine findBy 'does not equal'

I used the QueryBuilder to get the data,

$query=$this->dm->createQueryBuilder('AppBundle:DocumentName')
             ->field('fieldName')->notEqual(null);

$data=$query->getQuery()->execute();

How to preserve request url with nginx proxy_pass

for my auth server... this works. i like to have options for /auth for my own humanized readability... or also i have it configured by port/upstream for machine to machine.

.

at the beginning of conf

####################################################
upstream auth {
    server 127.0.0.1:9011 weight=1 fail_timeout=300s;
    keepalive 16;
  }

Inside my 443 server block

          if (-d $request_filename) {
          rewrite [^/]$ $scheme://$http_host$uri/ permanent;
      }

  location /auth {
          proxy_pass http://$http_host:9011;
          proxy_set_header Origin           http://$host;
          proxy_set_header Host             $http_host:9011;
          proxy_set_header X-Forwarded-For  $proxy_add_x_forwarded_for;
          proxy_set_header Upgrade          $http_upgrade;
          proxy_set_header Connection       $http_connection;
          proxy_http_version 1.1;
      }

At the bottom of conf

#####################################################################
#                                                                   #
#     Proxies for all the Other servers on other ports upstream     #
#                                                                   #
#####################################################################


#######################
#        Fusion       #
#######################

server {
    listen 9001 ssl;

#############  Lock it down  ################

# SSL certificate locations
    ssl_certificate /etc/letsencrypt/live/allineed.app/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/allineed.app/privkey.pem;

# Exclusions

    include snippets/exclusions.conf;

# Security

    include snippets/security.conf;
    include snippets/ssl.conf;

# Fastcgi cache rules

    include snippets/fastcgi-cache.conf;
    include snippets/limits.conf;
    include snippets/nginx-cloudflare.conf;

###########  Location upstream ##############

    location  ~ / {
        proxy_pass http://auth;
        proxy_set_header Origin           http://$host;
        proxy_set_header Host             $host:$server_port;
        proxy_set_header X-Forwarded-For  $proxy_add_x_forwarded_for;
        proxy_set_header Upgrade          $http_upgrade;
        proxy_set_header Connection       $http_connection;
        proxy_http_version 1.1;
    }
        if (-d $request_filename) {
        rewrite [^/]$ $scheme://$http_host$uri/ permanent;
    }
}

No module named setuptools

Install setuptools and try again.

try command:

sudo apt-get install -y python-setuptools

Android Studio cannot resolve R in imported project?

Regarding the following, from Crossle Song's answer

  1. Press F4 into Project Structure, Check SDKs on left
  2. Click Modules ---> Source Tab, check gen and src as sources

Despite the message "We will provide a UI to configure project settings later....etc" this worked for me.

Add newly created specific folder to .gitignore in Git

It's /public_html/stats/*.

$ ~/myrepo> ls public_html/stats/
bar baz foo
$ ~/myrepo> cat .gitignore 
public_html/stats/*
$ ~/myrepo> git status
# On branch master
#
# Initial commit
#
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#   .gitignore
nothing added to commit but untracked files present (use "git add" to track)
$ ~/myrepo>

How to maintain a Unique List in Java?

You may want to use one of the implementing class of java.util.Set<E> Interface e.g. java.util.HashSet<String> collection class.

A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.

How to set Internet options for Android emulator?

Hi me also faced same issue , solved using below steps:

cause 1:

Add internet permission in your android application

cause 2:

Check the manually your default application is able access internet or not if not its problem of your emulator , check in your internet connection in your pc

try below method to connect net in your pc

try explicitly specifying DNS server settings, this worked for me.

In Eclipse:

Window>Preferences>Android>Launch

Default emulator options: -dns-server 8.8.8.8,8.8.4.4**

cause 3:

check : check if you are using more than one internet connection to your pc like one is LAN second one is Modem , so disable all lan or modem .

Convert java.util.Date to java.time.LocalDate

LocalDate localDate = LocalDate.parse( new SimpleDateFormat("yyyy-MM-dd").format(date) );

How to print a two dimensional array?

Something like this that i answer in another question

public class Snippet {
    public static void main(String[] args) {
        int [][]lst = new int[10][10];

        for (int[] arr : lst) {
            System.out.println(Arrays.toString(arr));
        }
    }

}

Simulation of CONNECT BY PRIOR of Oracle in SQL Server

I haven't used connect by prior, but a quick search shows it's used for tree structures. In SQL Server, you use common table expressions to get similar functionality.

How to hide the Google Invisible reCAPTCHA badge

My solution was to hide the badge, then display it when the user focuses on a form input - thus still adhering to Google's T&Cs.

Note: The reCAPTCHA I was tweaking had been generated by a WordPress plugin, so you may need to wrap the reCAPTCHA with a <div class="inv-recaptcha-holder"> ... </div> yourself.

CSS

.inv-recaptcha-holder {
  visibility: hidden;
  opacity: 0;
  transition: linear opacity 1s;
}

.inv-recaptcha-holder.show {
  visibility: visible;
  opacity: 1;
  transition: linear opacity 1s;
}

jQuery

$(document).ready(function () {
  $('form input, form textarea').on( 'focus', function() {
    $('.inv-recaptcha-holder').addClass( 'show' );
  });
});

Obviously you can change the jQuery selector to target specific forms if necessary.

jQuery - Increase the value of a counter when a button is clicked

Several of the suggestions above use global variables. This is not a good solution for the problem. The count is specific to one element, and you can use jQuery's data function to bind an item of data to an element:

$('#counter').data('count', 0);
$('#update').click(function(){
    $('#counter').html(function(){
        var $this = $(this),
            count = $this.data('count') + 1;

        $this.data('count', count);
        return count;
    });
});

Note also that this uses the callback syntax of html to make the code more fluent and fast.

Delete entire row if cell contains the string X

  1. Delete rows 1 and 2 so that your headings are on row 1
  2. Put this in a macro (IT WILL CHECK THROUGH ROW 75000, YOU CAN LOWER THE NUMBER IF YOU WOULD LIKE

    Columns("E:E").Select Selection.AutoFilter ActiveSheet.Range("$E$1:$E$75000").AutoFilter Field:=1, Criteria1:="none" Range("E2:E75000").SpecialCells(xlCellTypeVisible).Select Selection.EntireRow.Delete ActiveSheet.Cells.EntireRow.Hidden = False ActiveSheet.Range("$E$1:$E$75000").AutoFilter Field:=1 Columns("E:E").Select Selection.AutoFilter Range("E2").Select Range("A1").Select

Best way to overlay an ESRI shapefile on google maps?

Do you mean shapefile as in an Esri shapefile? Either way, you should be able to perform the conversion using ogr2ogr, which is available in the GDAL packages. You need the .shp file and ideally the corresponding .dbf file (which will provide contextual information).

Also, consider using a tool like MapShaper to reduce the complexity of your shapefiles before transforming them into KML; you'll reduce filesize substantially depending on how much detail you need.

How to define a preprocessor symbol in Xcode

It's under "GCC 4.2 Preprocessing" (or just put "prepro" in the search box)...

...however, for the life of me I can't get it to work.

I have my standard Debug and Release configurations, and I want to define DEBUG=1 in the debugging configuration. But after adding it as a value:

(in the settings window) > Preprocessor Macros : DEBUG=1

#if DEBUG
    printf("DEBUG is set!");
#endif 

...never prints/gets called. It's driving me crazy...

Adding iOS UITableView HeaderView (not section header)

UITableView has a tableHeaderView property. Set that to whatever view you want up there.

Use a new UIView as a container, add a text label and an image view to that new UIView, then set tableHeaderView to the new view.

For example, in a UITableViewController:

-(void)viewDidLoad
{
     // ...
     UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(XXX, YYY, XXX, YYY)];
     UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(XXX, YYY, XXX, YYY)];
     [headerView addSubview:imageView];
     UILabel *labelView = [[UILabel alloc] initWithFrame:CGRectMake(XXX, YYY, XXX, YYY)];
     [headerView addSubview:labelView];
     self.tableView.tableHeaderView = headerView;
     [imageView release];
     [labelView release];
     [headerView release];
     // ...
} 

Clear image on picturebox

I've had a stubborn image too, that wouldn't go away by setting the Image and InitialImage to null. To remove the image from the pictureBox for good, I had to use the code below, by calling Application.DoEvents() repeatedly:

            Application.DoEvents();
            if (_pictureBox.Image != null)
                _pictureBox.Image.Dispose();
            _pictureBox.Image = null;
            Application.DoEvents();
            if (_pictureBox.InitialImage != null)
                _pictureBox.InitialImage.Dispose();
            _pictureBox.InitialImage = null;
            _pictureBox.Update();
            Application.DoEvents();
            _pictureBox.Refresh();

What is the best way to seed a database in Rails?

Usually there are 2 types of seed data required.

  • Basic data upon which the core of your application may rely. I call this the common seeds.
  • Environmental data, for example to develop the app it is useful to have a bunch of data in a known state that us can use for working on the app locally (the Factory Girl answer above covers this kind of data).

In my experience I was always coming across the need for these two types of data. So I put together a small gem that extends Rails' seeds and lets you add multiple common seed files under db/seeds/ and any environmental seed data under db/seeds/ENV for example db/seeds/development.

I have found this approach is enough to give my seed data some structure and gives me the power to setup my development or staging environment in a known state just by running:

rake db:setup

Fixtures are fragile and flakey to maintain, as are regular sql dumps.

Permissions error when connecting to EC2 via SSH on Mac OSx

I was getting this error when I was trying to ssh into an ec2 instance on the private subnet from the bastion, to fix this issue, you've to run (ssh-add -K) as follow.

    Step 1: run "chmod 400 myEC2Key.pem"
    Step 2: run "ssh-add -K ./myEC2Key.pem" on your local machine
    Step 3: ssh -i myEC2Key.pem [email protected]
    Step 4: Now try to ssh to EC2 instance that is on a private subnet without specifying the key, for example, try ssh ec2-user@ipaddress.

    Hope this will help.
Note: This solution is for Mac.

How to "test" NoneType in python?

Not sure if this answers the question. But I know this took me a while to figure out. I was looping through a website and all of sudden the name of the authors weren't there anymore. So needed a check statement.

if type(author) == type(None):
     my if body
else:
    my else body

Author can be any variable in this case, and None can be any type that you are checking for.

PHP save image file

Note: you should use the accepted answer if possible. It's better than mine.

It's quite easy with the GD library.

It's built in usually, you probably have it (use phpinfo() to check)

$image = imagecreatefromjpeg("http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com");

imagejpeg($image, "folder/file.jpg");

The above answer is better (faster) for most situations, but with GD you can also modify it in some form (cropping for example).

$image = imagecreatefromjpeg("http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com");
imagecopy($image, $image, 0, 140, 0, 0, imagesx($image), imagesy($image));
imagejpeg($image, "folder/file.jpg");

This only works if allow_url_fopen is true (it is by default)

wildcard * in CSS for classes

Yes you can do this.

*[id^='term-']{
    [css here]
}

This will select all ids that start with 'term-'.

As for the reason for not doing this, I see where it would be preferable to select this way; as for style, I wouldn't do it myself, but it's possible.

error: function returns address of local variable

The local variables have a lifetime which extends only inside the block in which it is defined. The moment the control goes outside the block in which the local variable is defined, the storage for the variable is no more allocated (not guaranteed). Therefore, using the memory address of the variable outside the lifetime area of the variable will be undefined behaviour.

On the other hand you can do the following.

 char *str_to_ret = malloc (sizeof (char) * required_size);
  .
  .
  .
 return str_to_ret;

And use the str_to_ret instead. And when returning str_to_ret, the address allocated by malloc will be returned. The memory allocated by malloc is allocated from the heap, which has a lifetime which spans the entire execution of the program. Therefore, you can access the memory location from any block and any time while the program is running.

Also note that it is a good practice that after you have done with the allocated memory block, free it to save from memory leaks. Once you free the memory, you can't access that block again.

Passing parameters to click() & bind() event in jquery?

see event.data

commentbtn.bind('click', { id: '12', name: 'Chuck Norris' }, function(event) {
    var data = event.data;
    alert(data.id);
    alert(data.name);
});

If your data is initialized before binding the event, then simply capture those variables in a closure.

// assuming id and name are defined in this scope
commentBtn.click(function() {
    alert(id), alert(name);
});

How to remove unwanted space between rows and columns in table?

I had this problem and none of the suggestions from several posts worked, I tried them all. My problem turned out that the table I was creating is nested in another table, inheriting on its properties. I needed to override the container table.

In this example, SuColTable is class on the table.

.SuColTable tr {
    border: none !important;
}

.SuColTable td {
    border-spacing: 0 !important;
    border: none !important;
    margin: 0 !important;
    padding-top: 0 !important;
    padding-bottom: 0 !important;
    padding-right: 0 !important;
}


.SuColTable {
    border-collapse: collapse !important;
    border: none !important;
    border-spacing: 0 !important;
    border-collapse: separate !important;
    padding-left: 0 !important;
    padding-top: 0 !important;
    padding-bottom: 0 !important;
}
// all padding would be padding: 0 !important

The border-collapse, border:none and border-spacing get rid of table/row/column line. The padding 0 calls get rid the padding from the container table. I had to including !important on every style for it work, in order override the container table styles.

I have padding_top, left and bottom (instead of only padding) because I have two other classes that control the padding_right.

line-height: 0px;

Line-height zero makes the row one line high. If you have several lines, they are compressed into one line.

React: how to update state.item[1] in state using setState?

Use the event on handleChange to figure out the element that has changed and then update it. For that you might need to change some property to identify it and update it.

See fiddle https://jsfiddle.net/69z2wepo/6164/

How to delete mysql database through shell command

[root@host]# mysqladmin -u root -p drop [DB]

Enter password:******

How to remove selected commit log entries from a Git repository while keeping their changes?

One more way,

git rebase -i ad0389efc1a79b1f9c4dd6061dca6edc1d5bb78a (C's hash)
and
git push origin master  -f

pick the hash that you want to use it as a base, and the above command should make it interactive so you can squash all the top messages ( you need to leave the oldest )

Nginx not picking up site in sites-enabled?

Include sites-available/default in sites-enabled/default. It requires only one line.

In sites-enabled/default (new config version?):

It seems that the include path is relative to the file that included it

include sites-available/default;

See the include documentation.


I believe that certain versions of nginx allows including/linking to other files purely by having a single line with the relative path to the included file. (At least that's what it looked like in some "inherited" config files I've been using, until a new nginx version broke them.)

In sites-enabled/default (old config version?):

It seems that the include path is relative to the current file

../sites-available/default

Angular4 - No value accessor for form control

The error means, that Angular doesn't know what to do when you put a formControl on a div. To fix this, you have two options.

  1. You put the formControlName on an element, that is supported by Angular out of the box. Those are: input, textarea and select.
  2. You implement the ControlValueAccessor interface. By doing so, you're telling Angular "how to access the value of your control" (hence the name). Or in simple terms: What to do, when you put a formControlName on an element, that doesn't naturally have a value associated with it.

Now, implementing the ControlValueAccessor interface can be a bit daunting at first. Especially because there isn't much good documentation of this out there and you need to add a lot of boilerplate to your code. So let me try to break this down in some simple-to-follow steps.

Move your form control into its own component

In order to implement the ControlValueAccessor, you need to create a new component (or directive). Move the code related to your form control there. Like this it will also be easily reusable. Having a control already inside a component might be the reason in the first place, why you need to implement the ControlValueAccessor interface, because otherwise you will not be able to use your custom component together with Angular forms.

Add the boilerplate to your code

Implementing the ControlValueAccessor interface is quite verbose, here's the boilerplate that comes with it:

import {Component, OnInit, forwardRef} from '@angular/core';
import {ControlValueAccessor, FormControl, NG_VALUE_ACCESSOR} from '@angular/forms';


@Component({
  selector: 'app-custom-input',
  templateUrl: './custom-input.component.html',
  styleUrls: ['./custom-input.component.scss'],

  // a) copy paste this providers property (adjust the component name in the forward ref)
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => CustomInputComponent),
      multi: true
    }
  ]
})
// b) Add "implements ControlValueAccessor"
export class CustomInputComponent implements ControlValueAccessor {

  // c) copy paste this code
  onChange: any = () => {}
  onTouch: any = () => {}
  registerOnChange(fn: any): void {
    this.onChange = fn;
  }
  registerOnTouched(fn: any): void {
    this.onTouch = fn;
  }

  // d) copy paste this code
  writeValue(input: string) {
    // TODO
  }

So what are the individual parts doing?

  • a) Lets Angular know during runtime that you implemented the ControlValueAccessor interface
  • b) Makes sure you're implementing the ControlValueAccessor interface
  • c) This is probably the most confusing part. Basically what you're doing is, you give Angular the means to override your class properties/methods onChange and onTouch with it's own implementation during runtime, such that you can then call those functions. So this point is important to understand: You don't need to implement onChange and onTouch yourself (other than the initial empty implementation). The only thing your doing with (c) is to let Angular attach it's own functions to your class. Why? So you can then call the onChange and onTouch methods provided by Angular at the appropriate time. We'll see how this works down below.
  • d) We'll also see how the writeValue method works in the next section, when we implement it. I've put it here, so all required properties on ControlValueAccessor are implemented and your code still compiles.

Implement writeValue

What writeValue does, is to do something inside your custom component, when the form control is changed on the outside. So for example, if you have named your custom form control component app-custom-input and you'd be using it in the parent component like this:

<form [formGroup]="form">
  <app-custom-input formControlName="myFormControl"></app-custom-input>
</form>

then writeValue gets triggered whenever the parent component somehow changes the value of myFormControl. This could be for example during the initialization of the form (this.form = this.formBuilder.group({myFormControl: ""});) or on a form reset this.form.reset();.

What you'll typically want to do if the value of the form control changes on the outside, is to write it to a local variable which represents the form control value. For example, if your CustomInputComponent revolves around a text based form control, it could look like this:

writeValue(input: string) {
  this.input = input;
}

and in the html of CustomInputComponent:

<input type="text"
       [ngModel]="input">

You could also write it directly to the input element as described in the Angular docs.

Now you have handled what happens inside of your component when something changes outside. Now let's look at the other direction. How do you inform the outside world when something changes inside of your component?

Calling onChange

The next step is to inform the parent component about changes inside of your CustomInputComponent. This is where the onChange and onTouch functions from (c) from above come into play. By calling those functions you can inform the outside about changes inside your component. In order to propagate changes of the value to the outside, you need to call onChange with the new value as the argument. For example, if the user types something in the input field in your custom component, you call onChange with the updated value:

<input type="text"
       [ngModel]="input"
       (ngModelChange)="onChange($event)">

If you check the implementation (c) from above again, you'll see what's happening: Angular bound it's own implementation to the onChange class property. That implementation expects one argument, which is the updated control value. What you're doing now is you're calling that method and thus letting Angular know about the change. Angular will now go ahead and change the form value on the outside. This is the key part in all this. You told Angular when it should update the form control and with what value by calling onChange. You've given it the means to "access the control value".

By the way: The name onChange is chosen by me. You could choose anything here, for example propagateChange or similar. However you name it though, it will be the same function that takes one argument, that is provided by Angular and that is bound to your class by the registerOnChange method during runtime.

Calling onTouch

Since form controls can be "touched", you should also give Angular the means to understand when your custom form control is touched. You can do it, you guessed it, by calling the onTouch function. So for our example here, if you want to stay compliant with how Angular is doing it for the out-of-the-box form controls, you should call onTouch when the input field is blurred:

<input type="text"
       [(ngModel)]="input"
       (ngModelChange)="onChange($event)"
       (blur)="onTouch()">

Again, onTouch is a name chosen by me, but what it's actual function is provided by Angular and it takes zero arguments. Which makes sense, since you're just letting Angular know, that the form control has been touched.

Putting it all together

So how does that look when it comes all together? It should look like this:

// custom-input.component.ts
import {Component, OnInit, forwardRef} from '@angular/core';
import {ControlValueAccessor, FormControl, NG_VALUE_ACCESSOR} from '@angular/forms';


@Component({
  selector: 'app-custom-input',
  templateUrl: './custom-input.component.html',
  styleUrls: ['./custom-input.component.scss'],

  // Step 1: copy paste this providers property
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => CustomInputComponent),
      multi: true
    }
  ]
})
// Step 2: Add "implements ControlValueAccessor"
export class CustomInputComponent implements ControlValueAccessor {

  // Step 3: Copy paste this stuff here
  onChange: any = () => {}
  onTouch: any = () => {}
  registerOnChange(fn: any): void {
    this.onChange = fn;
  }
  registerOnTouched(fn: any): void {
    this.onTouch = fn;
  }

  // Step 4: Define what should happen in this component, if something changes outside
  input: string;
  writeValue(input: string) {
    this.input = input;
  }

  // Step 5: Handle what should happen on the outside, if something changes on the inside
  // in this simple case, we've handled all of that in the .html
  // a) we've bound to the local variable with ngModel
  // b) we emit to the ouside by calling onChange on ngModelChange

}
// custom-input.component.html
<input type="text"
       [(ngModel)]="input"
       (ngModelChange)="onChange($event)"
       (blur)="onTouch()">
// parent.component.html
<app-custom-input [formControl]="inputTwo"></app-custom-input>

// OR

<form [formGroup]="form" >
  <app-custom-input formControlName="myFormControl"></app-custom-input>
</form>

More Examples

Nested Forms

Note that Control Value Accessors are NOT the right tool for nested form groups. For nested form groups you can simply use an @Input() subform instead. Control Value Accessors are meant to wrap controls, not groups! See this example how to use an input for a nested form: https://stackblitz.com/edit/angular-nested-forms-input-2

Sources

Web Service vs WCF Service

The major difference is time-out, WCF Service has timed-out when there is no response, but web-service does not have this property.

console.log timestamps in Chrome?

In Chrome, there is the option is Console Settings (Developer Tools -> Console -> Settings [upper-right corner] ) named "Show timestamps" which is exactly what I needed.

I've just found it. No other dirty hacks needed that destroys placeholders and erases place in the code where the messages was logged from.

Update for Chrome 68+

The "Show timestamps" setting has been moved to the Preferences pane of the "DevTools settings", found in the upper-right corner of the DevTools drawer:

enter image description here

Sort dataGridView columns in C# ? (Windows Form)

dataGridView1.Sort(dataGridView1.Columns[0],ListSortDirection.Ascending);

How to count days between two dates in PHP?

Use DateTime::diff (aka date_diff):

$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);

Or:

$datetime1 = date_create('2009-10-11');
$datetime2 = date_create('2009-10-13');
$interval = date_diff($datetime1, $datetime2);

You can then get the interval as a integer by calling $interval->days.

No MediaTypeFormatter is available to read an object of type 'String' from content with media type 'text/plain'

Or you can just create your own MediaTypeFormatter. I use this for text/html. If you add text/plain to it, it'll work for you too:

public class TextMediaTypeFormatter : MediaTypeFormatter
{
    public TextMediaTypeFormatter()
    {
        SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
    }

    public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
    {
        return ReadFromStreamAsync(type, readStream, content, formatterLogger, CancellationToken.None);
    }

    public override async Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger, CancellationToken cancellationToken)
    {
        using (var streamReader = new StreamReader(readStream))
        {
            return await streamReader.ReadToEndAsync();
        }
    }

    public override bool CanReadType(Type type)
    {
        return type == typeof(string);
    }

    public override bool CanWriteType(Type type)
    {
        return false;
    }
}

Finally you have to assign this to the HttpMethodContext.ResponseFormatter property.

Changing element style attribute dynamically using JavaScript

In addition to other answers, if you want to use the dash notition for style properties, you can also use:

document.getElementById("xyz").style["padding-top"] = "10px";

How to schedule a task to run when shutting down windows

One workaround might be to write a simple batch file to run the program then shutdown the computer.

You can shut down from the command line -- so your script could be fairly simple:

c:\directory\myProgram.exe
C:\WINDOWS\system32\shutdown.exe -s -f -t 0

Cannot open local file - Chrome: Not allowed to load local resource

Know this is kind of old, but see many questions like this...

We use Chrome a lot in the classroom and it is a must to working with local files.

What we have been using is "Web Server for Chrome". You start it up, choose the folder wishing to work with and go to URL (like 127.0.0.1:port you chose)

It is a simple server and cannot use PHP but for simple work, might be your solution:

https://chrome.google.com/webstore/detail/web-server-for-chrome/ofhbbkphhbklhfoeikjpcbhemlocgigb

async at console app in C#?

As a quick and very scoped solution:

Task.Result

Both Task.Result and Task.Wait won't allow to improving scalability when used with I/O, as they will cause the calling thread to stay blocked waiting for the I/O to end.

When you call .Result on an incomplete Task, the thread executing the method has to sit and wait for the task to complete, which blocks the thread from doing any other useful work in the meantime. This negates the benefit of the asynchronous nature of the task.

notasync

PHP DateTime __construct() Failed to parse time string (xxxxxxxx) at position x

You should use setTimestamp instead, if you hardcode it:

$start_date = new DateTime();
$start_date->setTimestamp(1372622987);

in your case

$start_date = new DateTime();
$start_date->setTimestamp($dbResult->db_timestamp);

Two's Complement in Python

Since Python 3.2, there are built-in functions for byte manipulation: https://docs.python.org/3.4/library/stdtypes.html#int.to_bytes.

By combining to_bytes and from_bytes, you get

def twos(val_str, bytes):
    import sys
    val = int(val_str, 2)
    b = val.to_bytes(bytes, byteorder=sys.byteorder, signed=False)                                                          
    return int.from_bytes(b, byteorder=sys.byteorder, signed=True)

Check:

twos('11111111', 1)  # gives -1
twos('01111111', 1)  # gives 127

For older versions of Python, travc's answer is good but it does not work for negative values if one would like to work with integers instead of strings. A twos' complement function for which f(f(val)) == val is true for each val is:

def twos_complement(val, nbits):
    """Compute the 2's complement of int value val"""
    if val < 0:
        val = (1 << nbits) + val
    else:
        if (val & (1 << (nbits - 1))) != 0:
            # If sign bit is set.
            # compute negative value.
            val = val - (1 << nbits)
    return val

How to expand 'select' option width after the user wants to select an option

A simple solution I used for an existing site in IE (using jQuery, but I can post back with eventListener code if you really don't know JS that well) is the following:

if (jQuery.browser.msie) {
  jQuery('#mySelect').focus(function() {
    jQuery(this).width('auto');
  }).bind('blur change', function() {
    jQuery(this).width('100%');
  });
};

Of course, use a variable (var cWidth = jQuery('#mySelect').width();) to store the previous width, but this is all that was required for ours to work as you'd expect.

How do I specify different layouts for portrait and landscape orientations?

Just a reminder:

Remove orientation from android:configChanges attribute for the activity in your manifest xml file if you defined it:

android:configChanges="orientation|screenLayout|screenSize"

Why does ANT tell me that JAVA_HOME is wrong when it is not?

The semicolon was throwing me off: I had JAVA_HOME set to "C:\jdk1.6.0_26;" instead of "C:\jdk1.6.0_26". I removed the trailing semicolon after following Jon Skeet's suggestion to examine the ant.bat file. This is part of that file:

if "%JAVA_HOME%" == "" goto noJavaHome
if not exist "%JAVA_HOME%\bin\java.exe" goto noJavaHome

So the semi-colon wasn't being trimmed off the end, causing this to fail to find the file, therefore defaulting to "C:\Java\jre6" or something like that.

The confusing part is that the HowtoBuild page states to use the semi-colon, but that seems to break it.

Initialize Array of Objects using NSArray

This might not really answer the question, but just in case someone just need to quickly send a string value to a function that require a NSArray parameter.

NSArray *data = @[@"The String Value"];

if you need to send more than just 1 string value, you could also use

NSArray *data = @[@"The String Value", @"Second String", @"Third etc"];

then you can send it to the function like below

theFunction(data);

ERROR Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies

check below link in which you can download suitable AjaxControlToolkit which suits your .NET version.

http://ajaxcontroltoolkit.codeplex.com/releases/view/43475

AjaxControlToolkit.Binary.NET4.zip - used for .NET 4.0

AjaxControlToolkit.Binary.NET35.zip - used for .NET 3.5

JavaScript: Upload file

Pure JS

You can use fetch optionally with await-try-catch

let photo = document.getElementById("image-file").files[0];
let formData = new FormData();
     
formData.append("photo", photo);
fetch('/upload/image', {method: "POST", body: formData});

_x000D_
_x000D_
async function SavePhoto(inp) 
{
    let user = { name:'john', age:34 };
    let formData = new FormData();
    let photo = inp.files[0];      
         
    formData.append("photo", photo);
    formData.append("user", JSON.stringify(user)); 
    
    const ctrl = new AbortController()    // timeout
    setTimeout(() => ctrl.abort(), 5000);
    
    try {
       let r = await fetch('/upload/image', 
         {method: "POST", body: formData, signal: ctrl.signal}); 
       console.log('HTTP response code:',r.status); 
    } catch(e) {
       console.log('Huston we have problem...:', e);
    }
    
}
_x000D_
<input id="image-file" type="file" onchange="SavePhoto(this)" >
<br><br>
Before selecting the file open chrome console > network tab to see the request details.
<br><br>
<small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>

<br><br>
(in stack overflow snippets there is problem with error handling, however in <a href="https://jsfiddle.net/Lamik/b8ed5x3y/5/">jsfiddle version</a> for 404 errors 4xx/5xx are <a href="https://stackoverflow.com/a/33355142/860099">not throwing</a> at all but we can read response status which contains code)
_x000D_
_x000D_
_x000D_

Old school approach - xhr

let photo = document.getElementById("image-file").files[0];  // file from input
let req = new XMLHttpRequest();
let formData = new FormData();

formData.append("photo", photo);                                
req.open("POST", '/upload/image');
req.send(formData);

_x000D_
_x000D_
function SavePhoto(e) 
{
    let user = { name:'john', age:34 };
    let xhr = new XMLHttpRequest();
    let formData = new FormData();
    let photo = e.files[0];      
    
    formData.append("user", JSON.stringify(user));   
    formData.append("photo", photo);
    
    xhr.onreadystatechange = state => { console.log(xhr.status); } // err handling
    xhr.timeout = 5000;
    xhr.open("POST", '/upload/image'); 
    xhr.send(formData);
}
_x000D_
<input id="image-file" type="file" onchange="SavePhoto(this)" >
<br><br>
Choose file and open chrome console > network tab to see the request details.
<br><br>
<small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>

<br><br>
(the stack overflow snippets, has some problem with error handling - the xhr.status is zero (instead of 404) which is similar to situation when we run script from file on <a href="https://stackoverflow.com/a/10173639/860099">local disc</a> - so I provide also js fiddle version which shows proper http error code <a href="https://jsfiddle.net/Lamik/k6jtq3uh/2/">here</a>)
_x000D_
_x000D_
_x000D_

SUMMARY

  • In server side you can read original file name (and other info) which is automatically included to request by browser in filename formData parameter.
  • You do NOT need to set request header Content-Type to multipart/form-data - this will be set automatically by browser.
  • Instead of /upload/image you can use full address like http://.../upload/image.
  • If you want to send many files in single request use multiple attribute: <input multiple type=... />, and attach all chosen files to formData in similar way (e.g. photo2=...files[2];... formData.append("photo2", photo2);)
  • You can include additional data (json) to request e.g. let user = {name:'john', age:34} in this way: formData.append("user", JSON.stringify(user));
  • You can set timeout: for fetch using AbortController, for old approach by xhr.timeout= milisec
  • This solutions should work on all major browsers.

Comparing two .jar files

  1. Rename .jar to .zip
  2. Extract
  3. Decompile class files with jad
  4. Recursive diff

Fully change package name including company domain

@Luch Filip's solution works well if you just want to rename the App package. In my case, I also want to rename the source package too, so as not to confuse things.

Only 2 steps are needed:

  1. Click on your source folder e.g. com.company.example > Shift + F6 (Refactor->Rename...) > Rename Package > enter your desired name.

  2. Go to your AndroidManifest.xml, click on your package name > Shift + F6 (Refactor->Rename...) > enter same name as above.

Step 1 will automatically rename your R.java folder, and you can build straight away.

Giving multiple URL patterns to Servlet Filter

If an URL pattern starts with /, then it's relative to the context root. The /Admin/* URL pattern would only match pages on http://localhost:8080/EMS2/Admin/* (assuming that /EMS2 is the context path), but you have them actually on http://localhost:8080/EMS2/faces/Html/Admin/*, so your URL pattern never matches.

You need to prefix your URL patterns with /faces/Html as well like so:

<url-pattern>/faces/Html/Admin/*</url-pattern>

You can alternatively also just reconfigure your web project structure/configuration so that you can get rid of the /faces/Html path in the URLs so that you can just open the page by for example http://localhost:8080/EMS2/Admin/Upload.xhtml.

Your filter mapping syntax is all fine. However, a simpler way to specify multiple URL patterns is to just use only one <filter-mapping> with multiple <url-pattern> entries:

<filter-mapping>
    <filter-name>LoginFilter</filter-name>
    <url-pattern>/faces/Html/Employee/*</url-pattern>
    <url-pattern>/faces/Html/Admin/*</url-pattern>
    <url-pattern>/faces/Html/Supervisor/*</url-pattern>
</filter-mapping>

What do I use for a max-heap implementation in Python?

The easiest and ideal solution

Multiply the values by -1

There you go. All the highest numbers are now the lowest and vice versa.

Just remember that when you pop an element to multiply it with -1 in order to get the original value again.

What characters can be used for up/down triangle (arrow without stem) for display in HTML?

Unicode arrows heads:

  • ? - U+25B2 BLACK UP-POINTING TRIANGLE
  • ? - U+25BC BLACK DOWN-POINTING TRIANGLE
  • ? - U+25B4 SMALL BLACK UP-POINTING TRIANGLE
  • ? - U+25BE SMALL BLACK DOWN-POINTING TRIANGLE

For ? and ? use &#x25B2; and &#x25BC; respectively if you cannot include Unicode characters directly (use UTF-8!).

Note that the font support for the smaller versions is not as good. Better to use the large versions in smaller font.

More Unicode arrows are at:

Lastly, these arrows are not ASCII, including ? and ?: they are Unicode.

Set Locale programmatically

As of 2020 language management become easy! All you have to do is:

  1. Call to Activity.applyOverrideConfiguration
  2. And call to Locale.setDefault

You must call those from the activity constructor since you can call to applyOverrideConfiguration only once, and the system calls it pretty early.

And watch out from app-bundles, Google will split your APK by language resources automatically when using app-bundles. Check out the new API and the workaround here.


I created a helper class to help you with it. In my implementation G.app is the application context. Also, I need to access resources from the app context so I use the Res class for it, this one is optional, but I provide its code as well.

Usage

public BaseActivity(){
    LanguageUtility.init(this);
}

public void changeLanguage(Local local){
    // you must recreat your activity after you call this
    LanguageUtillity.setDefaultLanguage(local, this);
}

Source code

public class LanguageUtility {

    private static Configuration configuration;

    public static void setDefaultLanguage(Locale locale, Context context) {
        Locale.setDefault(locale);

        context.getSharedPreferences("LocaleSettings", Context.MODE_PRIVATE)
                .edit()
                .putString("language", locale.getLanguage())
                .putString("country", locale.getCountry())
                .putString("variant", locale.getVariant())
                .apply();

        configuration = createConfiguration(context);
        Res.updateContext();
    }

    /**
     * Used to update your app context in case you cache it.
     */
    public static Context createConfigurationContext(Context context) {
        return context.createConfigurationContext(getConfiguration(context));
    }

    public static void init(Activity activity) {
        activity.applyOverrideConfiguration(LanguageUtility.getConfiguration(G.app));
        // you can't access sharedPrefferences from activity constructor 
        // with activity context, so I used the app context.
        Locale.setDefault(getLocale(G.app));
    }

    @NotNull
    private static Configuration getConfiguration(Context context) {
        if (configuration == null) {
            configuration = createConfiguration(context);
        }
        return configuration;
    }

    @NotNull
    private static Configuration createConfiguration(Context context) {
        Locale locale = getLocale(context);
        Configuration configuration = new Configuration();
        configuration.setLocale(locale);
        LanguageUtility.configuration = configuration;
        return configuration;
    }

    @NotNull
    private static Locale getLocale(Context context) {
        Locale aDefault = Locale.getDefault();
        SharedPreferences preferences =
                context.getSharedPreferences("LocaleSettings", Context.MODE_PRIVATE);
        String language = preferences.getString("language", aDefault.getLanguage());
        String country = preferences.getString("country", aDefault.getCountry());
        String variant = preferences.getString("variant", aDefault.getVariant());
        return new Locale(language, country, variant);
    }
}

An optional Res class.

public class Res {

    @SuppressLint("StaticFieldLeak")
    public static Context appLocalContext = LanguageUtility.createConfigurationContext(G.app);

    public static void updateContext() {
        appLocalContext = LanguageUtility.createConfigurationContext(G.app);
    }

    public static String getString(@StringRes int id, Object... formatArgs) {
        return appLocalContext.getResources().getString(id, formatArgs);
    }

    public static int getColor(@ColorRes int id) {
        return G.app.getColor(id);
    }
}

How to use python numpy.savetxt to write strings and float number to an ASCII file?

The currently accepted answer does not actually address the question, which asks how to save lists that contain both strings and float numbers. For completeness I provide a fully working example, which is based, with some modifications, on the link given in @joris comment.

import numpy as np

names  = np.array(['NAME_1', 'NAME_2', 'NAME_3'])
floats = np.array([ 0.1234 ,  0.5678 ,  0.9123 ])

ab = np.zeros(names.size, dtype=[('var1', 'U6'), ('var2', float)])
ab['var1'] = names
ab['var2'] = floats

np.savetxt('test.txt', ab, fmt="%10s %10.3f")

Update: This example also works properly in Python 3 by using the 'U6' Unicode string dtype, when creating the ab structured array, instead of the 'S6' byte string. The latter dtype would work in Python 2.7, but would write strings like b'NAME_1' in Python 3.

Center a popup window on screen?

This hybrid solution worked for me, both on single and dual screen setup

function popupCenter (url, title, w, h) {
    // Fixes dual-screen position                              Most browsers      Firefox
    const dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : window.screenX;
    const dualScreenTop = window.screenTop !== undefined ? window.screenTop : window.screenY;
    const left = (window.screen.width/2)-(w/2) + dualScreenLeft;
    const top = (window.screen.height/2)-(h/2) + dualScreenTop;
    return window.open(url, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width='+w+', height='+h+', top='+top+', left='+left);
}

How to make JavaScript execute after page load?

_x000D_
_x000D_
<script type="text/javascript">_x000D_
$(window).bind("load", function() { _x000D_
_x000D_
// your javascript event here_x000D_
_x000D_
});_x000D_
</script>
_x000D_
_x000D_
_x000D_

Is there a date format to display the day of the week in java?

I know the question is about getting the day of week as string (e.g. the short name), but for anybody who is looking for the numeric day of week (as I was), you can use the new "u" format string, supported since Java 7. For example:

new SimpleDateFormat("u").format(new Date());

returns today's day-of-week index, namely: 1 = Monday, 2 = Tuesday, ..., 7 = Sunday.

How to find the nearest parent of a Git branch?

An alternative: git rev-list master | grep "$(git rev-list HEAD)" | head -1

Get the last commit that it's both my branch and master (or whatever branch you want to specify)

Firing a Keyboard Event in Safari, using JavaScript

This is due to a bug in Webkit.

You can work around the Webkit bug using createEvent('Event') rather than createEvent('KeyboardEvent'), and then assigning the keyCode property. See this answer and this example.

Regex to match any character including new lines

Add the s modifier to your regex to cause . to match newlines:

$string =~ /(START)(.+?)(END)/s;