Programs & Examples On #Viewswitcher

ViewSwitcher is an Android widget that switches between two views only one being visible at a time.

iPhone - Grand Central Dispatch main thread

One place where it's useful is for UI activities, like setting a spinner before a lengthy operation:

- (void) handleDoSomethingButton{

    [mySpinner startAnimating];

    (do something lengthy)
    [mySpinner stopAnimating];
}

will not work, because you are blocking the main thread during your lengthy thing and not letting UIKit actually start the spinner.

- (void) handleDoSomethingButton{
     [mySpinner startAnimating];

     dispatch_async (dispatch_get_main_queue(), ^{
          (do something lengthy)
          [mySpinner stopAnimating];
    });
}

will return control to the run loop, which will schedule UI updating, starting the spinner, then will get the next thing off the dispatch queue, which is your actual processing. When your processing is done, the animation stop is called, and you return to the run loop, where the UI then gets updated with the stop.

LEFT OUTER JOIN in LINQ

As stated on:

101 LINQ Samples - Left outer join

var q =
    from c in categories
    join p in products on c.Category equals p.Category into ps
    from p in ps.DefaultIfEmpty()
    select new { Category = c, ProductName = p == null ? "(No products)" : p.ProductName };

Android: Clear the back stack

What about adding in manifests file for related activity :

android:noHistory="true"

to the activity definition of B and C ? They will not be added to the backstack. Not sure if that is what you want.

phpmyadmin "no data received to import" error, how to fix?

Open your php.ini file use CNTRL+F to search for the following settings which may be the culprit:

  • file_uploads
  • upload_max_filesize
  • post_max_size
  • memory_limit
  • max_input_time
  • max_execution_time

Make sure to save a copy of the php.ini prior to making changes. You will want to adjust the settings to accommodate your file size, and increase input and/or execution time.

Remember to restart your services after making changes.

Warning! There may be some unforeseen drawbacks if you adjust these settings too liberally. I am not expert enough to know this for sure.

Source: http://forum.wampserver.com/read.php?2,20757,20935

Add image to left of text via css

This works great

.create:before{
    content: "";
    display: block;
    background: url('somewhere.jpg') no-repeat;
    width: 25px;
    height: 25px;
    float: left;
}

Check line for unprintable characters while reading text file

The answer by @T.J.Crowder is Java 6 - in java 7 the valid answer is the one by @McIntosh - though its use of Charset for name for UTF -8 is discouraged:

List<String> lines = Files.readAllLines(Paths.get("/tmp/test.csv"),
    StandardCharsets.UTF_8);
for(String line: lines){ /* DO */ }

Reminds a lot of the Guava way posted by Skeet above - and of course same caveats apply. That is, for big files (Java 7):

BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8);
for (String line = reader.readLine(); line != null; line = reader.readLine()) {}

Swift days between two NSDates

Swift 5

Working, you need to set the time to be the same for both days, if you are off by seconds it will be wrong

func daysBetween(start: Date, end: Date) -> Int {
    let start = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: start)!
    let end = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: end)!
    return Calendar.current.dateComponents([.day], from: start, to: end).day ?? 0
}

How to show first commit by 'git log'?

Short answer

git rev-list --max-parents=0 HEAD

(from tiho's comment. As Chris Johnsen notices, --max-parents was introduced after this answer was posted.)

Explanation

Technically, there may be more than one root commit. This happens when multiple previously independent histories are merged together. It is common when a project is integrated via a subtree merge.

The git.git repository has six root commits in its history graph (one each for Linus’s initial commit, gitk, some initially separate tools, git-gui, gitweb, and git-p4). In this case, we know that e83c516 is the one we are probably interested in. It is both the earliest commit and a root commit.

It is not so simple in the general case.

Imagine that libfoo has been in development for a while and keeps its history in a Git repository (libfoo.git). Independently, the “bar” project has also been under development (in bar.git), but not for as long libfoo (the commit with the earliest date in libfoo.git has a date that precedes the commit with the earliest date in bar.git). At some point the developers of “bar” decide to incorporate libfoo into their project by using a subtree merge. Prior to this merge it might have been trivial to determine the “first” commit in bar.git (there was probably only one root commit). After the merge, however, there are multiple root commits and the earliest root commit actually comes from the history of libfoo, not “bar”.

You can find all the root commits of the history DAG like this:

git rev-list --max-parents=0 HEAD

For the record, if --max-parents weren't available, this does also work:

git rev-list --parents HEAD | egrep "^[a-f0-9]{40}$"

If you have useful tags in place, then git name-rev might give you a quick overview of the history:

git rev-list --parents HEAD | egrep "^[a-f0-9]{40}$" | git name-rev --stdin

Bonus

Use this often? Hard to remember? Add a git alias for quick access

git config --global alias.first "rev-list --max-parents=0 HEAD"

Now you can simply do

git first

TypeError: unhashable type: 'dict', when dict used as a key for another dict

From the error, I infer that referenceElement is a dictionary (see repro below). A dictionary cannot be hashed and therefore cannot be used as a key to another dictionary (or itself for that matter!).

>>> d1, d2 = {}, {}
>>> d1[d2] = 1
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: unhashable type: 'dict'

You probably meant either for element in referenceElement.keys() or for element in json['referenceElement'].keys(). With more context on what types json and referenceElement are and what they contain, we will be able to better help you if neither solution works.

Removing items from a list

You can't and shouldn't modify a list while iterating over it. You can solve this by temporarely saving the objects to remove:

List<Object> toRemove = new ArrayList<Object>();
for(Object a: list){
    if(a.getXXX().equalsIgnoreCase("AAA")){
        toRemove.add(a);
    }
}
list.removeAll(toRemove);

How to properly assert that an exception gets raised in pytest?

Right way is using pytest.raises but I found interesting alternative way in comments here and want to save it for future readers of this question:

try:
    thing_that_rasises_typeerror()
    assert False
except TypeError:
    assert True

textarea character limit

Quick and dirty universal jQuery version. Supports copy/paste.

$('textarea[maxlength]').on('keypress mouseup', function(){
    return !($(this).val().length >= $(this).attr('maxlength'));
});

Adding a parameter to the URL with JavaScript

If you have a string with url that you want to decorate with a param, you could try this:

urlstring += ( urlstring.match( /[\?]/g ) ? '&' : '?' ) + 'param=value';

This means that ? will be the prefix of the parameter, but if you already have ? in urlstring, than & will be the prefix.

I would also recommend to do encodeURI( paramvariable ) if you didn't hardcoded parameter, but it is inside a paramvariable; or if you have funny characters in it.

See javascript URL Encoding for usage of the encodeURI function.

Getting the error "Missing $ inserted" in LaTeX

In my code, when I got the error, I checked the possible source, In a line, I had typed a beginning \[ and an ending \] due to which the error of missing $ appeared though I tried using $ for both the brackets. Removing the brackets or using $[$ instead of $\[$ solved my problem. If you've something like that, try altering.

Change the color of cells in one column when they don't match cells in another column

  1. Select your range from cell A (or the whole columns by first selecting column A). Make sure that the 'lighter coloured' cell is A1 then go to conditional formatting, new rule:

    enter image description here

  2. Put the following formula and the choice of your formatting (notice that the 'lighter coloured' cell comes into play here, because it is being used in the formula):

    =$A1<>$B1
    

    enter image description here

  3. Then press OK and that should do it.

    enter image description here

How to get the azure account tenant Id?

If you have installed Azure CLI 2.0 in your machine, you should be able to get the list of subscription that you belong to with the following command,

az login

if you want to see as a table output you could just use

az account get-access-token --query tenant --output tsv

or you could use the Rest API

https://docs.microsoft.com/en-us/rest/api/resources/tenants/list

The storage engine for the table doesn't support repair. InnoDB or MyISAM?

First is you have to understand the difference between MyISAM and InnoDB Engines. And this is clearly stated on this link. You can use this sql statement if you want to convert InnoDB to MyISAM:

 ALTER TABLE t1 ENGINE=MyISAM;

Incorrect syntax near ''

Panagiotis Kanavos is right, sometimes copy and paste T-SQL can make appear unwanted characters...

I finally found a simple and fast way (only Notepad++ needed) to detect which character is wrong, without having to manually rewrite the whole statement: there is no need to save any file to disk.

It's pretty quick, in Notepad++:

  • Click "New file"
  • Check under the menu "Encoding": the value should be "Encode in UTF-8"; set it if it's not
  • Paste your text enter image description here
  • From Encoding menu, now click "Encode in ANSI" and check again your text enter image description here

You should easily find the wrong character(s)

TypeError: Object of type 'bytes' is not JSON serializable

I guess the answer you need is referenced here Python sets are not json serializable

Not all datatypes can be json serialized . I guess pickle module will serve your purpose.

Android SeekBar setOnSeekBarChangeListener

All answers are correct, but you need to convert a long big fat number into a timer first:

    public String toTimer(long milliseconds){
    String finalTimerString = "";
    String secondsString;
    // Convert total duration into time
    int hours = (int)( milliseconds / (1000*60*60));
    int minutes = (int)(milliseconds % (1000*60*60)) / (1000*60);
    int seconds = (int) ((milliseconds % (1000*60*60)) % (1000*60) / 1000);
    // Add hours if there
    if(hours > 0){
        finalTimerString = hours + ":";
    }
    // Prepending 0 to seconds if it is one digit
    if(seconds < 10){
        secondsString = "0" + seconds;
    }else{
        secondsString = "" + seconds;}
    finalTimerString = finalTimerString + minutes + ":" + secondsString;
    // return timer string
    return finalTimerString;
}

And this is how you use it:

@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
textView.setText(String.format("%s", toTimer(progress)));        
}

release Selenium chromedriver.exe from memory

Kill Multiple Processes From the Command Line The first thing you’ll need to do is open up a command prompt, and then use the taskkill command with the following syntax:

taskkill /F /IM <processname.exe> /T

These parameters will forcibly kill any process matching the name of the executable that you specify. For instance, to kill all iexplore.exe processes, we’d use:

taskkill /F /IM iexplore.exe

enter image description here

How to set the value for Radio Buttons When edit?

    Gender :<br>
    <input type="radio" name="g" value="male"  <?php echo ($g=='Male')?'checked':'' ?>>male <br>
    <input type="radio" name="g" value="female"<?php echo ($g=='female')?'checked':'' ?>>female
            <?php echo $errors['g'];?>

How to grep (search) committed code in the Git history

Adding more to the answers already present. If you know the file in which you might have made do this:

git log --follow -p -S 'search-string' <file-path>

--follow: lists the history of a file

Convert Mercurial project to Git

Some notes of my experience converting Mercurial to Git.

1. hg-fast-export

Using hg-fast-export failed and I needed --force as noted above. Next I got this error:

error: cannot lock ref 'refs/heads/stable': 'refs/heads/stable/sub-branch-name' exists; cannot create 'refs/heads/stable'

Upon completion of the hg-fast-export I ended up with an amputated repo. I think that this repo had a good few orphaned branches and that hg-fast-export needs a somewhat idealised repo. This all seemed a bit rough around the edges, so I moved on to Kiln Harmony (http://blog.fogcreek.com/announcing-kiln-harmony-the-future-of-dvcs/)

2. Kiln

Kiln Harmony does not appear to exist on a free tier account as suggested above. I could choose between Git-only and Mercurial-only repos and there is no option to switch. I raised a support ticket and will share the result if they reply.

3. hg-git

The Hg-Git mercurial plugin (http://hg-git.github.io/) did work for me. FYI on Mac OSX I installed hg-git via macports as follows:

  • sudo port install python27
  • sudo port select --set python python27
  • sudo port install py27-hggit
  • vi ~/.hgrc

.hgrc needs these lines:

[ui]
username = Name Surname <[email protected]>

[extensions]
hgext.bookmarks =
hggit = 

I then had success with:

hg push git+ssh://[email protected]:myaccount/myrepo.git

4. Caveat: Know your repo

All the above are blunt instruments and I only pushed ahead because it took enough time to get the team to use git properly.

Upon first pushing the project per (3) I ended up with all new changes missing. This is because this line of code must be viewed as a guide only:

$ hg bookmark -r default master # make a bookmark of master for default, so a ref gets created

The theory is that the default branch can be deemed to be master when pushing to git, and in my case I inherited a repo where they used 'stable' as the equivalent of master. Moreover, I also discovered that the tip of the repo was a hotfix not yet merged with the 'stable' branch.

Without properly understanding both Mercurial and the repo to be converted, you are probably better off not doing the conversion.

I did the following in order to get the repo ready for a second conversion attempt:

hg update -C stable
hg merge stable/hotfix-feature
hg ci -m "Merge with stable branch"
hg push git+ssh://[email protected]:myaccount/myrepo.git

After this I had a verifiably equivalent project in git, however all the orphaned branches I mentioned earlier are gone. I don't think that is too serious, but I may well live to regret this as an oversight. Therefore my final thought is to keep the original anyway.

Edit: If you just want the latest commit in git, this is simpler than the above merge:

hg book -r tip master
hg push git+ssh://[email protected]:myaccount/myrepo.git

Unicode characters in URLs

For me this is the correct way, This just worked:

    $linker = rawurldecode("$link");
    <a href="<?php echo $link;?>"   target="_blank"><?php echo $linker ;?></a>

This worked, and now links are displayed properly:

http://newspaper.annahar.com/article/121638-????--????-???-??-??????-?????-????-??????-??????-????-??????-?????-????????

Link found on:

http://www.galeriejaninerubeiz.com/newsite/news

Should I use past or present tense in git commit messages?

Who are you writing the message for? And is that reader typically reading the message pre- or post- ownership the commit themselves?

I think good answers here have been given from both perspectives, I’d perhaps just fall short of suggesting there is a best answer for every project. The split vote might suggest as much.

i.e. to summarise:

  • Is the message predominantly for other people, typically reading at some point before they have assumed the change: A proposal of what taking the change will do to their existing code.

  • Is the message predominantly as a journal/record to yourself (or to your team), but typically reading from the perspective of having assumed the change and searching back to discover what happened.

Perhaps this will lead the motivation for your team/project, either way.

How to increase Java heap space for a tomcat app

You need to add the following lines in your catalina.sh file.

export CATALINA_OPTS="-Xms512M -Xmx1024M"

UPDATE : catalina.sh content clearly says -

Do not set the variables in this script. Instead put them into a script setenv.sh in CATALINA_BASE/bin to keep your customizations separate.

So you can add above in setenv.sh instead (create a file if it does not exist).

How to get current url in view in asp.net core 1.0

There is a clean way to get the current URL from a Razor page or PageModel class. That is:

Url.PageLink()

Please note that I meant, the "ASP.NET Core Razor Pages", not the MVC.

I use this method when I want to print the canonical URL meta tag in the ASP.NET Core razor pages. But there is a catch. It will give you the URL which is supposed to be the right URL for that page. Let me explain.

Say, you have defined a route named "id" for your page and therefore, your URL should look like

http://example.com/product?id=34

The Url.PageLink() will give you exactly that URL as shown above.

Now, if the user adds anything extra on that URL, say,

http://example.com/product?id=34&somethingElse

Then, you will not get that "somethingElse" from this method. And that is why it is exactly good for printing canonical URL meta tag in the HTML page.

How do I find the value of $CATALINA_HOME?

Tomcat can tell you in several ways. Here's the easiest:

 $ /path/to/catalina.sh version
Using CATALINA_BASE:   /usr/local/apache-tomcat-7.0.29
Using CATALINA_HOME:   /usr/local/apache-tomcat-7.0.29
Using CATALINA_TMPDIR: /usr/local/apache-tomcat-7.0.29/temp
Using JRE_HOME:        /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home
Using CLASSPATH:       /usr/local/apache-tomcat-7.0.29/bin/bootstrap.jar:/usr/local/apache-tomcat-7.0.29/bin/tomcat-juli.jar
Server version: Apache Tomcat/7.0.29
Server built:   Jul 3 2012 11:31:52
Server number:  7.0.29.0
OS Name:        Mac OS X
OS Version:     10.7.4
Architecture:   x86_64
JVM Version:    1.6.0_33-b03-424-11M3720
JVM Vendor:     Apple Inc.

If you don't know where catalina.sh is (or it never gets called), you can usually find it via ps:

$ ps aux | grep catalina
chris            930   0.0  3.1  2987336 258328 s000  S    Wed01PM   2:29.43 /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/bin/java -Dnop -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Djava.library.path=/usr/local/apache-tomcat-7.0.29/lib -Djava.endorsed.dirs=/usr/local/apache-tomcat-7.0.29/endorsed -classpath /usr/local/apache-tomcat-7.0.29/bin/bootstrap.jar:/usr/local/apache-tomcat-7.0.29/bin/tomcat-juli.jar -Dcatalina.base=/Users/chris/blah/blah -Dcatalina.home=/usr/local/apache-tomcat-7.0.29 -Djava.io.tmpdir=/Users/chris/blah/blah/temp org.apache.catalina.startup.Bootstrap start

From the ps output, you can see both catalina.home and catalina.base. catalina.home is where the Tomcat base files are installed, and catalina.base is where the running configuration of Tomcat exists. These are often set to the same value unless you have configured your Tomcat for multiple (configuration) instances to be launched from a single Tomcat base install.

You can also interrogate the JVM directly if you can't find it in a ps listing:

$ jinfo -sysprops 930 | grep catalina
Attaching to process ID 930, please wait...
Debugger attached successfully.
Server compiler detected.
JVM version is 20.8-b03-424
catalina.base = /Users/chris/blah/blah
[...]
catalina.home = /usr/local/apache-tomcat-7.0.29

If you can't manage that, you can always try to write a JSP that dumps the values of the two system properties catalina.home and catalina.base.

Target a css class inside another css class

I use div instead of tables and am able to target classes within the main class, as below:

CSS

.main {
    .width: 800px;
    .margin: 0 auto;
    .text-align: center;
}
.main .table {
    width: 80%;
}
.main .row {
   / ***something ***/
}
.main .column {
    font-size: 14px;
    display: inline-block;
}
.main .left {
    width: 140px;
    margin-right: 5px;
    font-size: 12px;
}
.main .right {
    width: auto;
    margin-right: 20px;
    color: #fff;
    font-size: 13px;
    font-weight: normal;
}

HTML

<div class="main">
    <div class="table">
        <div class="row">
            <div class="column left">Swing Over Bed</div>
            <div class="column right">650mm</div>
            <div class="column left">Swing In Gap</div>
            <div class="column right">800mm</div>
        </div>
    </div>
</div>

If you want to style a particular "cell" exclusively you can use another sub-class or the id of the div e.g:

.main #red { color: red; }

<div class="main">
    <div class="table">
        <div class="row">
            <div id="red" class="column left">Swing Over Bed</div>
            <div class="column right">650mm</div>
            <div class="column left">Swing In Gap</div>
            <div class="column right">800mm</div>
        </div>
    </div>
</div>

LINK : fatal error LNK1104: cannot open file 'D:\...\MyProj.exe'

I had the same problem, however using Codeblocks. Because of this problem i quited programming because everytime i just wanted to throw my computer out of the window.

I want to thank user963228 whos answer is really a solution to that. You have to put Application Experience on Manual startup(you can do it by searching services in windows 7 start menu, and then find Application Experience and click properties).

This problem happens when people want to tweak theyr windows 7 machine, and they decide to disable some pointless services, so they google some tweaking guide and most of those guides say that Application Experience is safe to disable.

I think this problem should be linked to windows 7 problem not VS problem and it should be more visible - it took me long time to find this solution.

Thanks again!

What's the difference between tilde(~) and caret(^) in package.json?

Tilde ~ matches minor version, if you have installed a package that has 1.4.2 and after your installation, versions 1.4.3 and 1.4.4 are also available if in your package.json it is used as ~1.4.2 then npm install in your project after upgrade will install 1.4.4 in your project. But there is 1.5.0 available for that package then it will not be installed by ~. It is called minor version.

Caret ^ matches major version, if 1.4.2 package is installed in your project and after your installation 1.5.0 is released then ^ will install major version. It will not allow to install 2.1.0 if you have ^1.4.2.

Fixed version if you don't want to change version of package on each installation then used fixed version with out any special character e.g "1.4.2"

Latest Version * If you want to install latest version then only use * in front of package name.

Playing a video in VideoView in Android

VideoView can only Stream 3gp videos I recommend this code to stream your video or try a higher version of android. Try Video Online Streaming.

public void onCreate(Bundle savedInstanceState) {
    setContentView(R.layout.main);
    String videourl = "http://something.com/blah.mp4";
    Uri uri = Uri.parse(videourl);
    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
    intent.setDataAndType(uri, "video/mp4");
    startActivity(intent);
}

Or Click here to watch Android Video Streaming Tutorial.

How to execute IN() SQL queries with Spring's JDBCTemplate effectively?

Many things changed since 2009, but I can only find answers saying you need to use NamedParametersJDBCTemplate.

For me it works if I just do a

db.query(sql, new MyRowMapper(), StringUtils.join(listeParamsForInClause, ","));

using SimpleJDBCTemplate or JDBCTemplate

Changing the resolution of a VNC session in linux

I think that depends on your window manager.

I'm a windows user, so this might be a wrong guess, but: Isn't there something called X-Server running on linux machines - at least on ones that might be interesting targets for VNC - that you can connect to with "X-Clients"?

VNC just takes everything that's on the screen and "tunnels it through your network". If I'm not totally wrong then the "X" protocol should give you the chance to use your client's desktop resolution.

Give X-Server on Wikipedia a try, that might give you a rough overview.

mssql '5 (Access is denied.)' error during restoring database

In my case I had to check the box in Overwrite the existing database (WITH REPLACE) under Options tab on Restore Database page.

The reason I was getting this error: because there was already an MDF file present for the database and it was not getting overwritten.

Hope this will help someone.

Getting a list item by index

You can use the ElementAt extension method on the list.

For example:

// Get the first item from the list

using System.Linq;

var myList = new List<string>{ "Yes", "No", "Maybe"};
var firstItem = myList.ElementAt(0);

// Do something with firstItem

When does Git refresh the list of remote branches?

The OP did not ask for cleanup for all remotes, rather for all branches of default remote.

So git fetch --prune is what should be used.

Setting git config remote.origin.prune true makes --prune automatic. In that case just git fetch will also prune stale remote branches from the local copy. See also Automatic prune with Git fetch or pull.

Note that this does not clean local branches that are no longer tracking a remote branch. See How to prune local tracking branches that do not exist on remote anymore for that.

"pip install json" fails on Ubuntu

json is a built-in module, you don't need to install it with pip.

align textbox and text/labels in html?

You have two boxes, left and right, for each label/input pair. Both boxes are in one row and have fixed width. Now, you just have to make label text float to the right with text-align: right;

Here's a simple example:

http://jsfiddle.net/qP46X/

Difference between break and continue statement

Break Statement

Sometimes it’s necessary to exit a loop before the loop has finished fully iterating over all the step values. For example, looping over a list of numbers until you find a number that satisfies a certain condition. Or looping over a stream of characters from a file until a certain character is read.

In the following example, we’re using a simple for loop to print out values from 0 to 9:

for(int i=0; i<10; i++) {
  System.out.println(i);
}

Output:

0
1
2
3
4
5
6
7
8
9

Now if we add a break statement when i==4, our code will break out of the loop once i equals 4. You can use the break statement to break out of for loops, while loops and do-while loops. The break statement will only break out of the current loop. In order to break out of an outer loop from a nested inner loop, you would need to use labels with the break statement.

for(int i=0; i<10; i++) {
  System.out.println(i);
  if(i==4) {
    break;
  }
}

Output:

0
1
2
3
4

Continue Statement

Java’s continue statement skips over the current iteration of a loop and goes directly to the next iteration. After calling the continue statement in a for loop, the loop execution will execute the step value and evaluate the boolean condition before proceeding with the next iteration. In the following example, we’re printing out all values from 0 to 9 in a loop but we skip over printing out 4.

for(int i=0; i<10; i++) {
  if(i==4) {
    continue;
  }
  System.out.println(i);
}

Output:

0
1
2
3
5 <---- SKIPPED OVER 4 and continued with next loop iteration
6
7
8
9

Loop Label - Break Statement You can use labels within nested loops by specifying where you want execution to continue after breaking out of an inner loop. Normally, the break statement will only break out of the innermost loop so when you want to break out of an outer loop, you can use labels to accomplish this, essentially doing something similar to a goto statement.

The following example uses 3 loops, all nested within each other. Since there’s no way completely break out of the outer most loop from inside the inner most loop, we can use the label “outer1” to accomplish this and specify the label next to the break statement.

outer1:
for(int i=0; i<5; i++) {
  for(int j=0; j<4; j++) {
    for(int k=0; k<2; k++) {
      System.out.println("[" + i + "][" + j + "][" + k + "]");
      if(j == 3) {
        break outer1;
      }
    }
  }
}

Output:

[0][0][0]
[0][0][1]
[0][1][0]
[0][1][1]
[0][2][0]
[0][2][1]
[0][3][0]

Notice how the last line displayed is “0[0]” which is where j == 3 and that’s where we called “break outer1;” to break out of the outer most loop.

Loop Labels - Continue Statement

You can also use labels with the continue keyword to continue looping from a specific point. Taking the previous example and just changing one line to specify continue outer1; instead of break outer1; will cause the loop to continue looping from the outer1 label instead of breaking out of the loop. Note how each time continue outer1; is called, the code continues from the outer loop after incrementing the loop index i by 1.

outer1:
for(int i=0; i<5; i++) {
  for(int j=0; j<4; j++) {
    for(int k=0; k<2; k++) {
      System.out.println("[" + i + "][" + j + "][" + k + "]");
      if(j == 3) {
        continue outer1;
    }
  }
}

[0][0][0]
[0][0][1]
[0][1][0]
[0][1][1]
[0][2][0]
[0][2][1]
[0][3][0] <---- CONTINUE WITH LABEL CALLED HERE
[1][0][0] <---- CONTINUES FROM NEXT ITERATION OF OUTER LOOP
[1][0][1]
[1][1][0]
[1][1][1]
[1][2][0]
[1][2][1]
[1][3][0] <---- CONTINUE WITH LABEL CALLED HERE
[2][0][0] <---- CONTINUES FROM NEXT ITERATION OF OUTER LOOP
[2][0][1]
[2][1][0]
[2][1][1]
[2][2][0]
[2][2][1]
[2][3][0] <---- CONTINUE WITH LABEL CALLED HERE
[3][0][0] <---- CONTINUES FROM NEXT ITERATION OF OUTER LOOP
[3][0][1]
[3][1][0]
[3][1][1]
[3][2][0]
[3][2][1]
[3][3][0] <---- CONTINUE WITH LABEL CALLED HERE
[4][0][0] <---- CONTINUES FROM NEXT ITERATION OF OUTER LOOP
[4][0][1]
[4][1][0]
[4][1][1]
[4][2][0]
[4][2][1]
[4][3][0]

Source: Loops in Java – Ultimate Guide

DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server

var userPasswordString = new Buffer(baseAuth, 'base64').toString('ascii');

Change this line from your code to this -

var userPasswordString = Buffer.from(baseAuth, 'base64').toString('ascii');

or in my case, I gave the encoding in reverse order

var userPasswordString = Buffer.from(baseAuth, 'utf-8').toString('base64');

'ls' is not recognized as an internal or external command, operable program or batch file

I'm fairly certain that the ls command is for Linux, not Windows (I'm assuming you're using Windows as you referred to cmd, which is the command line for the Windows OS).

You should use dir instead, which is the Windows equivalent of ls.

Edit (since this post seems to be getting so many views :) ):

You can't use ls on cmd as it's not shipped with Windows, but you can use it on other terminal programs (such as GitBash). Note, ls might work on some FTP servers if the servers are linux based and the FTP is being used from cmd.

dir on Windows is similar to ls. To find out the various options available, just do dir/?.

If you really want to use ls, you could install 3rd party tools to allow you to run unix commands on Windows. Such a program is Microsoft Windows Subsystem for Linux (link to docs).

Difference between <input type='button' /> and <input type='submit' />

A 'button' is just that, a button, to which you can add additional functionality using Javascript. A 'submit' input type has the default functionality of submitting the form it's placed in (though, of course, you can still add additional functionality using Javascript).

How to convert char to integer in C?

In the old days, when we could assume that most computers used ASCII, we would just do

int i = c[0] - '0';

But in these days of Unicode, it's not a good idea. It was never a good idea if your code had to run on a non-ASCII computer.

Edit: Although it looks hackish, evidently it is guaranteed by the standard to work. Thanks @Earwicker.

How to convert an array to object in PHP?

You can use the (object) function to convert your array into an object.

$arr= [128=> ['status'=>
                 'Figure A. Facebook \'s horizontal scrollbars showing up on a 1024x768 screen resolution.'],
                  129=>['status'=>'The other day at work, I had some spare time']];

            $ArrToObject=(object)$arr;
            var_dump($ArrToObject);

The result will be an object that contains arrays:

object(stdClass)#1048 (2) { [128]=> array(1) {

["status"]=> string(87) "Figure A. Facebook 's horizontal scrollbars showing up on a 1024x768 screen resolution." }

[129]=> array(1) { ["status"]=> string(44) "The other day at work, I had some spare time" } }

Getting the textarea value of a ckeditor textarea with javascript

Simply execute

CKEDITOR.instances[elementId].getData();

with element id = id of element assigned the editor.

Angular 5 ngHide ngShow [hidden] not working

Try this:

<button (click)="click()">Click me</button>

<input class="txt" type="password" [(ngModel)]="input_pw" [ngClass]="{'hidden': isHidden}" />

component.ts:

isHidden: boolean = false;
click(){
    this.isHidden = !this.isHidden;
}

How do I purge a linux mail box with huge number of emails?

Just use:

mail
d 1-15
quit

Which will delete all messages between number 1 and 15. to delete all, use the d *.

I just used this myself on ubuntu 12.04.4, and it worked like a charm.

For example:

eric@dev ~ $ mail
Heirloom Mail version 12.4 7/29/08.  Type ? for help.
"/var/spool/mail/eric": 2 messages 2 new
>N  1 Cron Daemon           Tue Jul 29 17:43  23/1016  "Cron <eric@ip-10-0-1-51> /usr/bin/php /var/www/sandbox/eric/c"
 N  2 Cron Daemon           Tue Jul 29 17:44  23/1016  "Cron <eric@ip-10-0-1-51> /usr/bin/php /var/www/sandbox/eric/c"
& d *
& quit

Then check your mail again:

eric@dev ~ $ mail
No mail for eric
eric@dev ~ $

What is tripping you up is you are using x or exit to quit which rolls back the changes during that session.

How can a windows service programmatically restart itself?

I don't think you can in a self-contained service (when you call Restart, it will stop the service, which will interrupt the Restart command, and it won't ever get started again). If you can add a second .exe (a Console app that uses the ServiceManager class), then you can kick off the standalone .exe and have it restart the service and then exit.

On second thought, you could probably have the service register a Scheduled Task (using the command-line 'at' command, for example) to start the service and then have it stop itself; that would probably work.

Use success() or complete() in AJAX call

complete executes after either the success or error callback were executed.

Maybe you should check the second parameter complete offers too. It's a String holding the type of success the ajaxCall had.

The different callbacks are described a little more in detail here jQuery.ajax( options )


I guess you missed the fact that the complete and the success function (I know inconsistent API) get different data passed in. success gets only the data, complete gets the whole XMLHttpRequest object. Of course there is no responseText property on the data string.

So if you replace complete with success you also have to replace data.responseText with data only.

success

The function gets passed two arguments: The data returned from the server, formatted according to the 'dataType' parameter, and a string describing the status.

complete

The function gets passed two arguments: The XMLHttpRequest object and a string describing the type of success of the request.

If you need to have access to the whole XMLHttpRequest object in the success callback I suggest trying this.

var myXHR = $.ajax({
    ...
    success: function(data, status) {
        ...do whatever with myXHR; e.g. myXHR.responseText...
    },
    ...
});

PHP Warning: PHP Startup: Unable to load dynamic library

What I did was;

1 - I first find out what version of PHP I am using thru the function phpinfo()

<?php   
    phpinfo();
?>

2 - From there you will find the location of your configuration(php.ini) file

method phpinfo() result

3 - Open that file

4 - Comment out the line similar to the image below

This might be a different value but it should be related to extension. I am no expert but this process helped me solved similar problem.

enter image description here

better way to drop nan rows in pandas

To expand Hitesh's answer if you want to drop rows where 'x' specifically is nan, you can use the subset parameter. His answer will drop rows where other columns have nans as well

dat.dropna(subset=['x'])

Integer division: How do you produce a double?

If you change the type of one the variables you have to remember to sneak in a double again if your formula changes, because if this variable stops being part of the calculation the result is messed up. I make a habit of casting within the calculation, and add a comment next to it.

double d = 5 / (double) 20; //cast to double, to do floating point calculations

Note that casting the result won't do it

double d = (double)(5 / 20); //produces 0.0

Equal height rows in CSS Grid Layout

Short Answer

If the goal is to create a grid with equal height rows, where the tallest cell in the grid sets the height for all rows, here's a quick and simple solution:

  • Set the container to grid-auto-rows: 1fr

How it works

Grid Layout provides a unit for establishing flexible lengths in a grid container. This is the fr unit. It is designed to distribute free space in the container and is somewhat analogous to the flex-grow property in flexbox.

If you set all rows in a grid container to 1fr, let's say like this:

grid-auto-rows: 1fr;

... then all rows will be equal height.

It doesn't really make sense off-the-bat because fr is supposed to distribute free space. And if several rows have content with different heights, then when the space is distributed, some rows would be proportionally smaller and taller.

Except, buried deep in the grid spec is this little nugget:

7.2.3. Flexible Lengths: the fr unit

...

When the available space is infinite (which happens when the grid container’s width or height is indefinite), flex-sized (fr) grid tracks are sized to their contents while retaining their respective proportions.

The used size of each flex-sized grid track is computed by determining the max-content size of each flex-sized grid track and dividing that size by the respective flex factor to determine a “hypothetical 1fr size”.

The maximum of those is used as the resolved 1fr length (the flex fraction), which is then multiplied by each grid track’s flex factor to determine its final size.

So, if I'm reading this correctly, when dealing with a dynamically-sized grid (e.g., the height is indefinite), grid tracks (rows, in this case) are sized to their contents.

The height of each row is determined by the tallest (max-content) grid item.

The maximum height of those rows becomes the length of 1fr.

That's how 1fr creates equal height rows in a grid container.


Why flexbox isn't an option

As noted in the question, equal height rows are not possible with flexbox.

Flex items can be equal height on the same row, but not across multiple rows.

This behavior is defined in the flexbox spec:

6. Flex Lines

In a multi-line flex container, the cross size of each line is the minimum size necessary to contain the flex items on the line.

In other words, when there are multiple lines in a row-based flex container, the height of each line (the "cross size") is the minimum height necessary to contain the flex items on the line.

Sublime Text 2: How do I change the color that the row number is highlighted?

If you have SublimeLinter installed, your theme (at least it ST3) may end up in .../Packages/User/SublimeLinter/[ your-chosen-theme ]

As mentioned above - find the nested 'settings' dict and edit or add the 'lineHighlight' entry with your desired #RRGGBB or #RRGGBBAA. I like #0000AA99 when on a black(ish) background.

Handy tool if you do not know your color combinations: RGBtoHEX and HEXtoRGB

Convert hexadecimal string (hex) to a binary string

Fast, and works for large strings:

    private String hexToBin(String hex){
        hex = hex.replaceAll("0", "0000");
        hex = hex.replaceAll("1", "0001");
        hex = hex.replaceAll("2", "0010");
        hex = hex.replaceAll("3", "0011");
        hex = hex.replaceAll("4", "0100");
        hex = hex.replaceAll("5", "0101");
        hex = hex.replaceAll("6", "0110");
        hex = hex.replaceAll("7", "0111");
        hex = hex.replaceAll("8", "1000");
        hex = hex.replaceAll("9", "1001");
        hex = hex.replaceAll("A", "1010");
        hex = hex.replaceAll("B", "1011");
        hex = hex.replaceAll("C", "1100");
        hex = hex.replaceAll("D", "1101");
        hex = hex.replaceAll("E", "1110");
        hex = hex.replaceAll("F", "1111");
        return hex;
    }

Bash Shell Script - Check for a flag and grab its value

Use $# to grab the number of arguments, if it is unequal to 2 there are not enough arguments provided:

if [ $# -ne 2 ]; then
   usage;
fi

Next, check if $1 equals -t, otherwise an unknown flag was used:

if [ "$1" != "-t" ]; then
  usage;
fi

Finally store $2 in FLAG:

FLAG=$2

Note: usage() is some function showing the syntax. For example:

function usage {
   cat << EOF
Usage: script.sh -t <application>

Performs some activity
EOF
   exit 1
}

GoTo Next Iteration in For Loop in java

Try this,

1. If you want to skip a particular iteration, use continue.

2. If you want to break out of the immediate loop use break

3 If there are 2 loop, outer and inner.... and you want to break out of both the loop from the inner loop, use break with label.

eg:

continue

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

    if (i==2){

      continue;
    }
 }

eg:

break

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

        if (i==2){

          break;
        }
     }

eg:

break with label

lab1: for(int j=0 ; j<5 ; j++){
     for(int i=0 ; i<5 ; i++){

        if (i==2){

          break lab1;
        }
     }
  }

@Html.DropDownListFor how to set default value

SelectListItem has a Selected property. If you are creating the SelectListItems dynamically, you can just set the one you want as Selected = true and it will then be the default.

SelectListItem defaultItem = new SelectListItem()
{
   Value = 1,
   Text = "Default Item",
   Selected = true
};

Setting new value for an attribute using jQuery

It is working you have to check attr after assigning value

LiveDemo

$('#amount').attr( 'datamin','1000');

alert($('#amount').attr( 'datamin'));?

Clone Object without reference javascript

If you use an = statement to assign a value to a var with an object on the right side, javascript will not copy but reference the object.

You can use lodash's clone method

var obj = {a: 25, b: 50, c: 75};
var A = _.clone(obj);

Or lodash's cloneDeep method if your object has multiple object levels

var obj = {a: 25, b: {a: 1, b: 2}, c: 75};
var A = _.cloneDeep(obj);

Or lodash's merge method if you mean to extend the source object

var obj = {a: 25, b: {a: 1, b: 2}, c: 75};
var A = _.merge({}, obj, {newkey: "newvalue"});

Or you can use jQuerys extend method:

var obj = {a: 25, b: 50, c: 75};
var A = $.extend(true,{},obj);

Here is jQuery 1.11 extend method's source code :

jQuery.extend = jQuery.fn.extend = function() {
    var src, copyIsArray, copy, name, options, clone,
        target = arguments[0] || {},
        i = 1,
        length = arguments.length,
        deep = false;

    // Handle a deep copy situation
    if ( typeof target === "boolean" ) {
        deep = target;

        // skip the boolean and the target
        target = arguments[ i ] || {};
        i++;
    }

    // Handle case when target is a string or something (possible in deep copy)
    if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
        target = {};
    }

    // extend jQuery itself if only one argument is passed
    if ( i === length ) {
        target = this;
        i--;
    }

    for ( ; i < length; i++ ) {
        // Only deal with non-null/undefined values
        if ( (options = arguments[ i ]) != null ) {
            // Extend the base object
            for ( name in options ) {
                src = target[ name ];
                copy = options[ name ];

                // Prevent never-ending loop
                if ( target === copy ) {
                    continue;
                }

                // Recurse if we're merging plain objects or arrays
                if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
                    if ( copyIsArray ) {
                        copyIsArray = false;
                        clone = src && jQuery.isArray(src) ? src : [];

                    } else {
                        clone = src && jQuery.isPlainObject(src) ? src : {};
                    }

                    // Never move original objects, clone them
                    target[ name ] = jQuery.extend( deep, clone, copy );

                // Don't bring in undefined values
                } else if ( copy !== undefined ) {
                    target[ name ] = copy;
                }
            }
        }
    }

    // Return the modified object
    return target;
};

Making text background transparent but not text itself

If you use RGBA for modern browsers you don't need let older IEs use only the non-transparent version of the given color with RGB.

If you don't stick to CSS-only solutions, give CSS3PIE a try. With this syntax you can see exactly the same result in older IEs that you see in modern browsers:

div {
    -pie-background: rgba(223,231,233,0.8);
    behavior: url(../PIE.htc);
}

getResourceAsStream() vs FileInputStream

The java.io.File and consorts acts on the local disk file system. The root cause of your problem is that relative paths in java.io are dependent on the current working directory. I.e. the directory from which the JVM (in your case: the webserver's one) is started. This may for example be C:\Tomcat\bin or something entirely different, but thus not C:\Tomcat\webapps\contextname or whatever you'd expect it to be. In a normal Eclipse project, that would be C:\Eclipse\workspace\projectname. You can learn about the current working directory the following way:

System.out.println(new File(".").getAbsolutePath());

However, the working directory is in no way programmatically controllable. You should really prefer using absolute paths in the File API instead of relative paths. E.g. C:\full\path\to\file.ext.

You don't want to hardcode or guess the absolute path in Java (web)applications. That's only portability trouble (i.e. it runs in system X, but not in system Y). The normal practice is to place those kind of resources in the classpath, or to add its full path to the classpath (in an IDE like Eclipse that's the src folder and the "build path" respectively). This way you can grab them with help of the ClassLoader by ClassLoader#getResource() or ClassLoader#getResourceAsStream(). It is able to locate files relative to the "root" of the classpath, as you by coincidence figured out. In webapplications (or any other application which uses multiple classloaders) it's recommend to use the ClassLoader as returned by Thread.currentThread().getContextClassLoader() for this so you can look "outside" the webapp context as well.

Another alternative in webapps is the ServletContext#getResource() and its counterpart ServletContext#getResourceAsStream(). It is able to access files located in the public web folder of the webapp project, including the /WEB-INF folder. The ServletContext is available in servlets by the inherited getServletContext() method, you can call it as-is.

See also:

json: cannot unmarshal object into Go value of type

You JSON doesn't match your struct fields: E.g. "district" in JSON and "District" as the field.

Also: Your Item is a slice type but your JSON is a dict value. Do not mix this up. Slices decode from arrays.

Getting cursor position in Python

win32gui.GetCursorPos(point)

This retrieves the cursor's position, in screen coordinates - point = (x,y)

flags, hcursor, (x,y) = win32gui.GetCursorInfo()

Retrieves information about the global cursor.

Links:

I am assuming that you would be using python win32 API bindings or pywin32.

What version of Python is on my Mac?

You could have multiple Python versions on your macOS.

You may check that by command, type or which command, like:

which -a python python2 python2.7 python3 python3.6

Or type python in Terminal and hit Tab few times for auto completion, which is equivalent to:

compgen -c python

By default python/pip commands points to the first binary found in PATH environment variable depending what's actually installed. So before installing Python packages with Homebrew, the default Python is installed in /usr/bin which is shipped with your macOS (e.g. Python 2.7.10 on High Sierra). Any versions found in /usr/local (such as /usr/local/bin) are provided by external packages.

It is generally advised, that when working with multiple versions, for Python 2 you may use python2/pip2 command, respectively for Python 3 you can use python3/pip3, but it depends on your configuration which commands are available.

It is also worth to mention, that since release of Homebrew 1.5.0+ (on 19 January 2018), the python formula has been upgraded to Python 3.x and a python@2 formula will be added for installing Python 2.7. Before, python formula was pointing to Python 2.

For instance, if you've installed different version via Homebrew, try the following command:

brew list python python3

or:

brew list | grep ^python

it'll show you all Python files installed with the package.

Alternatively you may use apropos or locate python command to locate more Python related files.

To check any environment variables related to Python, run:

env | grep ^PYTHON

To address your issues:

  • Error: No such keg: /usr/local/Cellar/python

    Means you don't have Python installed via Homebrew. However double check by specifying only one package at a time (like brew list python python2 python3).

  • The locate database (/var/db/locate.database) does not exist.

    Follow the advice and run:

    sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.locate.plist
    

    After the database is rebuild, you can use locate command.

How to set Apache Spark Executor memory

Also note, that for local mode you have to set the amount of driver memory before starting jvm:

bin/spark-submit --driver-memory 2g --class your.class.here app.jar

This will start the JVM with 2G instead of the default 512M.
Details here:

For local mode you only have one executor, and this executor is your driver, so you need to set the driver's memory instead. *That said, in local mode, by the time you run spark-submit, a JVM has already been launched with the default memory settings, so setting "spark.driver.memory" in your conf won't actually do anything for you. Instead, you need to run spark-submit as follows

jQuery & CSS - Remove/Add display:none

jQuery's .show() and .hide() functions are probably your best bet.

git ignore vim temporary files

I would also recommend to think to ignore files like:

.*.swp
.*.swo

as you may have files that end with .swp

Improve subplot size/spacing with many subplots in matplotlib

You can use plt.subplots_adjust to change the spacing between the subplots (source)

call signature:

subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)

The parameter meanings (and suggested defaults) are:

left  = 0.125  # the left side of the subplots of the figure
right = 0.9    # the right side of the subplots of the figure
bottom = 0.1   # the bottom of the subplots of the figure
top = 0.9      # the top of the subplots of the figure
wspace = 0.2   # the amount of width reserved for blank space between subplots
hspace = 0.2   # the amount of height reserved for white space between subplots

The actual defaults are controlled by the rc file

Testing two JSON objects for equality ignoring child order in Java

You can try JsonUnit. It can compare two JSON objects and report differences. It's built on top of Jackson.

For example

assertThatJson("{\"test\":1}").isEqualTo("{\n\"test\": 2\n}");

Results in

java.lang.AssertionError: JSON documents are different:
Different value found in node "test". Expected 1, got 2.

How to create a connection string in asp.net c#

Add this in your web.config file

<connectionStrings>
<add name="itmall" 
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=D:\19-
02\ABCC\App_Data\abcc.mdf;Integrated Security=True;User Instance=True" />
</connectionStrings>

Preprocessing in scikit learn - single sample - Depreciation warning

.values.reshape(-1,1) will be accepted without alerts/warnings

.reshape(-1,1) will be accepted, but with deprecation war

Pass a list to a function to act as multiple arguments

Yes, you can use the *args (splat) syntax:

function_that_needs_strings(*my_list)

where my_list can be any iterable; Python will loop over the given object and use each element as a separate argument to the function.

See the call expression documentation.

There is a keyword-parameter equivalent as well, using two stars:

kwargs = {'foo': 'bar', 'spam': 'ham'}
f(**kwargs)

and there is equivalent syntax for specifying catch-all arguments in a function signature:

def func(*args, **kw):
    # args now holds positional arguments, kw keyword arguments

How to resolve conflicts in EGit

GIT has the most irritating way of resolving conflicts (Unlike svn where you can simply compare and do the changes). I strongly feel git has complex conflict resolution process. If I were to resolve, I would simply take another code from GIT as fresh, add my changes and commit them. It simple and not so process oriented.

What's the difference between fill_parent and wrap_content?

fill_parent (deprecated) = match_parent
The border of the child view expands to match the border of the parent view.

wrap_content
The border of the child view wraps snugly around its own content.

Here are some images to make things more clear. The green and red are TextViews. The white is a LinearLayout showing through.

enter image description here

Every View (a TextView, an ImageView, a Button, etc.) needs to set the width and the height of the view. In the xml layout file, that might look like this:

android:layout_width="wrap_content"
android:layout_height="match_parent"

Besides setting the width and height to match_parent or wrap_content, you could also set them to some absolute value:

android:layout_width="100dp"
android:layout_height="200dp"

Generally that is not as good, though, because it is not as flexible for different sized devices. After you have understood wrap_content and match_parent, the next thing to learn is layout_weight.

See also

XML for above images

Vertical LinearLayout

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="width=wrap height=wrap"
        android:background="#c5e1b0"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="width=match height=wrap"
        android:background="#f6c0c0"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="width=match height=match"
        android:background="#c5e1b0"/>

</LinearLayout>

Horizontal LinearLayout

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="WrapWrap"
        android:background="#c5e1b0"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="WrapMatch"
        android:background="#f6c0c0"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="MatchMatch"
        android:background="#c5e1b0"/>

</LinearLayout>

Note

The explanation in this answer assumes there is no margin or padding. But even if there is, the basic concept is still the same. The view border/spacing is just adjusted by the value of the margin or padding.

How to check if a string "StartsWith" another string?

Also check out underscore.string.js. It comes with a bunch of useful string testing and manipulation methods, including a startsWith method. From the docs:

startsWith _.startsWith(string, starts)

This method checks whether string starts with starts.

_("image.gif").startsWith("image")
=> true

Reset all the items in a form

If you have some panels or groupboxes reset fields should be recursive.

public class Utilities
{
    public static void ResetAllControls(Control form)
    {
        foreach (Control control in form.Controls)
        {
            RecursiveResetForm(control);
        }
    }

    private void RecursiveResetForm(Control control)
    {            
        if (control.HasChildren)
        {
            foreach (Control subControl in control.Controls)
            {
                RecursiveResetForm(subControl);
            }
        }
        switch (control.GetType().Name)
        {
            case "TextBox":
                TextBox textBox = (TextBox)control;
                textBox.Text = null;
                break;

            case "ComboBox":
                ComboBox comboBox = (ComboBox)control;
                if (comboBox.Items.Count > 0)
                    comboBox.SelectedIndex = 0;
                break;

            case "CheckBox":
                CheckBox checkBox = (CheckBox)control;
                checkBox.Checked = false;
                break;

            case "ListBox":
                ListBox listBox = (ListBox)control;
                listBox.ClearSelected();
                break;

            case "NumericUpDown":
                NumericUpDown numericUpDown = (NumericUpDown)control;
                numericUpDown.Value = 0;
                break;
        }
    }        
}

Why aren't programs written in Assembly more often?

ASM has poor legibility and isn't really maintainable compared to higher-level languages.

Also, there are many fewer ASM developers than for other more popular languages, such as C.

Furthermore, if you use a higher-level language and new ASM instructions become available (SSE for example), you just need to update your compiler and your old code can easily make use of the new instructions.

What if the next CPU has twice as many registers?

The converse of this question would be: What functionality do compilers provide?

I doubt you can/want to/should optimize your ASM better than gcc -O3 can.

How do I find out what version of Sybase is running

Run this command:

select @@version

AngularJS Folder Structure

I'm on my third angularjs app and the folder structure has improved every time so far. I keep mine simple right now.

index.html (or .php)
/resources
  /css
  /fonts
  /images
  /js
    /controllers
    /directives
    /filters
    /services
  /partials (views)

I find that good for single apps. I haven't really had a project yet where I'd need multiple.

How to git reset --hard a subdirectory?

According to Git developer Duy Nguyen who kindly implemented the feature and a compatibility switch, the following works as expected as of Git 1.8.3:

git checkout -- a

(where a is the directory you want to hard-reset). The original behavior can be accessed via

git checkout --ignore-skip-worktree-bits -- a

Run a JAR file from the command line and specify classpath

You can do these in unix shell:

java -cp MyJar.jar:lib/* com.somepackage.subpackage.Main

You can do these in windows powershell:

java -cp "MyJar.jar;lib\*" com.somepackage.subpackage.Main

Error 405 (Method Not Allowed) Laravel 5

The methodNotAllowed exception indicates that a route doesn't exist for the HTTP method you are requesting.

Your form is set up to make a DELETE request, so your route needs to use Route::delete() to receive this.

Route::delete('empresas/eliminar/{id}', [
        'as' => 'companiesDelete',
        'uses' => 'CompaniesController@delete'
]);

How to add target="_blank" to JavaScript window.location?

_x000D_
_x000D_
    var linkGo = function(item) {_x000D_
      $(item).on('click', function() {_x000D_
        var _$this = $(this);_x000D_
        var _urlBlank = _$this.attr("data-link");_x000D_
        var _urlTemp = _$this.attr("data-url");_x000D_
        if (_urlBlank === "_blank") {_x000D_
          window.open(_urlTemp, '_blank');_x000D_
        } else {_x000D_
          // cross-origin_x000D_
          location.href = _urlTemp;_x000D_
        }_x000D_
      });_x000D_
    };_x000D_
_x000D_
    linkGo(".button__main[data-link]");
_x000D_
.button{cursor:pointer;}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
_x000D_
<span class="button button__main" data-link="" data-url="https://stackoverflow.com/">go stackoverflow</span>
_x000D_
_x000D_
_x000D_

How to delete an element from an array in C#

You can also convert your array to a list and call remove on the list. You can then convert back to your array.

int[] numbers = {1, 3, 4, 9, 2};
var numbersList = numbers.ToList();
numbersList.Remove(4);

What is the difference between "px", "dip", "dp" and "sp"?

Where to use what & relationship between px & dp?

Density-independent pixel (dp)

A virtual pixel unit that you should use when defining UI layout, to express layout dimensions or position in a density-independent way. As described above, the density-independent pixel is equivalent to one physical pixel on a 160 dpi screen, which is the baseline density assumed by the system for a "medium" density screen. At runtime, the system transparently handles any scaling of the dp units, as necessary, based on the actual density of the screen in use. The conversion of dp units to screen pixels is simple:

px = dp * (dpi / 160).

For example, on a 240 dpi screen, 1 dp equals 1.5 physical pixels. You should always use dp units when defining your application's UI, to ensure proper display of your UI on screens with different densities.

Understanding pixel to dp and vice versa is very essential (especially for giving exact dp values to creative team)

dp = px * 160 / dpi

MDPI = 160 dpi || Therefore, on MDPI 1 px = 1 dp
For example, if you want to convert 20 pixel to dp, use the above formula,
dp = 20 * 160 / 160 = 20.
So, 20 pixel = 20 dp.

HDPI = 240 dpi - So, on HDPI 1.5 px = 1 dp
XHDPI = 320 dpi - So, on XHDPI 2 px = 1 dp
XXHDPI = 480 dpi - So, on XXHDPI 3 px = 1 dp

For example, let us consider Nexus 4.
If 24 pixels to be converted to dp and if it is a Nexus 4 screen, developers can
convert it to dp easily by the following calculation :
dp = 24 * 160 / 320 = 12 dp
Screen dimension:
768 x 1280 pixel resolution (320 ppi or 320dpi)
Optional (screen size):
 4.7" diagonal
  • Try to get all pixel values in even numbers from the creative team. Otherwise precision lose will happen while multiplying with 0.5.

px

It is explained above. Try to avoid in layout files. But there are some cases, where px is required. for example, ListView divider line. px is better here for giving a one-pixel line as a divider for all across screen resolutions.

sp

Use sp for font sizes. Then only the font inside the application will change while device fonts size changes (that is, Display -> Fonts on Device). If you want to keep a static sized font inside the app, you can give the font dimension in dp. In such a case, it will never change. Developers may get such a requirement for some specific screens, for that, developers can use dp instead of sp. In all other cases, sp is recommended.

What's the difference between select_related and prefetch_related in Django ORM?

As Django documentation says:

prefetch_related()

Returns a QuerySet that will automatically retrieve, in a single batch, related objects for each of the specified lookups.

This has a similar purpose to select_related, in that both are designed to stop the deluge of database queries that is caused by accessing related objects, but the strategy is quite different.

select_related works by creating an SQL join and including the fields of the related object in the SELECT statement. For this reason, select_related gets the related objects in the same database query. However, to avoid the much larger result set that would result from joining across a ‘many’ relationship, select_related is limited to single-valued relationships - foreign key and one-to-one.

prefetch_related, on the other hand, does a separate lookup for each relationship, and does the ‘joining’ in Python. This allows it to prefetch many-to-many and many-to-one objects, which cannot be done using select_related, in addition to the foreign key and one-to-one relationships that are supported by select_related. It also supports prefetching of GenericRelation and GenericForeignKey, however, it must be restricted to a homogeneous set of results. For example, prefetching objects referenced by a GenericForeignKey is only supported if the query is restricted to one ContentType.

More information about this: https://docs.djangoproject.com/en/2.2/ref/models/querysets/#prefetch-related

How do you implement a circular buffer in C?

A simple implementation could consist of:

  • A buffer, implemented as an array of size n, of whatever type you need
  • A read pointer or index (whichever is more efficient for your processor)
  • A write pointer or index
  • A counter indicating how much data is in the buffer (derivable from the read and write pointers, but faster to track it separately)

Every time you write data, you advance the write pointer and increment the counter. When you read data, you increase the read pointer and decrement the counter. If either pointer reaches n, set it to zero.

You can't write if counter = n. You can't read if counter = 0.

cast or convert a float to nvarchar?

For anyone willing to try a different method, they can use this:

select FORMAT([Column_Name], '') from YourTable

This will easily change any float value to nvarchar.

How to autoplay HTML5 mp4 video on Android?

similar to KNaito's answer, the following does the trick for me

function simulateClick() {
  var event = new MouseEvent('click', {
    'view': window,
    'bubbles': true,
    'cancelable': true
  });
  var cb = document.getElementById('player'); 
  var canceled = !cb.dispatchEvent(event);
  if (canceled) {
    // A handler called preventDefault.
    alert("canceled");
  } else {
    // None of the handlers called preventDefault.
    alert("not canceled");
  }
}

When is the @JsonProperty property used and what is it used for?

In addition to all the answers above, don't forget the part of the documentation that says

Marker annotation that can be used to define a non-static method as a "setter" or "getter" for a logical property (depending on its signature), or non-static object field to be used (serialized, deserialized) as a logical property.

If you have a non-static method in your class that is not a conventional getter or setter then you can make it act like a getter and setter by using the annotation on it. See the example below

public class Testing {
    private Integer id;
    private String username;

    public Integer getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getIdAndUsername() {
        return id + "." + username; 
    }

    public String concatenateIdAndUsername() {
        return id + "." + username; 
    }
}

When the above object is serialized, then response will contain

  • username from getUsername()
  • id from getId()
  • idAndUsername from getIdAndUsername*

Since the method getIdAndUsername starts with get then it's treated as normal getter hence, why you could annotate such with @JsonIgnore.

If you have noticed the concatenateIdAndUsername is not returned and that's because it name does not start with get and if you wish the result of that method to be included in the response then you can use @JsonProperty("...") and it would be treated as normal getter/setter as mentioned in the above highlighted documentation.

MySQL Trigger: Delete From Table AFTER DELETE

Why not set ON CASCADE DELETE on Foreign Key patron_info.pid?

How to test if a string contains one of the substrings in a list, in pandas?

Here is a one line lambda that also works:

df["TrueFalse"] = df['col1'].apply(lambda x: 1 if any(i in x for i in searchfor) else 0)

Input:

searchfor = ['og', 'at']

df = pd.DataFrame([('cat', 1000.0), ('hat', 2000000.0), ('dog', 1000.0), ('fog', 330000.0),('pet', 330000.0)], columns=['col1', 'col2'])

   col1  col2
0   cat 1000.0
1   hat 2000000.0
2   dog 1000.0
3   fog 330000.0
4   pet 330000.0

Apply Lambda:

df["TrueFalse"] = df['col1'].apply(lambda x: 1 if any(i in x for i in searchfor) else 0)

Output:

    col1    col2        TrueFalse
0   cat     1000.0      1
1   hat     2000000.0   1
2   dog     1000.0      1
3   fog     330000.0    1
4   pet     330000.0    0

If (Array.Length == 0)

If array is null, trying to derefrence array.Length will throw a NullReferenceException. If your code considers null to be an invalid value for array, you should reject it and blame the caller. One such pattern is to throw ArgumentNullException:

void MyMethod(string[] array)
{
    if (array == null) throw new ArgumentNullException(nameof(array));

    if (array.Length > 0)
    {
        // Do something with array…
    }
}

If you want to accept a null array as an indication to not do something or as an optional parameter, you may simply not access it if it is null:

void MyMethod(string[] array)
{
    if (array != null)
    {
        // Do something with array here…
    }
}

If you want to avoid touching array when it is either null or has zero length, then you can check for both at the same time with C#-6’s null coalescing operator.

void MyMethod(string[] array)
{
    if (array?.Length > 0)
    {
        // Do something with array…
    }
}

Superfluous Length Check

It seems strange that you are treating the empty array as a special case. In many cases, if you, e.g., would just loop over the array anyway, there’s no need to treat the empty array as a special case. foreach (var elem in array) {«body»} will simply never execute «body» when array.Length is 0. If you are treating array == null || array.Length == 0 specially to, e.g., improve performance, you might consider leaving a comment for posterity. Otherwise, the check for Length == 0 appears superfluous.

Superfluous code makes understanding a program harder because people reading the code likely assume that each line is necessary to solve some problem or achieve correctness. If you include unnecessary code, the readers are going to spend forever trying to figure out why that line is or was necessary before deleting it ;-).

git repo says it's up-to-date after pull but files are not updated

For me my forked branch was not in sync with the master branch. So I went to bitbucket and synced and merged my forked branch and then tried to take the pull. Then it worked fine.

Setting focus to iframe contents

This is something that worked for me, although it smells a bit wrong:

var iframe = ...
var doc = iframe.contentDocument;

var i = doc.createElement('input');
i.style.display = 'none'; 
doc.body.appendChild(i);
i.focus();
doc.body.removeChild(i);

hmmm. it also scrolls to the bottom of the content. Guess I should be inserting the dummy textbox at the top.

endforeach in loops?

It's mainly so you can make start and end statements clearer when creating HTML in loops:

<table>
<? while ($record = mysql_fetch_assoc($rs)): ?>
    <? if (!$record['deleted']): ?>
        <tr>
        <? foreach ($display_fields as $field): ?>
            <td><?= $record[$field] ?></td>
        <? endforeach; ?>
        <td>
        <select name="action" onChange="submit">
        <? foreach ($actions as $action): ?>
            <option value="<?= $action ?>"><?= $action ?>
        <? endforeach; ?>
        </td>
        </tr>
    <? else: ?>
         <tr><td colspan="<?= array_count($display_fields) ?>"><i>record <?= $record['id'] ?> has been deleted</i></td></tr>
    <? endif; ?>
<? endwhile; ?>
</table>

versus

<table>
<? while ($record = mysql_fetch_assoc($rs)) { ?>
    <? if (!$record['deleted']) { ?>
        <tr>
        <? foreach ($display_fields as $field) { ?>
            <td><?= $record[$field] ?></td>
        <? } ?>
        <td>
        <select name="action" onChange="submit">
        <? foreach ($actions as $action) { ?>
            <option value="<?= $action ?>"><?= action ?>
        <? } ?>
        </td>
        </tr>
    <? } else { ?>
         <tr><td colspan="<?= array_count($display_fields) ?>"><i>record <?= $record['id'] ?> has been deleted</i></td></tr>
    <? } ?>
<? } ?>
</table>

Hopefully my example is sufficient to demonstrate that once you have several layers of nested loops, and the indenting is thrown off by all the PHP open/close tags and the contained HTML (and maybe you have to indent the HTML a certain way to get your page the way you want), the alternate syntax (endforeach) form can make things easier for your brain to parse. With the normal style, the closing } can be left on their own and make it hard to tell what they're actually closing.

How do I move focus to next input with jQuery?

Use eq to get to specific element.

Documentation about index

_x000D_
_x000D_
$("input").keyup(function () {_x000D_
   var index = $(this).index("input");    _x000D_
   $("input:eq(" + (index +1) + ")").focus(); _x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<input type="text" maxlength="1"  />_x000D_
<input type="text" maxlength="1"  />_x000D_
_x000D_
<input type="text" maxlength="1"  />_x000D_
_x000D_
<input type="text" maxlength="1"  />_x000D_
<input type="text" maxlength="1"  />_x000D_
<input type="text" maxlength="1"  />
_x000D_
_x000D_
_x000D_

How do I do string replace in JavaScript to convert ‘9.61’ to ‘9:61’?

A simple one liner:

$("#text").val( $("#text").val().replace(".", ":") );

Git undo changes in some files

Source : http://git-scm.com/book/en/Git-Basics-Undoing-Things

git checkout -- modifiedfile.java


1)$ git status

you will see the modified file

2)$git checkout -- modifiedfile.java

3)$git status

Changes in import statement python3

To support both Python 2 and Python 3, use explicit relative imports as below. They are relative to the current module. They have been supported starting from 2.5.

from .sister import foo
from . import brother
from ..aunt import bar
from .. import uncle

Running JAR file on Windows 10

How do I run an executable JAR file? If you have a jar file called Example.jar, follow these rules:

Open a notepad.exe.
Write : java -jar Example.jar.
Save it with the extension .bat.
Copy it to the directory which has the .jar file.
Double click it to run your .jar file.

Check if string contains only digits

_x000D_
_x000D_
var str='1232323a.1';
var reg=/^[0-9]*[.]?[0-9]*$/;

console.log(reg.test(str))
_x000D_
_x000D_
_x000D_

Python: What OS am I running on?

try this:

import os

os.uname()

and you can make it :

info=os.uname()
info[0]
info[1]

XSLT equivalent for JSON

it is very possible to convert JSON using XSLT: you need JSON2SAX deserializer and SAX2JSON serializer.

Sample code in Java: http://www.gerixsoft.com/blog/json/xslt4json

@RequestParam vs @PathVariable

@RequestParam annotation used for accessing the query parameter values from the request. Look at the following request URL:

http://localhost:8080/springmvc/hello/101?param1=10&param2=20

In the above URL request, the values for param1 and param2 can be accessed as below:

public String getDetails(
    @RequestParam(value="param1", required=true) String param1,
        @RequestParam(value="param2", required=false) String param2){
...
}

The following are the list of parameters supported by the @RequestParam annotation:

  • defaultValue – This is the default value as a fallback mechanism if request is not having the value or it is empty.
  • name – Name of the parameter to bind
  • required – Whether the parameter is mandatory or not. If it is true, failing to send that parameter will fail.
  • value – This is an alias for the name attribute

@PathVariable

@PathVariable identifies the pattern that is used in the URI for the incoming request. Let’s look at the below request URL:

http://localhost:8080/springmvc/hello/101?param1=10&param2=20

The above URL request can be written in your Spring MVC as below:

@RequestMapping("/hello/{id}")    public String getDetails(@PathVariable(value="id") String id,
    @RequestParam(value="param1", required=true) String param1,
    @RequestParam(value="param2", required=false) String param2){
.......
}

The @PathVariable annotation has only one attribute value for binding the request URI template. It is allowed to use the multiple @PathVariable annotation in the single method. But, ensure that no more than one method has the same pattern.

Also there is one more interesting annotation: @MatrixVariable

http://localhost:8080/spring_3_2/matrixvars/stocks;BT.A=276.70,+10.40,+3.91;AZN=236.00,+103.00,+3.29;SBRY=375.50,+7.60,+2.07

And the Controller method for it

 @RequestMapping(value = "/{stocks}", method = RequestMethod.GET)
  public String showPortfolioValues(@MatrixVariable Map<String, List<String>> matrixVars, Model model) {

    logger.info("Storing {} Values which are: {}", new Object[] { matrixVars.size(), matrixVars });

    List<List<String>> outlist = map2List(matrixVars);
    model.addAttribute("stocks", outlist);

    return "stocks";
  }

But you must enable:

<mvc:annotation-driven enableMatrixVariables="true" >

Inverse of a matrix using numpy

What about inv?

e.g.: my_inverse_array = inv(my_array)

Can't connect to MySQL server on 'localhost' (10061)

  1. Make sure that your windows host file (located at c://windows/system32/drivers/etc.host) has following line. If not, add it at the end

    127.0.0.1 localhost
    ::1 localhost
    
  2. Sometimes mysql can not trigger Windows to force start host services if firewall blocks it, so start it manually

win+run>>services.msc, select the "MySQL_xx" where "xx" is the name you have assigned to MySQL host services during setup. Click on 'start' to start from hyperlink appeared on left side.

Change the Theme in Jupyter Notebook?

Simple, global change of Jupyter font size and inner & outer background colors (this change will affect all notebooks).

In Windows, find config directory by running a command: jupyter --config-dir

In Linux it is ~/.jupyter

In this directory create subfolder custom Create file custom.css and paste:

/* Change outer background and make the notebook take all available width */
.container {
    width: 99% !important;
    background: #DDC !important;
}   

/* Change inner background (CODE) */
div.input_area {
    background: #F4F4E2 !important;
    font-size: 16px !important;
}

/* Change global font size (CODE) */
.CodeMirror {
    font-size: 16px !important;
}  

/* Prevent the edit cell highlight box from getting clipped;
 * important so that it also works when cell is in edit mode */
div.cell.selected {
    border-left-width: 1px !important;
} 

Finally - restart Jupyter. Result:

darker backgrounds

List<Object> and List<?>

List<Object> object = new List<Object>();

You cannot do this because List is an interface and you cannot create object of any interface or in other word you cannot instantiate any interface. Moreover, you can assign any object of class which implements List to its reference variable. For example you can do this:

list<Object> object = new ArrayList<Object>();

Here ArrayList is a class which implements List, you can use any class which implements List.

How to delete files/subfolders in a specific directory at the command prompt in Windows

RD stands for REMOVE Directory.

/S : Delete all files and subfolders in addition to the folder itself. Use this to remove an entire folder tree.

/Q : Quiet - do not display YN confirmation

Example :

RD /S /Q C:/folder_path/here

Why are elementwise additions much faster in separate loops than in a combined loop?

It's not because of a different code, but because of caching: RAM is slower than the CPU registers and a cache memory is inside the CPU to avoid to write the RAM every time a variable is changing. But the cache is not big as the RAM is, hence, it maps only a fraction of it.

The first code modifies distant memory addresses alternating them at each loop, thus requiring continuously to invalidate the cache.

The second code don't alternate: it just flow on adjacent addresses twice. This makes all the job to be completed in the cache, invalidating it only after the second loop starts.

Select elements by attribute in CSS

You can combine multiple selectors and this is so cool knowing that you can select every attribute and attribute based on their value like href based on their values with CSS only..

Attributes selectors allows you play around some extra with id and class attributes

Here is an awesome read on Attribute Selectors

Fiddle

_x000D_
_x000D_
a[href="http://aamirshahzad.net"][title="Aamir"] {_x000D_
  color: green;_x000D_
  text-decoration: none;_x000D_
}_x000D_
_x000D_
a[id*="google"] {_x000D_
  color: red;_x000D_
}_x000D_
_x000D_
a[class*="stack"] {_x000D_
  color: yellow;_x000D_
}
_x000D_
<a href="http://aamirshahzad.net" title="Aamir">Aamir</a>_x000D_
<br>_x000D_
<a href="http://google.com" id="google-link" title="Google">Google</a>_x000D_
<br>_x000D_
<a href="http://stackoverflow.com" class="stack-link" title="stack">stack</a>
_x000D_
_x000D_
_x000D_

Browser support:
IE6+, Chrome, Firefox & Safari

You can check detail here.

Alternate table row color using CSS?

You can use nth-child(odd/even) selectors however not all browsers (ie 6-8, ff v3.0) support these rules hence why most solutions fall back to some form of javascript/jquery solution to add the classes to the rows for these non compliant browsers to get the tiger stripe effect.

Incompatible implicit declaration of built-in function ‘malloc’

The stdlib.h file contains the header information or prototype of the malloc, calloc, realloc and free functions.

So to avoid this warning in ANSI C, you should include the stdlib header file.

Parse date string and change format

You can install the dateutil library. Its parse function can figure out what format a string is in without having to specify the format like you do with datetime.strptime.

from dateutil.parser import parse
dt = parse('Mon Feb 15 2010')
print(dt)
# datetime.datetime(2010, 2, 15, 0, 0)
print(dt.strftime('%d/%m/%Y'))
# 15/02/2010

TINYTEXT, TEXT, MEDIUMTEXT, and LONGTEXT maximum storage sizes

This is nice but doesn't answer the question:

"A VARCHAR should always be used instead of TINYTEXT." Tinytext is useful if you have wide rows - since the data is stored off the record. There is a performance overhead, but it does have a use.

android start activity from service

Another thing worth mentioning: while the answer above works just fine when our task is in the background, the only way I could make it work if our task (made of service + some activities) was in the foreground (i.e. one of our activities visible to user) was like this:

    Intent intent = new Intent(storedActivity, MyActivity.class);
    intent.setAction(Intent.ACTION_VIEW);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
    storedActivity.startActivity(intent);

I do not know whether ACTION_VIEW or FLAG_ACTIVITY_NEW_TASK are of any actual use here. The key to succeeding was

storedActivity.startActivity(intent);

and of course FLAG_ACTIVITY_REORDER_TO_FRONT for not instantiating the activity again. Best of luck!

Alternative for PHP_excel

I wrote a very simple class for exporting to "Excel XML" aka SpreadsheetML. It's not quite as convenient for the end user as XSLX (depending on file extension and Excel version, they may get a warning message), but it's a lot easier to work with than XLS or XLSX.

http://github.com/elidickinson/php-export-data

I'm getting the "missing a using directive or assembly reference" and no clue what's going wrong

.Net framework of the referencing dll should be same as the .Net framework version of the Project in which dll is referred

Truncating all tables in a Postgres database

For removing the data and preserving the table-structures in pgAdmin you can do:

  • Right-click database -> backup, select "Schema only"
  • Drop the database
  • Create a new database and name it like the former
  • Right-click the new database -> restore -> select the backup, select "Schema only"

How to flatten only some dimensions of a numpy array

A slight generalization to Peter's answer -- you can specify a range over the original array's shape if you want to go beyond three dimensional arrays.

e.g. to flatten all but the last two dimensions:

arr = numpy.zeros((3, 4, 5, 6))
new_arr = arr.reshape(-1, *arr.shape[-2:])
new_arr.shape
# (12, 5, 6)

EDIT: A slight generalization to my earlier answer -- you can, of course, also specify a range at the beginning of the of the reshape too:

arr = numpy.zeros((3, 4, 5, 6, 7, 8))
new_arr = arr.reshape(*arr.shape[:2], -1, *arr.shape[-2:])
new_arr.shape
# (3, 4, 30, 7, 8)

How to initialise a string from NSData in Swift

import Foundation
var string = NSString(data: NSData?, encoding: UInt)

Xampp-mysql - "Table doesn't exist in engine" #1932

I had the same issue. I had a backup of my C:\xampp\mysql\data folder. But integrating it with the newly installed xampp had issues. So I located the C:\xampp\mysql\bin\my.ini file and directed innodb_data_home_dir = "C:/xampp/mysql/data" to my backed-up data folder and it worked flawlessly.

How can you program if you're blind?

Emacs has a number of extensions to allow blind users to manipulate text files. You'd have to consult an expert on the topic, but emacs has text-to-speech capabilities. And probably more.

In addition, there's BLinux:

http://leb.net/blinux/

Linux for the blind. Been around for a very long time. More than ten years I think, and very mature.

Does Visual Studio Code have box select/multi-line edit?

The shortcuts I use in Visual Studio for multiline (aka box) select are Shift + Alt + up/down/left/right

To create this in Visual Studio Code you can add these keybindings to the keybindings.json file (menu FilePreferencesKeyboard shortcuts).

{ "key": "shift+alt+down", "command": "editor.action.insertCursorBelow",
                                 "when": "editorTextFocus" },
{ "key": "shift+alt+up", "command": "editor.action.insertCursorAbove",
                                 "when": "editorTextFocus" },
{ "key": "shift+alt+right", "command": "cursorRightSelect",
                                     "when": "editorTextFocus" },
{ "key": "shift+alt+left", "command": "cursorLeftSelect",
                                     "when": "editorTextFocus" }

What is the use of <<<EOD in PHP?

there are four types of strings available in php. They are single quotes ('), double quotes (") and Nowdoc (<<<'EOD') and heredoc(<<<EOD) strings

you can use both single quotes and double quotes inside heredoc string. Variables will be expanded just as double quotes.

nowdoc strings will not expand variables just like single quotes.

ref: http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc

How can I fill a column with random numbers in SQL? I get the same value in every row

If you are on SQL Server 2008 you can also use

 CRYPT_GEN_RANDOM(2) % 10000

Which seems somewhat simpler (it is also evaluated once per row as newid is - shown below)

DECLARE @foo TABLE (col1 FLOAT)

INSERT INTO @foo SELECT 1 UNION SELECT 2

UPDATE @foo
SET col1 =  CRYPT_GEN_RANDOM(2) % 10000

SELECT *  FROM @foo

Returns (2 random probably different numbers)

col1
----------------------
9693
8573

Mulling the unexplained downvote the only legitimate reason I can think of is that because the random number generated is between 0-65535 which is not evenly divisible by 10,000 some numbers will be slightly over represented. A way around this would be to wrap it in a scalar UDF that throws away any number over 60,000 and calls itself recursively to get a replacement number.

CREATE FUNCTION dbo.RandomNumber()
RETURNS INT
AS
  BEGIN
      DECLARE @Result INT

      SET @Result = CRYPT_GEN_RANDOM(2)

      RETURN CASE
               WHEN @Result < 60000
                     OR @@NESTLEVEL = 32 THEN @Result % 10000
               ELSE dbo.RandomNumber()
             END
  END  

Get Android Device Name

@hbhakhra's answer will do.

If you're interested in detailed explanation, it is useful to look into Android Compatibility Definition Document. (3.2.2 Build Parameters)

You will find:

DEVICE - A value chosen by the device implementer containing the development name or code name identifying the configuration of the hardware features and industrial design of the device. The value of this field MUST be encodable as 7-bit ASCII and match the regular expression “^[a-zA-Z0-9_-]+$”.

MODEL - A value chosen by the device implementer containing the name of the device as known to the end user. This SHOULD be the same name under which the device is marketed and sold to end users. There are no requirements on the specific format of this field, except that it MUST NOT be null or the empty string ("").

MANUFACTURER - The trade name of the Original Equipment Manufacturer (OEM) of the product. There are no requirements on the specific format of this field, except that it MUST NOT be null or the empty string ("").

jQuery Get Selected Option From Dropdown

Usually you'd need to not only get the selected value, but also run some action. So why not avoid all the jQuery magic and just pass the selected value as an argument to the action call?

<select onchange="your_action(this.value)">
   <option value='*'>All</option>
   <option ... />
</select>

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

Use the following code to get Name and Value of a dynamic object's property.

dynamic d = new { Property1= "Value1", Property2= "Value2"};

var properties = d.GetType().GetProperties();
foreach (var property in properties)
{
    var PropertyName=property.Name; 
//You get "Property1" as a result

  var PropetyValue=d.GetType().GetProperty(property.Name).GetValue(d, null); 
//You get "Value1" as a result

// you can use the PropertyName and Value here
 }

Can you force Visual Studio to always run as an Administrator in Windows 8?

Also, you can check the compatibility troubleshooting

  • Right-click on Visual Studio > select Troubleshoot compatibility.
  • Select Troubleshoot Program.
  • Check The program requires additional permissions.
  • Click on Test the program.
  • Wait for a moment until the program launch. Click Next.
  • Select Yes, save these settings for this program.
  • Wait for resolving the issue.
  • Make sure the final status is fixed. Click Close.

Check the detail steps, and other ways to always open VS as Admin at Visual Studio requires the application to have elevated permissions.

Hash Map in Python

Hash maps are built-in in Python, they're called dictionaries:

streetno = {}                        #create a dictionary called streetno
streetno["1"] = "Sachin Tendulkar"   #assign value to key "1"

Usage:

"1" in streetno                      #check if key "1" is in streetno
streetno["1"]                        #get the value from key "1"

See the documentation for more information, e.g. built-in methods and so on. They're great, and very common in Python programs (unsurprisingly).

Retrieving subfolders names in S3 bucket from boto3

Here is a possible solution:

def download_list_s3_folder(my_bucket,my_folder):
    import boto3
    s3 = boto3.client('s3')
    response = s3.list_objects_v2(
        Bucket=my_bucket,
        Prefix=my_folder,
        MaxKeys=1000)
    return [item["Key"] for item in response['Contents']]

how to rotate a bitmap 90 degrees

I would simplify comm1x's Kotlin extension function even more:

fun Bitmap.rotate(degrees: Float) =
    Bitmap.createBitmap(this, 0, 0, width, height, Matrix().apply { postRotate(degrees) }, true)

How to find the nearest parent of a Git branch?

vbc=$(git rev-parse --abbrev-ref HEAD)
vbc_col=$(( $(git show-branch | grep '^[^\[]*\*' | head -1 | cut -d* -f1 | wc -c) - 1 )) 
swimming_lane_start_row=$(( $(git show-branch | grep -n "^[\-]*$" | cut -d: -f1) + 1 )) 
git show-branch | tail -n +$swimming_lane_start_row | grep -v "^[^\[]*\[$vbc" | grep "^.\{$vbc_col\}[^ ]" | head -n1 | sed 's/.*\[\(.*\)\].*/\1/' | sed 's/[\^~].*//'

Achieves the same ends as Mark Reed's answer, but uses a much safer approach that doesn't misbehave in a number of scenarios:

  1. Parent branch's last commit is a merge, making the column show - not *
  2. Commit message contains branch name
  3. Commit message contains *

"Unable to acquire application service" error while launching Eclipse

In the Windows environment, running Eclipse as Administrator solved the issue. (Right click>Run as Administrator)

What is the use of hashCode in Java?

hashCode() is a unique code which is generated by the JVM for every object creation.

We use hashCode() to perform some operation on hashing related algorithm like Hashtable, Hashmap etc..

The advantages of hashCode() make searching operation easy because when we search for an object that has unique code, it helps to find out that object.

But we can't say hashCode() is the address of an object. It is a unique code generated by JVM for every object.

That is why nowadays hashing algorithm is the most popular search algorithm.

What's the equivalent of Java's Thread.sleep() in JavaScript?

setTimeout would not hold and resume on your own thread however Thread.sleep does. There is no actual equal in Javascript

How do I group Windows Form radio buttons?

GroupBox is better.But not only group box, even you can use Panels (System.Windows.Forms.Panel).

  • That is very usefully when you are designing Internet Protocol version 4 setting dialog.(Check it with your pc(windows),then you can understand the behavior)

Checking if a collection is null or empty in Groovy

!members.find()

I think now the best way to solve this issue is code above. It works since Groovy 1.8.1 http://docs.groovy-lang.org/docs/next/html/groovy-jdk/java/util/Collection.html#find(). Examples:

def lst1 = []
assert !lst1.find()

def lst2 = [null]
assert !lst2.find()

def lst3 = [null,2,null]
assert lst3.find()

def lst4 = [null,null,null]
assert !lst4.find()

def lst5 = [null, 0, 0.0, false, '', [], 42, 43]
assert lst5.find() == 42

def lst6 = null; 
assert !lst6.find()

Liquibase lock - reasons?

You can safely delete the table manually or using query. It will be recreated automatically.

DROP TABLE DATABASECHANGELOGLOCK;

How to set the From email address for mailx command?

The "-r" option is invalid on my systems. I had to use a different syntax for the "From" field.

-a "From: Foo Bar <[email protected]>"

Auto-redirect to another HTML page

One of these will work...

_x000D_
_x000D_
<head>_x000D_
  <meta http-equiv='refresh' content='0; URL=http://example.com/'>_x000D_
</head>
_x000D_
_x000D_
_x000D_

...or it can done with JavaScript:

_x000D_
_x000D_
window.location.href = 'https://example.com/';
_x000D_
_x000D_
_x000D_

HTML5: Slider with two inputs possible?

The question was: "Is it possible to make a HTML5 slider with two input values, for example to select a price range? If so, how can it be done?"

Ten years ago the answer was probably 'No'. However, times have changed. In 2020 it is finally possible to create a fully accessible, native, non-jquery HTML5 slider with two thumbs for price ranges. If found this posted after I already created this solution and I thought that it would be nice to share my implementation here.

This implementation has been tested on mobile Chrome and Firefox (Android) and Chrome and Firefox (Linux). I am not sure about other platforms, but it should be quite good. I would love to get your feedback and improve this solution.

This solution allows multiple instances on one page and it consists of just two inputs (each) with descriptive labels for screen readers. You can set the thumb size in the amount of grid labels. Also, you can use touch, keyboard and mouse to interact with the slider. The value is updated during adjustment, due to the 'on input' event listener.

My first approach was to overlay the sliders and clip them. However, that resulted in complex code with a lot of browser dependencies. Then I recreated the solution with two sliders that were 'inline'. This is the solution you will find below.

_x000D_
_x000D_
var thumbsize = 14;

function draw(slider,splitvalue) {

    /* set function vars */
    var min = slider.querySelector('.min');
    var max = slider.querySelector('.max');
    var lower = slider.querySelector('.lower');
    var upper = slider.querySelector('.upper');
    var legend = slider.querySelector('.legend');
    var thumbsize = parseInt(slider.getAttribute('data-thumbsize'));
    var rangewidth = parseInt(slider.getAttribute('data-rangewidth'));
    var rangemin = parseInt(slider.getAttribute('data-rangemin'));
    var rangemax = parseInt(slider.getAttribute('data-rangemax'));

    /* set min and max attributes */
    min.setAttribute('max',splitvalue);
    max.setAttribute('min',splitvalue);

    /* set css */
    min.style.width = parseInt(thumbsize + ((splitvalue - rangemin)/(rangemax - rangemin))*(rangewidth - (2*thumbsize)))+'px';
    max.style.width = parseInt(thumbsize + ((rangemax - splitvalue)/(rangemax - rangemin))*(rangewidth - (2*thumbsize)))+'px';
    min.style.left = '0px';
    max.style.left = parseInt(min.style.width)+'px';
    min.style.top = lower.offsetHeight+'px';
    max.style.top = lower.offsetHeight+'px';
    legend.style.marginTop = min.offsetHeight+'px';
    slider.style.height = (lower.offsetHeight + min.offsetHeight + legend.offsetHeight)+'px';
    
    /* correct for 1 off at the end */
    if(max.value>(rangemax - 1)) max.setAttribute('data-value',rangemax);

    /* write value and labels */
    max.value = max.getAttribute('data-value'); 
    min.value = min.getAttribute('data-value');
    lower.innerHTML = min.getAttribute('data-value');
    upper.innerHTML = max.getAttribute('data-value');

}

function init(slider) {
    /* set function vars */
    var min = slider.querySelector('.min');
    var max = slider.querySelector('.max');
    var rangemin = parseInt(min.getAttribute('min'));
    var rangemax = parseInt(max.getAttribute('max'));
    var avgvalue = (rangemin + rangemax)/2;
    var legendnum = slider.getAttribute('data-legendnum');

    /* set data-values */
    min.setAttribute('data-value',rangemin);
    max.setAttribute('data-value',rangemax);
    
    /* set data vars */
    slider.setAttribute('data-rangemin',rangemin); 
    slider.setAttribute('data-rangemax',rangemax); 
    slider.setAttribute('data-thumbsize',thumbsize); 
    slider.setAttribute('data-rangewidth',slider.offsetWidth);

    /* write labels */
    var lower = document.createElement('span');
    var upper = document.createElement('span');
    lower.classList.add('lower','value');
    upper.classList.add('upper','value');
    lower.appendChild(document.createTextNode(rangemin));
    upper.appendChild(document.createTextNode(rangemax));
    slider.insertBefore(lower,min.previousElementSibling);
    slider.insertBefore(upper,min.previousElementSibling);
    
    /* write legend */
    var legend = document.createElement('div');
    legend.classList.add('legend');
    var legendvalues = [];
    for (var i = 0; i < legendnum; i++) {
        legendvalues[i] = document.createElement('div');
        var val = Math.round(rangemin+(i/(legendnum-1))*(rangemax - rangemin));
        legendvalues[i].appendChild(document.createTextNode(val));
        legend.appendChild(legendvalues[i]);

    } 
    slider.appendChild(legend);

    /* draw */
    draw(slider,avgvalue);

    /* events */
    min.addEventListener("input", function() {update(min);});
    max.addEventListener("input", function() {update(max);});
}

function update(el){
    /* set function vars */
    var slider = el.parentElement;
    var min = slider.querySelector('#min');
    var max = slider.querySelector('#max');
    var minvalue = Math.floor(min.value);
    var maxvalue = Math.floor(max.value);
    
    /* set inactive values before draw */
    min.setAttribute('data-value',minvalue);
    max.setAttribute('data-value',maxvalue);

    var avgvalue = (minvalue + maxvalue)/2;

    /* draw */
    draw(slider,avgvalue);
}

var sliders = document.querySelectorAll('.min-max-slider');
sliders.forEach( function(slider) {
    init(slider);
});
_x000D_
* {padding: 0; margin: 0;}
body {padding: 40px;}

.min-max-slider {position: relative; width: 200px; text-align: center; margin-bottom: 50px;}
.min-max-slider > label {display: none;}
span.value {height: 1.7em; font-weight: bold; display: inline-block;}
span.value.lower::before {content: "€"; display: inline-block;}
span.value.upper::before {content: "- €"; display: inline-block; margin-left: 0.4em;}
.min-max-slider > .legend {display: flex; justify-content: space-between;}
.min-max-slider > .legend > * {font-size: small; opacity: 0.25;}
.min-max-slider > input {cursor: pointer; position: absolute;}

/* webkit specific styling */
.min-max-slider > input {
  -webkit-appearance: none;
  outline: none!important;
  background: transparent;
  background-image: linear-gradient(to bottom, transparent 0%, transparent 30%, silver 30%, silver 60%, transparent 60%, transparent 100%);
}
.min-max-slider > input::-webkit-slider-thumb {
  -webkit-appearance: none; /* Override default look */
  appearance: none;
  width: 14px; /* Set a specific slider handle width */
  height: 14px; /* Slider handle height */
  background: #eee; /* Green background */
  cursor: pointer; /* Cursor on hover */
  border: 1px solid gray;
  border-radius: 100%;
}
.min-max-slider > input::-webkit-slider-runnable-track {cursor: pointer;}
_x000D_
<div class="min-max-slider" data-legendnum="2">
    <label for="min">Minimum price</label>
    <input id="min" class="min" name="min" type="range" step="1" min="0" max="3000" />
    <label for="max">Maximum price</label>
    <input id="max" class="max" name="max" type="range" step="1" min="0" max="3000" />
</div>
_x000D_
_x000D_
_x000D_

Note that you should keep the step size to 1 to prevent the values to change due to redraws/redraw bugs.

View online at: https://codepen.io/joosts/pen/rNLdxvK

How to copy sheets to another workbook using vba?

    Workbooks.Open Filename:="Path(Ex: C:\Reports\ClientWiseReport.xls)"ReadOnly:=True


    For Each Sheet In ActiveWorkbook.Sheets

        Sheet.Copy After:=ThisWorkbook.Sheets(1)

    Next Sheet

Google.com and clients1.google.com/generate_204

Like Snukker said, clients1.google.com is where the search suggestions come from. My guess is that they make a request to force clients1.google.com into your DNS cache before you need it, so you will have less latency on the first "real" request.

Google Chrome already does that for any links on a page, and (I think) when you type an address in the location bar. This seems like a way to get all browsers to do the same thing.

How to use if - else structure in a batch file?

I think in the question and in some of the answers there is a bit of confusion about the meaning of this pseudocode in DOS: IF A IF B X ELSE Y. It does not mean IF(A and B) THEN X ELSE Y, but in fact means IF A( IF B THEN X ELSE Y). If the test of A fails, then he whole of the inner if-else will be ignored.

As one of the answers mentioned, in this case only one of the tests can succeed so the 'else' is not needed, but of course that only works in this example, it isn't a general solution for doing if-else.

There are lots of ways around this. Here is a few ideas, all are quite ugly but hey, this is (or at least was) DOS!

@echo off

set one=1
set two=2

REM Example 1

IF %one%_%two%==1_1 (
   echo Example 1 fails
) ELSE IF %one%_%two%==1_2 (
   echo Example 1 works correctly
) ELSE (
    echo Example 1 fails
)

REM Example 2

set test1result=0
set test2result=0

if %one%==1 if %two%==1 set test1result=1
if %one%==1 if %two%==2 set test2result=1

IF %test1result%==1 (
   echo Example 2 fails
) ELSE IF %test2result%==1 (
   echo Example 2 works correctly
) ELSE (
    echo Example 2 fails
)

REM Example 3

if %one%==1 if %two%==1 (
   echo Example 3 fails
   goto :endoftests
)
if %one%==1 if %two%==2 (
   echo Example 3 works correctly
   goto :endoftests
)
echo Example 3 fails
)
:endoftests

Bad Request, Your browser sent a request that this server could not understand

If you use Apache httpd web server in version above 2.2.15-60, then it could be also because of underscore _ in hostname.

https://ma.ttias.be/apache-httpd-2-2-15-60-underscores-hostnames-now-blocked/

Namespace not recognized (even though it is there)

I have a similar problem with references not being recognized in VS2010 and the answers herein were not able to correct it.

The problem in my solution was related to the extension of the path where the project referenced was located. As I am working with SVN, I made a branch of a repository to do some testing and that branch increased two levels in path structure, so the path became too long to be usable in windows. This did not throw any error but did not recognize the namespace of the project reference. When I correct the location of the project to have a smaller path everything went fine.

How/When does Execute Shell mark a build as failure in Jenkins?

Plain and simple:

If Jenkins sees the build step (which is a script too) exits with non-zero code, the build is marked with a red ball (= failed).

Why exactly that happens depends on your build script.

I wrote something similar from another point-of-view but maybe it will help to read it anyway: Why does Jenkins think my build succeeded?

Detecting the character encoding of an HTTP POST request

The Charset used in the POST will match that of the Charset specified in the HTML hosting the form. Hence if your form is sent using UTF-8 encoding that is the encoding used for the posted content. The URL encoding is applied after the values are converted to the set of octets for the character encoding.

How to remove trailing whitespaces with sed?

To only strip whitespaces (in my case spaces and tabs) from lines with at least one non-whitespace character (this way empty indented lines are not touched):

sed -i -r 's/([^ \t]+)[ \t]+$/\1/' "$file"

Reading a simple text file

In Mono For Android....

try
{
    System.IO.Stream StrIn = this.Assets.Open("MyMessage.txt");
    string Content = string.Empty;
    using (System.IO.StreamReader StrRead = new System.IO.StreamReader(StrIn))
    {
      try
      {
            Content = StrRead.ReadToEnd();
            StrRead.Close();
      }  
      catch (Exception ex) { csFunciones.MostarMsg(this, ex.Message); }
      }
          StrIn.Close();
          StrIn = null;
}
catch (Exception ex) { csFunciones.MostarMsg(this, ex.Message); }

What is the Difference Between read() and recv() , and Between send() and write()?

Another thing on linux is:

send does not allow to operate on non-socket fd. Thus, for example to write on usb port, write is necessary.

Set a button background image iPhone programmatically

This will work

UIImage *buttonImage = [UIImage imageNamed:@"imageName.png"];
[btn setImage:buttonImage forState:UIControlStateNormal];
[self.view addSubview:btn];

What do raw.githubusercontent.com URLs represent?

There are two ways of looking at github content, the "raw" way and the "Web page" way.

raw.githubusercontent.com returns the raw content of files stored in github, so they can be downloaded simply to your computer. For example, if the page represents a ruby install script, then you will get a ruby install script that your ruby installation will understand.

If you instead download the file using the github.com link, you will actually be downloading a web page with buttons and comments and which displays your wanted script in the middle -- it's what you want to give to your web browser to get a nice page to look at, but for the computer, it is not a script that can be executed or code that can be compiled, but a web page to be displayed. That web page has a button called Raw that sends you to the corresponding content on raw.githubusercontent.com.

To see the content of raw.githubusercontent.com/${repo}/${branch}/${path} in the usual github interface:

  1. you replace raw.githubusercontent.com with plain github.com
  2. AND you insert "blob" between the repo name and the branch name.

In this case, the branch name is "master" (which is a very common branch name), so you replace /master/ with /blob/master/, and so

https://raw.githubusercontent.com/Homebrew/install/master/install

becomes

https://github.com/Homebrew/install/blob/master/install

This is the reverse of finding a file on Github and clicking the Raw link.

Reading a file line by line in Go

In the new version of Go 1.16 we can use package embed to read the file contents as shown below.

package main

import _"embed"


func main() {
    //go:embed "hello.txt"
    var s string
    print(s)

    //go:embed "hello.txt"
    var b []byte
    print(string(b))

    //go:embed hello.txt
    var f embed.FS
    data, _ := f.ReadFile("hello.txt")
    print(string(data))
}

For more details go through https://tip.golang.org/pkg/embed/ And https://golangtutorial.dev/tips/embed-files-in-go/

Trigger an action after selection select2

See the documentation events section

Depending on the version, one of the snippets below should give you the event you want, alternatively just replace "select2-selecting" with "change".

Version 4.0 +

Events are now in format: select2:selecting (instead of select2-selecting)

Thanks to snakey for the notification that this has changed as of 4.0

$('#yourselect').on("select2:selecting", function(e) { 
   // what you would like to happen
});

Version Before 4.0

$('#yourselect').on("select2-selecting", function(e) { 
   // what you would like to happen
});

Just to clarify, the documentation for select2-selecting reads:

select2-selecting Fired when a choice is being selected in the dropdown, but before any modification has been made to the selection. This event is used to allow the user to reject selection by calling event.preventDefault()

whereas change has:

change Fired when selection is changed.

So change may be more appropriate for your needs, depending on whether you want the selection to complete and then do your event, or potentially block the change.

Check key exist in python dict

Use the in keyword.

if 'apples' in d:
    if d['apples'] == 20:
        print('20 apples')
    else:
        print('Not 20 apples')

If you want to get the value only if the key exists (and avoid an exception trying to get it if it doesn't), then you can use the get function from a dictionary, passing an optional default value as the second argument (if you don't pass it it returns None instead):

if d.get('apples', 0) == 20:
    print('20 apples.')
else:
    print('Not 20 apples.')

Is it possible to declare a variable in Gradle usable in Java?

rciovati's answer is entirely correct I just wanted to add one more tidbit that you can also create variables for every build type within the default config portion of your build.gradle. This would look like this:

android {
    defaultConfig {
        buildConfigField "String", "APP_NAME", "\"APP_NAME\""
    }
}

This will allow you to have access to through

BuildConfig.App_NAME

Just wanted to make a note of this scenario as well if you want a common config.

Difference between WebStorm and PHPStorm

In my own experience, even though theoretically many JetBrains products share the same functionalities, the new features that get introduced in some apps don't get immediately introduced in the others. In particular, IntelliJ IDEA has a new version once per year, while WebStorm and PHPStorm get 2 to 3 per year I think. Keep that in mind when choosing an IDE. :)

Sorting a vector in descending order

Actually, the first one is a bad idea. Use either the second one, or this:

struct greater
{
    template<class T>
    bool operator()(T const &a, T const &b) const { return a > b; }
};

std::sort(numbers.begin(), numbers.end(), greater());

That way your code won't silently break when someone decides numbers should hold long or long long instead of int.

Float a div above page content

The results container div has position: relative meaning it is still in the document flow and will change the layout of elements around it. You need to use position: absolute to achieve a 'floating' effect.

You should also check the markup you're using, you have phantom <li>s with no container <ul>, you could probably replace both the div#suggestions and div#autoSuggestionsList with a single <ul> and get the desired result.

Setting width to wrap_content for TextView through code

I am posting android Java base multi line edittext.

EditText editText = findViewById(R.id.editText);/* edittext access */

ViewGroup.LayoutParams params  =  editText.getLayoutParams(); 
params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
editText.setLayoutParams(params); /* Gives as much height for multi line*/

editText.setSingleLine(false); /* Makes it Multi line */

convert big endian to little endian in C [without using provided func]

EDIT: This function only swaps the endianness of aligned 16 bit words. A function often necessary for UTF-16/UCS-2 encodings. EDIT END.

If you want to change the endianess of a memory block you can use my blazingly fast approach. Your memory array should have a size that is a multiple of 8.

#include <stddef.h>
#include <limits.h>
#include <stdint.h>

void ChangeMemEndianness(uint64_t *mem, size_t size) 
{
uint64_t m1 = 0xFF00FF00FF00FF00ULL, m2 = m1 >> CHAR_BIT;

size = (size + (sizeof (uint64_t) - 1)) / sizeof (uint64_t);
for(; size; size--, mem++)
  *mem = ((*mem & m1) >> CHAR_BIT) | ((*mem & m2) << CHAR_BIT);
}

This kind of function is useful for changing the endianess of Unicode UCS-2/UTF-16 files.

using batch echo with special characters

The answer from Joey was not working for me. After executing

  echo ^<?xml version="1.0" encoding="utf-8" ?^> > myfile.xml

I got this error bash: syntax error near unexpected token `>'

This solution worked for me:

 echo "<?xml version=\"1.0\" encoding=\"utf-8\">" > myfile.txt

See also http://www.robvanderwoude.com/escapechars.php

Makefile If-Then Else and Loops

Here's an example if:

ifeq ($(strip $(OS)),Linux)
        PYTHON = /usr/bin/python
        FIND = /usr/bin/find
endif

Note that this comes with a word of warning that different versions of Make have slightly different syntax, none of which seems to be documented very well.

IIS error, Unable to start debugging on the webserver

There may be many reasons for the above problem.

You need to check this:- Unable to Start Debugging on the Web Server

On a side note:- Go to IIS and check that the App Pool you are using is started.

Try this from your command line:-

cd %windir%\Microsoft.NET\Framework\v4.0.30319
aspnet_regiis.exe -i

What does LINQ return when the results are empty

It won't throw exception, you'll get an empty list.

How to view AndroidManifest.xml from APK file?

To decode the AndroidManifest.xml file using axmldec:

axmldec -o output.xml AndroidManifest.xml

or

axmldec -o output.xml AndroidApp.apk

Simplest way to restart service on a remote computer

I recommend the method given by doofledorfer.

If you really want to do it via a direct API call, then look at the OpenSCManager function. Below are sample functions to take a machine name and service, and stop or start them.

function ServiceStart(sMachine, sService : string) : boolean;  //start service, return TRUE if successful
var schm, schs : SC_Handle;
    ss         : TServiceStatus;
    psTemp     : PChar;
    dwChkP     : DWord;
begin
  ss.dwCurrentState := 0;
  schm := OpenSCManager(PChar(sMachine),Nil,SC_MANAGER_CONNECT);  //connect to the service control manager

  if(schm > 0)then begin // if successful...
    schs := OpenService( schm,PChar(sService),SERVICE_START or SERVICE_QUERY_STATUS);    // open service handle, start and query status
    if(schs > 0)then begin     // if successful...
      psTemp := nil;
      if (StartService(schs,0,psTemp)) and (QueryServiceStatus(schs,ss)) then
        while(SERVICE_RUNNING <> ss.dwCurrentState)do begin
          dwChkP := ss.dwCheckPoint;  //dwCheckPoint contains a value incremented periodically to report progress of a long operation.  Store it.
          Sleep(ss.dwWaitHint);  //Sleep for recommended time before checking status again
          if(not QueryServiceStatus(schs,ss))then
            break;  //couldn't check status
          if(ss.dwCheckPoint < dwChkP)then
            Break;  //if QueryServiceStatus didn't work for some reason, avoid infinite loop
        end;  //while not running
      CloseServiceHandle(schs);
    end;  //if able to get service handle
    CloseServiceHandle(schm);
  end;  //if able to get svc mgr handle
  Result := SERVICE_RUNNING = ss.dwCurrentState;  //if we were able to start it, return true
end;

function ServiceStop(sMachine, sService : string) : boolean;  //stop service, return TRUE if successful
var schm, schs : SC_Handle;
    ss         : TServiceStatus;
    dwChkP     : DWord;
begin
  schm := OpenSCManager(PChar(sMachine),nil,SC_MANAGER_CONNECT);

  if(schm > 0)then begin
    schs := OpenService(schm,PChar(sService),SERVICE_STOP or SERVICE_QUERY_STATUS);
    if(schs > 0)then begin
      if (ControlService(schs,SERVICE_CONTROL_STOP,ss)) and (QueryServiceStatus(schs,ss)) then
        while(SERVICE_STOPPED <> ss.dwCurrentState) do begin
          dwChkP := ss.dwCheckPoint;
          Sleep(ss.dwWaitHint);
          if(not QueryServiceStatus(schs,ss))then
            Break;

          if(ss.dwCheckPoint < dwChkP)then
            Break;
        end;  //while
      CloseServiceHandle(schs);
    end;  //if able to get svc handle
    CloseServiceHandle(schm);
  end;  //if able to get svc mgr handle
  Result := SERVICE_STOPPED = ss.dwCurrentState;
end;

How to recover closed output window in netbeans?

I had this same issue recently and none of the other fixes worked. I got it to show finally by switching to the "Services" tab, right-clicking on "Apache Tomcat or TomEE" and clicking "Restart".

When to use Task.Delay, when to use Thread.Sleep?

I want to add something. Actually, Task.Delay is a timer based wait mechanism. If you look at the source you would find a reference to a Timer class which is responsible for the delay. On the other hand Thread.Sleep actually makes current thread to sleep, that way you are just blocking and wasting one thread. In async programming model you should always use Task.Delay() if you want something(continuation) happen after some delay.

How to manage exceptions thrown in filters in Spring?

You can use the following method inside the catch block:

response.sendError(HttpStatus.UNAUTHORIZED.value(), "Invalid token")

Notice that you can use any HttpStatus code and a custom message.

POST request not allowed - 405 Not Allowed - nginx, even with headers included

This is the real proxy redirection to the intended server.

server {
  listen          80;
  server_name     localhost;
location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-NginX-Proxy true;
    proxy_pass http://xx.xxx.xxx.xxx/;
    proxy_redirect off;
    proxy_set_header Host $host;

  }
}

How to use the DropDownList's SelectedIndexChanged event

You should add AutoPostBack="true" to DropDownList1

                <asp:DropDownList ID="ddmanu" runat="server" AutoPostBack="true"
                    DataSourceID="Sql_fur_model_manu"    
                    DataTextField="manufacturer" DataValueField="manufacturer" 
                    onselectedindexchanged="ddmanu_SelectedIndexChanged">
                </asp:DropDownList>

How to remove all line breaks from a string

I am adding my answer, it is just an addon to the above, as for me I tried all the /n options and it didn't work, I saw my text is comming from server with double slash so I used this:

var fixedText = yourString.replace(/(\r\n|\n|\r|\\n)/gm, '');

How do I install a custom font on an HTML site

For the best possible browser support, your CSS code should look like this :

@font-face {
  font-family: 'MyWebFont';
  src: url('webfont.eot'); /* IE9 Compat Modes */
  src: url('webfont.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
       url('webfont.woff2') format('woff2'), /* Super Modern Browsers */
       url('webfont.woff') format('woff'), /* Pretty Modern Browsers */
       url('webfont.ttf')  format('truetype'), /* Safari, Android, iOS */
       url('webfont.svg#svgFontName') format('svg'); /* Legacy iOS */
}

body {
  font-family: 'MyWebFont', Fallback, sans-serif;
}

For more info, see the article Using @font-face at CSS-tricks.com.

Eclipse comment/uncomment shortcut?

An easier way is to press Ctrl + Shift + C, just like in Code::Blocks

Python DNS module import error

One possible reason here might be your script have wrong shebang (so it is not using python from your virtualenv). I just did this change and it works:

-#!/bin/python
+#!/usr/bin/env python

Or ignore shebang and just run the script with python in your venv:

$ python your_script.py

Eclipse - java.lang.ClassNotFoundException

Make sure if your test class working before , but you facing issue all of sudden. then clean your project and build it again. Make sure project has been configured in build path as read above article.

How to describe table in SQL Server 2008?

As a variation of Bridge's answer (I don't yet have enough rep to comment, and didn't feel right about editing that answer), here is a version that works better for me.

SELECT column_name AS [Name],
   IS_NULLABLE AS [Null?],
   DATA_TYPE + CASE
                 WHEN CHARACTER_MAXIMUM_LENGTH IS NULL THEN ''
                 WHEN CHARACTER_MAXIMUM_LENGTH > 99999 THEN ''
                 ELSE '(' + Cast(CHARACTER_MAXIMUM_LENGTH AS VARCHAR(5)) + ')' 
               END AS [Type]
FROM   INFORMATION_SCHEMA.Columns
WHERE  table_name = 'table_name'

Notable changes:

  • Works for types without length. For an int column, I was seeing NULL for the type because the length was null and it wiped out the whole Type column. So don't print any length component (or parens).
  • Change the check for CAST length of -1 to check actual length. I was getting a syntax error because the case resulted in '*' rather than -1. Seems to make more sense to perform an arithmetic check rather than an overflow from the CAST.
  • Don't print length when very long (arbitrarily > 5 digits).

Monitor the Graphics card usage

From Unix.SE: A simple command-line utility called gpustat now exists: https://github.com/wookayin/gpustat.

It is free software (MIT license) and is packaged in pypi. It is a wrapper of nvidia-smi.

Add to integers in a list

If you try appending the number like, say listName.append(4) , this will append 4 at last. But if you are trying to take <int> and then append it as, num = 4 followed by listName.append(num), this will give you an error as 'num' is of <int> type and listName is of type <list>. So do type cast int(num) before appending it.

How to check for DLL dependency?

In the past (i.e. WinXP days), I used to depend/rely on DLL Dependency Walker (depends.exe) but there are times when I am still not able to determine the DLL issue(s). Ideally, we'd like to find out before runtime by inspections but if that does not resolve it (or taking too much time), you can try enabling the "loader snap" as described on http://blogs.msdn.com/b/junfeng/archive/2006/11/20/debugging-loadlibrary-failures.aspx and https://msdn.microsoft.com/en-us/library/windows/hardware/ff556886(v=vs.85).aspx and briefly mentioned LoadLibrary fails; GetLastError no help

WARNING: I've messed up my Windows in the past fooling around with gflag making it crawl to its knees, you have been forewarned.

enter image description here

Note: "Loader snap" is per-process so the UI enable won't stay checked (use cdb or glfags -i)

How can I exclude multiple folders using Get-ChildItem -exclude?

You could also do this in a single statement:

$j = "Somepath"
$files = Get-ChildItem -Path $j -Include '*.xlsx','*.zip' -Recurse -ErrorAction SilentlyContinue –File | ? {$_.Directory -notlike "$j\donotwantfoldername"}

How to use QTimer

Other way is using of built-in method start timer & event TimerEvent.

Header:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private:
    Ui::MainWindow *ui;
    int timerId;

protected:
    void timerEvent(QTimerEvent *event);
};

#endif // MAINWINDOW_H

Source:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    timerId = startTimer(1000);
}

MainWindow::~MainWindow()
{
    killTimer(timerId);
    delete ui;
}

void MainWindow::timerEvent(QTimerEvent *event)
{
    qDebug() << "Update...";
}

How to implement a Keyword Search in MySQL?

I will explain the method i usally prefer:

First of all you need to take into consideration that for this method you will sacrifice memory with the aim of gaining computation speed. Second you need to have a the right to edit the table structure.

1) Add a field (i usually call it "digest") where you store all the data from the table.

The field will look like:

"n-n1-n2-n3-n4-n5-n6-n7-n8-n9" etc.. where n is a single word

I achieve this using a regular expression thar replaces " " with "-". This field is the result of all the table data "digested" in one sigle string.

2) Use the LIKE statement %keyword% on the digest field:

SELECT * FROM table WHERE digest LIKE %keyword%

you can even build a qUery with a little loop so you can search for multiple keywords at the same time looking like:

SELECT * FROM table WHERE 
 digest LIKE %keyword1% AND 
 digest LIKE %keyword2% AND 
 digest LIKE %keyword3% ... 

Loop code for each file in a directory

Looks for the function glob():

<?php
$files = glob("dir/*.jpg");
foreach($files as $jpg){
    echo $jpg, "\n";
}
?>

What's the best way to parse a JSON response from the requests library?

You can use json.loads:

import json
import requests

response = requests.get(...)
json_data = json.loads(response.text)

This converts a given string into a dictionary which allows you to access your JSON data easily within your code.

Or you can use @Martijn's helpful suggestion, and the higher voted answer, response.json().

'innerText' works in IE, but not in Firefox

A really simple line of Javascript can get the "non-taggy" text in all main browsers...

var myElement = document.getElementById('anyElementId');
var myText = (myElement.innerText || myElement.textContent);

How to get config parameters in Symfony2 Twig Templates

In confing.yml

# app/config/config.yml
twig:
  globals:
    version: '%app.version%'

In Twig view

# twig view
{{ version }}

Default value of function parameter

The first way would be preferred to the second.

This is because the header file will show that the parameter is optional and what its default value will be. Additionally, this will ensure that the default value will be the same, no matter the implementation of the corresponding .cpp file.

In the second way, there is no guarantee of a default value for the second parameter. The default value could change, depending on how the corresponding .cpp file is implemented.

MSVCP140.dll missing

Either make your friends download the runtime DLL (@Kay's answer), or compile the app with static linking.

In visual studio, go to Project tab -> properties - > configuration properties -> C/C++ -> Code Generation on runtime library choose /MTd for debug mode and /MT for release mode.

This will cause the compiler to embed the runtime into the app. The executable will be significantly bigger, but it will run without any need of runtime dlls.

Case statement with multiple values in each 'when' block

You might take advantage of ruby's "splat" or flattening syntax.

This makes overgrown when clauses — you have about 10 values to test per branch if I understand correctly — a little more readable in my opinion. Additionally, you can modify the values to test at runtime. For example:

honda  = ['honda', 'acura', 'civic', 'element', 'fit', ...]
toyota = ['toyota', 'lexus', 'tercel', 'rx', 'yaris', ...]
...

if include_concept_cars
  honda += ['ev-ster', 'concept c', 'concept s', ...]
  ...
end

case car
when *toyota
  # Do something for Toyota cars
when *honda
  # Do something for Honda cars
...
end

Another common approach would be to use a hash as a dispatch table, with keys for each value of car and values that are some callable object encapsulating the code you wish to execute.