Programs & Examples On #Preference

How to change the integrated terminal in visual studio code or VSCode

From Official Docs

Correctly configuring your shell on Windows is a matter of locating the right executable and updating the setting. Below is a list of common shell executables and their default locations.

There is also the convenience command Select Default Shell that can be accessed through the command palette which can detect and set this for you.

So you can open a command palette using ctrl+shift+p, use the command Select Default Shell, then it displays all the available command line interfaces, select whatever you want, VS code sets that as default integrated terminal for you automatically.

If you want to set it manually find the location of executable of your cli and open user settings of vscode(ctrl+,) then set

"terminal.integrated.shell.windows":"path/to/executable.exe"

Example for gitbash on windows7:

"terminal.integrated.shell.windows":"C:\\Users\\stldev03\\AppData\\Local\\Programs\\Git\\bin\\bash.exe",

Field 'browser' doesn't contain a valid alias configuration

In my situation, I did not have an export at the bottom of my webpack.config.js file. Simply adding

export default Config;

solved it.

How to disable a particular checkstyle rule for a particular line of code?

<module name="Checker">
    <module name="SuppressionCommentFilter"/>
    <module name="TreeWalker">
        <module name="FileContentsHolder"/>
    </module>
</module>

To configure a filter to suppress audit events between a comment containing line BEGIN GENERATED CODE and a comment containing line END GENERATED CODE:

<module name="SuppressionCommentFilter">
  <property name="offCommentFormat" value="BEGIN GENERATED CODE"/>
  <property name="onCommentFormat" value="END GENERATED CODE"/>
</module>

//BEGIN GENERATED CODE
@Override
public boolean equals(Object obj) { ... } // No violation events will be reported

@Override
public int hashCode() { ... } // No violation events will be reported
//END GENERATED CODE

See more

vbscript output to console

You mean:

Wscript.Echo "Like this?"

If you run that under wscript.exe (the default handler for the .vbs extension, so what you'll get if you double-click the script) you'll get a "MessageBox" dialog with your text in it. If you run that under cscript.exe you'll get output in your console window.

Example use of "continue" statement in Python?

Here is very good visual representation about continue and break statements

Chart

source

Adjust table column width to content size

If you want the table to still be 100% then set one of the columns to have a width:100%; That will extend that column to fill the extra space and allow the other columns to keep their auto width :)

What does the servlet <load-on-startup> value signify

yes it can have same value....the reason for giving numbers to load-on-startup is to define a sequence for server to load all the servlet. servlet with 0 load-on-startup value will load first and servlet with value 1 will load after that.

if two servlets will have the same value for load-on-startup than it will be loaded how they are declared in the web.xml from top to bottom. the servlet which comes first in the web.xml will be loaded first and the other will be loaded after that.

twitter-bootstrap: how to get rid of underlined button text when hovering over a btn-group within an <a>-tag?

The problem is that you're targeting the button, but it's the A Tag that causes the text-decoration: underline. So if you target the A tag then it should work.

a:hover, a:focus { text-decoration: none;}

How to apply a CSS filter to a background image

Now this become even simpler and more flexible by using CSS GRID.You just have to overlap the blured background(imgbg) with the text(h2)

<div class="container">
 <div class="imgbg"></div>
 <h2>
  Lorem ipsum dolor sit amet consectetur, adipisicing elit. Facilis enim
  aut rerum mollitia quas voluptas delectus facere magni cum unde?:)
 </h2>
</div>

and the css:

.container {
        display: grid;
        width: 30em;
      }

.imgbg {
        background: url(bg3.jpg) no-repeat center;
        background-size: cover;
        grid-column: 1/-1;
        grid-row: 1/-1;
        filter: blur(4px);
      }


     .container h2 {
        text-transform: uppercase;
        grid-column: 1/-1;
        grid-row: 1/-1;
        z-index: 2;
      }

How can a add a row to a data frame in R?

To formalize what someone else used setNames for:

add_row <- function(original_data, new_vals_list){ 
  # appends row to dataset while assuming new vals are ordered and classed appropriately. 
  # new_vals must be a list not a single vector. 
  rbind(
    original_data,
    setNames(data.frame(new_vals_list), colnames(original_data))
    )
  }

It preserves class when legal and passes errors elsewhere.

m <- mtcars[ ,1:3]
m$cyl <- as.factor(m$cyl)
str(m)

#'data.frame':  32 obs. of  3 variables:
# $ mpg : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
# $ cyl : Factor w/ 3 levels "4","6","8": 2 2 1 2 3 2 3 1 1 2 ...
# $ disp: num  160 160 108 258 360 ...

Factor preserved when adding 4, even though it was passed as a numeric.

str(add_row(m, list(20,4,160)))
#'data.frame':  33 obs. of  3 variables:
# $ mpg : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
# $ cyl : Factor w/ 3 levels "4","6","8": 2 2 1 2 3 2 3 1 1 2 ... 
# $ disp: num  160 160 108 258 360 ...

Attempting to pass a non- 4,6,8 would return an error that factor level is invalid.

str(add_row(m, list(20,3,160)))
# 'data.frame': 33 obs. of  3 variables:
# $ mpg : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
# $ cyl : Factor w/ 3 levels "4","6","8": 2 2 1 2 3 2 3 1 1 2 ...
# $ disp: num  160 160 108 258 360 ...
Warning message:
In `[<-.factor`(`*tmp*`, ri, value = 3) :
  invalid factor level, NA generated

forcing web-site to show in landscape mode only

@Golmaal really answered this, I'm just being a bit more verbose.

<style type="text/css">
    #warning-message { display: none; }
    @media only screen and (orientation:portrait){
        #wrapper { display:none; }
        #warning-message { display:block; }
    }
    @media only screen and (orientation:landscape){
        #warning-message { display:none; }
    }
</style>

....

<div id="wrapper">
    <!-- your html for your website -->
</div>
<div id="warning-message">
    this website is only viewable in landscape mode
</div>

You have no control over the user moving the orientation however you can at least message them. This example will hide the wrapper if in portrait mode and show the warning message and then hide the warning message in landscape mode and show the portrait.

I don't think this answer is any better than @Golmaal , only a compliment to it. If you like this answer, make sure to give @Golmaal the credit.

Update

I've been working with Cordova a lot recently and it turns out you CAN control it when you have access to the native features.

Another Update

So after releasing Cordova it is really terrible in the end. It is better to use something like React Native if you want JavaScript. It is really amazing and I know it isn't pure web but the pure web experience on mobile kind of failed.

how to check if a datareader is null or empty

I also experiencing this kind of problem but mine, i'm using DbDataReader as my generic reader (for SQL, Oracle, OleDb, etc.). If using DataTable, DataTable has this method:

DataTable dt = new DataTable();
dt.Rows[0].Table.Columns.Contains("SampleColumn");

using this I can determine if that column is existing in the result set that my query has. I'm also looking if DbDataReader has this capability.

How to properly use the "choices" field option in Django

I think no one actually has answered to the first question:

Why did they create those variables?

Those variables aren't strictly necessary. It's true. You can perfectly do something like this:

MONTH_CHOICES = (
    ("JANUARY", "January"),
    ("FEBRUARY", "February"),
    ("MARCH", "March"),
    # ....
    ("DECEMBER", "December"),
)

month = models.CharField(max_length=9,
                  choices=MONTH_CHOICES,
                  default="JANUARY")

Why using variables is better? Error prevention and logic separation.

JAN = "JANUARY"
FEB = "FEBRUARY"
MAR = "MAR"
# (...)

MONTH_CHOICES = (
    (JAN, "January"),
    (FEB, "February"),
    (MAR, "March"),
    # ....
    (DEC, "December"),
)

Now, imagine you have a view where you create a new Model instance. Instead of doing this:

new_instance = MyModel(month='JANUARY')

You'll do this:

new_instance = MyModel(month=MyModel.JAN)

In the first option you are hardcoding the value. If there is a set of values you can input, you should limit those options when coding. Also, if you eventually need to change the code at the Model layer, now you don't need to make any change in the Views layer.

Running Bash commands in Python

Also you can use 'os.popen'. Example:

import os

command = os.popen('ls -al')
print(command.read())
print(command.close())

Output:

total 16
drwxr-xr-x 2 root root 4096 ago 13 21:53 .
drwxr-xr-x 4 root root 4096 ago 13 01:50 ..
-rw-r--r-- 1 root root 1278 ago 13 21:12 bot.py
-rw-r--r-- 1 root root   77 ago 13 21:53 test.py

None

How to break lines in PowerShell?

I think I found it. All you have to do is type in "`n" (WITH THE QUOTATION MARKS!)

Thanks!

How to Toggle a div's visibility by using a button click

with JQuery .toggle() you can accomplish it easily

$( ".target" ).toggle();

Splitting a table cell into two columns in HTML

Like this http://jsfiddle.net/8ha9e/1/

Add colspan="2" to the 3rd <th> and then have 4 <td>'s in your second row.

<table border="1">
  <tr>
    <th scope="col">Header</th>
    <th scope="col">Header</th>
    <th scope="col" colspan="2">Header</th>
  </tr>
  <tr>
    <th scope="row">&nbsp;</th>
    <td>&nbsp;</td>
    <!-- The following two cells will appear under the same header -->
    <td>Col 1</td>
    <td>Col 2</td>
  </tr>
</table>

Easy interview question got harder: given numbers 1..100, find the missing number(s) given exactly k are missing

I asked a 4-year-old to solve this problem. He sorted the numbers and then counted along. This has a space requirement of O(kitchen floor), and it works just as easy however many balls are missing.

MySQL FULL JOIN?

Everyone is correct here but writing same query twice is not a good way of programming ... so I have another way to do the full join in mysql which is as follows

SELECT
 user_id , user_name, user_department 
FROM 
 (SELECT 
     user_id  , user_name , NULL as user_department 
  FROM
   tb_users 
 UNION 
   SELECT 
     user_id ,NULL as user_name , user_department
   FROM 
      tb_departments
 ) as t group by user_id

What should I set JAVA_HOME environment variable on macOS X 10.6?

As other answers note, the correct way to find the Java home directory is to use /usr/libexec/java_home.

The official documentation for this is in Apple's Technical Q&A QA1170: Important Java Directories on OS X: https://developer.apple.com/library/mac/qa/qa1170/_index.html

Plot multiple lines in one graph

The answer by @Federico Giorgi was a very good answer. It helpt me. Therefore, I did the following, in order to produce multiple lines in the same plot from the data of a single dataset, I used a for loop. Legend can be added as well.

plot(tab[,1],type="b",col="red",lty=1,lwd=2, ylim=c( min( tab, na.rm=T ),max( tab, na.rm=T ) )  )
for( i in 1:length( tab )) { [enter image description here][1]
lines(tab[,i],type="b",col=i,lty=1,lwd=2)
  } 
axis(1,at=c(1:nrow(tab)),labels=rownames(tab))

How to add the JDBC mysql driver to an Eclipse project?

if you are getting this exception again and again then download my-sql connector and paste in tomcat/WEB-INF/lib folder...note that some times WEB-INF folder does not contains lib folder, at that time manually create lib folder and paste mysql connector in that folder..definitely this will work.if still you got problem then check that your jdk must match your system. i.e if your system is 64 bit then jdk must be 64 bit

How to add image to canvas

You need to wait until the image is loaded before you draw it. Try this instead:

var canvas = document.getElementById('viewport'),
context = canvas.getContext('2d');

make_base();

function make_base()
{
  base_image = new Image();
  base_image.src = 'img/base.png';
  base_image.onload = function(){
    context.drawImage(base_image, 0, 0);
  }
}

i.e. draw the image in the onload callback of the image.

How to generate a core dump in Linux on a segmentation fault?

For Ubuntu 14.04

  1. Check core dump enabled:

    ulimit -a
    
  2. One of the lines should be :

    core file size          (blocks, -c) unlimited
    
  3. If not :

    gedit ~/.bashrc and add ulimit -c unlimited to end of file and save, re-run terminal.

  4. Build your application with debug information :

    In Makefile -O0 -g

  5. Run application that create core dump (core dump file with name ‘core’ should be created near application_name file):

    ./application_name
    
  6. Run under gdb:

    gdb application_name core
    

Filter dict to contain only certain keys?

Here is another simple method using del in one liner:

for key in e_keys: del your_dict[key]

e_keys is the list of the keys to be excluded. It will update your dict rather than giving you a new one.

If you want a new output dict, then make a copy of the dict before deleting:

new_dict = your_dict.copy()           #Making copy of dict

for key in e_keys: del new_dict[key]

How to get all keys with their values in redis

I had the same problem, and I felt on your post.

I think the easiest way to solve this issue is by using redis Hashtable.

It allows you to save a Hash, with different fields and values associated with every field.

To get all the fiels and values client.HGETALLL does the trick. It returns an array of

all the fields followed by their values.

More informations here https://redis.io/commands/hgetall

Some projects cannot be imported because they already exist in the workspace error in Eclipse

If you've arrived at this because you have cloned a git project into the existing workspace and now you want to promote that workspace to a full fledged project then you should use the 'Git Repositories' view -> select 'Working Directory' -> Import Projects -> Existing projects.

What does the shrink-to-fit viewport meta attribute do?

It is Safari specific, at least at time of writing, being introduced in Safari 9.0. From the "What's new in Safari?" documentation for Safari 9.0:

Viewport Changes

Viewport meta tags using "width=device-width" cause the page to scale down to fit content that overflows the viewport bounds. You can override this behavior by adding "shrink-to-fit=no" to your meta tag as shown below. The added value will prevent the page from scaling to fit the viewport.

<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">

In short, adding this to the viewport meta tag restores pre-Safari 9.0 behaviour.

Example

Here's a worked visual example which shows the difference upon loading the page in the two configurations.

The red section is the width of the viewport and the blue section is positioned outside the initial viewport (eg left: 100vw). Note how in the first example the page is zoomed to fit when shrink-to-fit=no is omitted (thus showing the out-of-viewport content) and the blue content remains off screen in the latter example.

The code for this example can be found at https://codepen.io/davidjb/pen/ENGqpv.

Without shrink-to-fit specified

Without shrink-to-fit=no

With shrink-to-fit=no

With shrink-to-fit=no

How to concatenate strings in django templates?

In my project I did it like this:

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

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

In template and using your case:

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

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

Rails and PostgreSQL: Role postgres does not exist

I ended up here after attempting to follow Ryan Bate's tutorial on deploying to AWS EC2 with rubber. Here is what happened for me: We created a new app using "

rails new blog -d postgresql

Obviosuly this creates a new app with pg as the database, but the database was not made yet. With sqlite, you just run rake db:migrate, however with pg you need to create the pg database first. Ryan did not do this step. The command is rake db:create:all, then we can run rake db:migrate

The second part is changing the database.yml file. The default for the username when the file is generated is 'appname'. However, chances are your role for postgresql admin is something different (at least it was for me). I changed it to my name (see above advice about creating a role name) and I was good to go.

Hope this helps.

Convert date field into text in Excel

If that is one table and have nothing to do with this - the simplest solution can be copy&paste to notepad then copy&paste back to excel :P

How can I debug a Perl script?

I would also recommend using the Perl debugger.

However, since you asked about something like shell's -x have a look at the Devel::Trace module which does something similar.

How to cut first n and last n columns?

The first part of your question is easy. As already pointed out, cut accepts omission of either the starting or the ending index of a column range, interpreting this as meaning either “from the start to column n (inclusive)” or “from column n (inclusive) to the end,” respectively:

$ printf 'this:is:a:test' | cut -d: -f-2
this:is
$ printf 'this:is:a:test' | cut -d: -f3-
a:test

It also supports combining ranges. If you want, e.g., the first 3 and the last 2 columns in a row of 7 columns:

$ printf 'foo:bar:baz:qux:quz:quux:quuz' | cut -d: -f-3,6-
foo:bar:baz:quux:quuz

However, the second part of your question can be a bit trickier depending on what kind of input you’re expecting. If by “last n columns” you mean “last n columns (regardless of their indices in the overall row)” (i.e. because you don’t necessarily know how many columns you’re going to find in advance) then sadly this is not possible to accomplish using cut alone. In order to effectively use cut to pull out “the last n columns” in each line, the total number of columns present in each line must be known beforehand, and each line must be consistent in the number of columns it contains.

If you do not know how many “columns” may be present in each line (e.g. because you’re working with input that is not strictly tabular), then you’ll have to use something like awk instead. E.g., to use awk to pull out the last 2 “columns” (awk calls them fields, the number of which can vary per line) from each line of input:

$ printf '/a\n/a/b\n/a/b/c\n/a/b/c/d\n' | awk -F/ '{print $(NF-1) FS $(NF)}'
/a
a/b
b/c
c/d

What does auto do in margin:0 auto?

It is a broken/very hard to use replacement for the "center" tag. It comes in handy when you need broken tables and non-working centering for blocks and text.

What is the use of "using namespace std"?

When you make a call to using namespace <some_namespace>; all symbols in that namespace will become visible without adding the namespace prefix. A symbol may be for instance a function, class or a variable.

E.g. if you add using namespace std; you can write just cout instead of std::cout when calling the operator cout defined in the namespace std.

This is somewhat dangerous because namespaces are meant to be used to avoid name collisions and by writing using namespace you spare some code, but loose this advantage. A better alternative is to use just specific symbols thus making them visible without the namespace prefix. Eg:

#include <iostream>
using std::cout;

int main() {
  cout << "Hello world!";
  return 0;
}

C++ convert hex string to signed integer

use std::stringstream

unsigned int x;   
std::stringstream ss;
ss << std::hex << "fffefffe";
ss >> x;

the following example produces -65538 as its result:

#include <sstream>
#include <iostream>

int main() {
    unsigned int x;   
    std::stringstream ss;
    ss << std::hex << "fffefffe";
    ss >> x;
    // output it as a signed type
    std::cout << static_cast<int>(x) << std::endl;
}

In the new C++11 standard, there are a few new utility functions which you can make use of! specifically, there is a family of "string to number" functions (http://en.cppreference.com/w/cpp/string/basic_string/stol and http://en.cppreference.com/w/cpp/string/basic_string/stoul). These are essentially thin wrappers around C's string to number conversion functions, but know how to deal with a std::string

So, the simplest answer for newer code would probably look like this:

std::string s = "0xfffefffe";
unsigned int x = std::stoul(s, nullptr, 16);

NOTE: Below is my original answer, which as the edit says is not a complete answer. For a functional solution, stick the code above the line :-).

It appears that since lexical_cast<> is defined to have stream conversion semantics. Sadly, streams don't understand the "0x" notation. So both the boost::lexical_cast and my hand rolled one don't deal well with hex strings. The above solution which manually sets the input stream to hex will handle it just fine.

Boost has some stuff to do this as well, which has some nice error checking capabilities as well. You can use it like this:

try {
    unsigned int x = lexical_cast<int>("0x0badc0de");
} catch(bad_lexical_cast &) {
    // whatever you want to do...
}

If you don't feel like using boost, here's a light version of lexical cast which does no error checking:

template<typename T2, typename T1>
inline T2 lexical_cast(const T1 &in) {
    T2 out;
    std::stringstream ss;
    ss << in;
    ss >> out;
    return out;
}

which you can use like this:

// though this needs the 0x prefix so it knows it is hex
unsigned int x = lexical_cast<unsigned int>("0xdeadbeef"); 

jQuery disable a link

Here is an alternate css/jQuery solution that I prefer for its terseness and minimized scripting:

css:

a.disabled {
  opacity: 0.5;
  pointer-events: none;
  cursor: default;
}

jQuery:

$('.disableAfterClick').click(function (e) {
   $(this).addClass('disabled');
});

How can I extract substrings from a string in Perl?

Long time no Perl

while(<STDIN>) {
    next unless /:\s*(\S+)\s+\(([^\)]+)\)\s*(\*?)/;
    print "|$1|$2|$3|\n";
}

Dynamic SELECT TOP @var In SQL Server

SELECT TOP (@count) * FROM SomeTable

This will only work with SQL 2005+

UITextField border color

this question shows up pretty high on a Google search and worked for the most part! I did find that Salman Zaidi's answer was partially correct for iOS 7.

You need to make a modification to the "reverting" code. I found that the following for reverting worked perfectly:

textField.layer.cornerRadius = 0.0f;
textField.layer.masksToBounds = YES;
textField.layer.borderColor = [[UIColor blackColor] CGColor];
textField.layer.borderWidth = 0.0f;

I understand that this is most likely due to changes in iOS 7.

How to avoid warning when introducing NAs by coercion

Use suppressWarnings():

suppressWarnings(as.numeric(c("1", "2", "X")))
[1]  1  2 NA

This suppresses warnings.

Adding a column after another column within SQL

It depends on what database you are using. In MySQL, you would use the "ALTER TABLE" syntax. I don't remember exactly how, but it would go something like this if you wanted to add a column called 'newcol' that was a 200 character varchar:

ALTER TABLE example ADD newCol VARCHAR(200) AFTER otherCol;

1052: Column 'id' in field list is ambiguous

You would do that by providing a fully qualified name, e.g.:

SELECT tbl_names.id as id, name, section FROM tbl_names, tbl_section WHERE tbl_names.id = tbl_section.id

Which would give you the id of tbl_names

Call a url from javascript

Yes, what you are asking for is called AJAX or XMLHttpRequest. You can either use a library like jQuery to simplify making the call (due to cross-browser compatibility issues), or write your own handler.

In jQuery:

$.GET('url.asp', {data: 'here'}, function(data){ /* what to do with the data returned */ })

In plain vanilla javaScript (from w3c):

var xmlhttp;
function loadXMLDoc(url)
{
    xmlhttp=null;
if (window.XMLHttpRequest)
  {// code for all new browsers
      xmlhttp=new XMLHttpRequest();
  }
else if (window.ActiveXObject)
  {// code for IE5 and IE6
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
if (xmlhttp!=null)
  {
      xmlhttp.onreadystatechange=state_Change;
      xmlhttp.open("GET",url,true);
      xmlhttp.send(null);
  }
else
  {
      alert("Your browser does not support XMLHTTP.");
  }
}

function state_Change()
{
    if (xmlhttp.readyState==4)
      {// 4 = "loaded"
          if (xmlhttp.status==200)
            {// 200 = OK
             //xmlhttp.data and shtuff
            // ...our code here...
        }
  else
        {
            alert("Problem retrieving data");
        }
  }
}

Remove trailing spaces automatically or with a shortcut

You can enable whitespace trimming at file save time from settings:

  1. Open Visual Studio Code User Settings (menu FilePreferencesSettingsUser Settings tab).
  2. Click the enter image description here icon in the top-right part of the window. This will open a document.
  3. Add a new "files.trimTrailingWhitespace": true setting to the User Settings document if it's not already there. This is so you aren't editing the Default Setting directly, but instead adding to it.
  4. Save the User Settings file.

We also added a new command to trigger this manually (Trim Trailing Whitespace from the command palette).

Custom Adapter for List View

Google has an example called EfficientAdapter, which in my opinion is the best simple example of how to implement custom adapters. http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/view/List14.html @CommonsWare has written a good explanation of the patterns used in the above example http://commonsware.com/Android/excerpt.pdf

How to customize message box

You can't restyle the default MessageBox as that's dependant on the current Windows OS theme, however you can easily create your own MessageBox. Just add a new form (i.e. MyNewMessageBox) to your project with these settings:

FormBorderStyle    FixedToolWindow
ShowInTaskBar      False
StartPosition      CenterScreen

To show it use myNewMessageBoxInstance.ShowDialog();. And add a label and buttons to your form, such as OK and Cancel and set their DialogResults appropriately, i.e. add a button to MyNewMessageBox and call it btnOK. Set the DialogResult property in the property window to DialogResult.OK. When that button is pressed it would return the OK result:

MyNewMessageBox myNewMessageBoxInstance = new MyNewMessageBox();
DialogResult result = myNewMessageBoxInstance.ShowDialog();
if (result == DialogResult.OK)
{
    // etc
}

It would be advisable to add your own Show method that takes the text and other options you require:

public DialogResult Show(string text, Color foreColour)
{
     lblText.Text = text;
     lblText.ForeColor = foreColour;
     return this.ShowDialog();
}

SQL Server Profiler - How to filter trace to only display events from one database?

Under Trace properties > Events Selection tab > select show all columns. Now under column filters, you should see the database name. Enter the database name for the Like section and you should see traces only for that database.

`node-pre-gyp install --fallback-to-build` failed during MeanJS installation on OSX

This might not work for everyone, but I updated node and it fixed the issue for me when none of the above did

Output grep results to text file, need cleaner output

grep -n "YOUR SEARCH STRING" * > output-file

The -n will print the line number and the > will redirect grep-results to the output-file.
If you want to "clean" the results you can filter them using pipe | for example:
grep -n "test" * | grep -v "mytest" > output-file will match all the lines that have the string "test" except the lines that match the string "mytest" (that's the switch -v) - and will redirect the result to an output file.
A few good grep-tips can be found on this post

Function inside a function.?

function inside a function or so called nested functions are very usable if you need to do some recursion processes such as looping true multiple layer of array or a file tree without multiple loops or sometimes i use it to avoid creating classes for small jobs which require dividing and isolating functionality among multiple functions. but before you go for nested functions you have to understand that

  1. child function will not be available unless the main function is executed
  2. Once main function got executed the child functions will be globally available to access
  3. if you need to call the main function twice it will try to re define the child function and this will throw a fatal error

so is this mean you cant use nested functions? No, you can with the below workarounds

first method is to block the child function being re declaring into global function stack by using conditional block with function exists, this will prevent the function being declared multiple times into global function stack.

function myfunc($a,$b=5){
    if(!function_exists("child")){
        function child($x,$c){
            return $c+$x;   
        }
    }
    
    try{
        return child($a,$b);
    }catch(Exception $e){
        throw $e;
    }
    
}

//once you have invoke the main function you will be able to call the child function
echo myfunc(10,20)+child(10,10);

and the second method will be limiting the function scope of child to local instead of global, to do that you have to define the function as a Anonymous function and assign it to a local variable, then the function will only be available in local scope and will re declared and invokes every time you call the main function.

function myfunc($a,$b=5){
    $child = function ($x,$c){
        return $c+$x;   
    };
    
    try{
        return $child($a,$b);
    }catch(Exception $e){
        throw $e;
    }
    
}

echo myfunc(10,20);

remember the child will not be available outside the main function or global function stack

Format date as dd/MM/yyyy using pipes

If anyone looking with time and timezone, this is for you

 {{data.ct | date :'dd-MMM-yy h:mm:ss a '}}

add z for time zone at the end of date and time format

 {{data.ct | date :'dd-MMM-yy h:mm:ss a z'}}

JavaScript Number Split into individual digits

I might be wrong, but a solution picking up bits and pieces. Perhaps, as I still learning, is that the functions does many things in the same one. Do not hesitate to correct me, please.

const totalSum = (num) => [...num + ' '].map(Number).reduce((a, b) => a + b);

So we take the parameter and convert it to and arr, adding empty spaces. We do such operation in every single element and push it into a new array with the map method. Once splited, we use reduce to sum all the elements and get the total.

As I said, don't hesitate to correct me or improve the function if you see something that I don't.

Almost forgot, just in case:

const totalSum = (num) => ( num === 0 || num < 0) ? 'I need a positive number' : [...num + ' '].map(Number).reduce((a, b) => a + b);

If negatives numbers or just plain zero go down as parameters. Happy coding to us all.

How to check if dropdown is disabled?

I was searching for something like this, because I've got to check which of all my selects are disabled.

So I use this:

let select= $("select");

for (let i = 0; i < select.length; i++) {
    const element = select[i];
    if(element.disabled == true ){
        console.log(element)
    }
}

Why does Git say my master branch is "already up to date" even though it is not?

The top answer is much better in terms of breadth and depth of information given, but it seems like if you wanted your problem fixed almost immediately, and don't mind trodding on some of the basic principles of version control, you could ...

  1. Switch to master

    $ git checkout upstream master
    
  2. Delete your unwanted branch. (Note: it must be have the -D, instead of the normal -d flag because your branch is many commits ahead of the master.)

    $ git branch -d <branch_name>
    
  3. Create a new branch

    $ git checkout -b <new_branch_name>
    

Iterating each character in a string using Python

You can also do the following:

txt = "Hello World!"
print (*txt, sep='\n')

This does not use loops but internally print statement takes care of it.

* unpacks the string into a list and sends it to the print statement

sep='\n' will ensure that the next char is printed on a new line

The output will be:

H
e
l
l
o
 
W
o
r
l
d
!

If you do need a loop statement, then as others have mentioned, you can use a for loop like this:

for x in txt: print (x)

What does the construct x = x || y mean?

Whilst Cletus' answer is correct, I feel more detail should be added in regards to "evaluates to false" in JavaScript.

var title = title || 'Error';
var msg   = msg || 'Error on Request';

Is not just checking if title/msg has been provided, but also if either of them are falsy. i.e. one of the following:

  • false.
  • 0 (zero)
  • "" (empty string)
  • null.
  • undefined.
  • NaN (a special Number value meaning Not-a-Number!)

So in the line

var title = title || 'Error';

If title is truthy (i.e., not falsy, so title = "titleMessage" etc.) then the Boolean OR (||) operator has found one 'true' value, which means it evaluates to true, so it short-circuits and returns the true value (title).

If title is falsy (i.e. one of the list above), then the Boolean OR (||) operator has found a 'false' value, and now needs to evaluate the other part of the operator, 'Error', which evaluates to true, and is hence returned.

It would also seem (after some quick firebug console experimentation) if both sides of the operator evaluate to false, it returns the second 'falsy' operator.

i.e.

return ("" || undefined)

returns undefined, this is probably to allow you to use the behavior asked about in this question when trying to default title/message to "". i.e. after running

var foo = undefined
foo = foo || ""

foo would be set to ""

How do I set up Visual Studio Code to compile C++ code?

With an updated VS Code you can do it in the following manner:

  1. Hit (Ctrl+P) and type:

    ext install cpptools
    
  2. Open a folder (Ctrl+K & Ctrl+O) and create a new file inside the folder with the extension .cpp (ex: hello.cpp):

  3. Type in your code and hit save.

  4. Hit (Ctrl+Shift+P and type, Configure task runner and then select other at the bottom of the list.

  5. Create a batch file in the same folder with the name build.bat and include the following code to the body of the file:

    @echo off
    call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" x64     
    set compilerflags=/Od /Zi /EHsc
    set linkerflags=/OUT:hello.exe
    cl.exe %compilerflags% hello.cpp /link %linkerflags%
    
  6. Edit the task.json file as follows and save it:

    {
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "0.1.0",
    "command": "build.bat",
    "isShellCommand": true,
    //"args": ["Hello World"],
    "showOutput": "always"
    }
    
  7. Hit (Ctrl+Shift+B to run Build task. This will create the .obj and .exe files for the project.

  8. For debugging the project, Hit F5 and select C++(Windows).

  9. In launch.json file, edit the following line and save the file:

    "program": "${workspaceRoot}/hello.exe",
    
  10. Hit F5.

How do I print the content of a .txt file in Python?

with open("filename.txt", "w+") as file:
  for line in file:
    print line

This with statement automatically opens and closes it for you and you can iterate over the lines of the file with a simple for loop

How are echo and print different in PHP?

From: http://web.archive.org/web/20090221144611/http://faqts.com/knowledge_base/view.phtml/aid/1/fid/40

  1. Speed. There is a difference between the two, but speed-wise it should be irrelevant which one you use. echo is marginally faster since it doesn't set a return value if you really want to get down to the nitty gritty.

  2. Expression. print() behaves like a function in that you can do: $ret = print "Hello World"; And $ret will be 1. That means that print can be used as part of a more complex expression where echo cannot. An example from the PHP Manual:

$b ? print "true" : print "false";

print is also part of the precedence table which it needs to be if it is to be used within a complex expression. It is just about at the bottom of the precedence list though. Only , AND OR XOR are lower.

  1. Parameter(s). The grammar is: echo expression [, expression[, expression] ... ] But echo ( expression, expression ) is not valid. This would be valid: echo ("howdy"),("partner"); the same as: echo "howdy","partner"; (Putting the brackets in that simple example serves no purpose since there is no operator precedence issue with a single term like that.)

So, echo without parentheses can take multiple parameters, which get concatenated:

   echo  "and a ", 1, 2, 3;   // comma-separated without parentheses
   echo ("and a 123");        // just one parameter with parentheses

print() can only take one parameter:

   print ("and a 123");
   print  "and a 123";

Writing image to local server

A few things happening here:

  1. I assume you required fs/http, and set the dir variable :)
  2. google.com redirects to www.google.com, so you're saving the redirect response's body, not the image
  3. the response is streamed. that means the 'data' event fires many times, not once. you have to save and join all the chunks together to get the full response body
  4. since you're getting binary data, you have to set the encoding accordingly on response and writeFile (default is utf8)

This should work:

var http = require('http')
  , fs = require('fs')
  , options

options = {
    host: 'www.google.com'
  , port: 80
  , path: '/images/logos/ps_logo2.png'
}

var request = http.get(options, function(res){
    var imagedata = ''
    res.setEncoding('binary')

    res.on('data', function(chunk){
        imagedata += chunk
    })

    res.on('end', function(){
        fs.writeFile('logo.png', imagedata, 'binary', function(err){
            if (err) throw err
            console.log('File saved.')
        })
    })

})

TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable

I had the same issue caused by importing the internal version of 'takeUntil' instead of the operators Change

import { takeUntil } from 'rxjs/internal/operators/takeUntil';

to

import { takeUntil } from 'rxjs/operators';

This happen also for other operators

python: get directory two levels up

You can use this as a generic solution:

import os

def getParentDir(path, level=1):
  return os.path.normpath( os.path.join(path, *([".."] * level)) )

Android getResources().getDrawable() deprecated API 22

You can use

ContextCompat.getDrawable(getApplicationContext(),R.drawable.example);

that's work for me

WampServer orange icon

To add to the above post^^:

If either of the services are not running, it might simply just be because they need to be installed/configured. This is easy to do straight from the WampManager Icon.


If Apache is not running:

 WampManager Icon -> Apache -> Service -> Install Service

You should get a command prompt pop-up if port 80 is free (if not, see above post):

      'Your port 80 is available. Install will proceed.

       Press Enter to continue...'


If MySQL is not running:

WampManager Icon -> MySQL -> Service -> Install Service


Do that for one or both services then:

WampManager Icon -> Restart All Services

The icon should now turn green :)

How to uncommit my last commit in Git

Be careful, reset --hard will remove your local (uncommitted) modifications, too.

git reset --hard HEAD^

note: if you're on windows you'll need to quote the HEAD^ so

git reset --hard "HEAD^"

If you want to revert the commit WITHOUT throwing away work, use the --soft flag instead of --hard

How can I solve Exception in thread "main" java.lang.NullPointerException error

This is the problem

double a[] = null;

Since a is null, NullPointerException will arise every time you use it until you initialize it. So this:

a[i] = var;

will fail.

A possible solution would be initialize it when declaring it:

double a[] = new double[PUT_A_LENGTH_HERE]; //seems like this constant should be 7

IMO more important than solving this exception, is the fact that you should learn to read the stacktrace and understand what it says, so you could detect the problems and solve it.

java.lang.NullPointerException

This exception means there's a variable with null value being used. How to solve? Just make sure the variable is not null before being used.

at twoten.TwoTenB.(TwoTenB.java:29)

This line has two parts:

  • First, shows the class and method where the error was thrown. In this case, it was at <init> method in class TwoTenB declared in package twoten. When you encounter an error message with SomeClassName.<init>, means the error was thrown while creating a new instance of the class e.g. executing the constructor (in this case that seems to be the problem).
  • Secondly, shows the file and line number location where the error is thrown, which is between parenthesis. This way is easier to spot where the error arose. So you have to look into file TwoTenB.java, line number 29. This seems to be a[i] = var;.

From this line, other lines will be similar to tell you where the error arose. So when reading this:

at javapractice.JavaPractice.main(JavaPractice.java:32)

It means that you were trying to instantiate a TwoTenB object reference inside the main method of your class JavaPractice declared in javapractice package.

adding directory to sys.path /PYTHONPATH

Temporarily changing dirs works well for importing:

cwd = os.getcwd()
os.chdir(<module_path>)
import <module>
os.chdir(cwd)

How can I detect if a selector returns null?

My favourite is to extend jQuery with this tiny convenience:

$.fn.exists = function () {
    return this.length !== 0;
}

Used like:

$("#notAnElement").exists();

More explicit than using length.

Convert character to Date in R

The easiest way is to use lubridate:

library(lubridate)
prods.all$Date2 <- mdy(prods.all$Date2)

This function automatically returns objects of class POSIXct and will work with either factors or characters.

HTTP Error 503. The service is unavailable. App pool stops on accessing website

Most of Time, it was occured due to AppPool Setting.

Check the following to resolve this

  1. Check Apppool service is running.
  2. Check Identity of AppPool.
  3. Enter the new password if it has changed for that identity.

The following Images show these setting in IIS

enter image description here

Python variables as keys to dict

a = "something"
randround = {}
randround['A'] = "%s" % a

Worked.

How to getElementByClass instead of GetElementById with JavaScript?

My solution:

First create "<style>" tags with an ID.

<style id="YourID">
    .YourClass {background-color:red}
</style>

Then, I create a function in JavaScript like this:

document.getElementById('YourID').innerHTML = '.YourClass {background-color:blue}'

Worked like a charm for me.

How to make HTTP Post request with JSON body in Swift

import UIKit

class ViewController: UIViewController {

    var getdata = NSMutableData()
    @IBOutlet weak var password_txt: UITextField!
    @IBOutlet weak var mobile_txt: UITextField!
    @IBOutlet weak var email_txt: UITextField!
    @IBOutlet weak var name_txt: UITextField!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.

    }
    @IBAction func RegAction(_ sender: UIButton) {
        let url = URL(string: "https//.....")
        var requrl = URLRequest(url: url!)
        requrl.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "content_type")
        requrl.httpMethod = "post"
        let postString = "name=\(name_txt.text!)&email=\(email_txt.text!)&mobile=\(mobile_txt.text!)&password=\(password_txt.text!)"
        print("poststring-->>",postString)
        requrl.httpBody = postString.data(using: .utf8)
        let task = URLSession.shared.dataTask(with: requrl){(data,response,error) in
            let mydata = data
            do{
                print("mydata",mydata!)
                do{
                    self.getdata.append(mydata!)
                    let jsondata = try JSONSerialization.jsonObject(with: self.getdata as Data, options: [])
                    print("jsondata-->",jsondata)
                }
            }
            catch
            {
                print("error-->",error.localizedDescription)
            }
        };
        task.resume()

    }
}
`GET METHOD`
import UIKit

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
    var dataarray = [[String: Any]]()
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataarray.count
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 450.0
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
        let  item = dataarray[indexPath.row]

        cell.name_txt.text = item["name"]as? String ?? ""
        cell.pname_txt.text = item["realname"]as? String ?? ""
        cell.team_txt.text = item["team"]as? String ?? ""
        cell.firstapp_txt.text = item["firstappearance"]as? String ?? ""
        cell.Createdby_txt.text = item["createdby"]as? String ?? ""
        cell.Publisher_txt.text = item["publisher"]as? String ?? ""

        if item["imageurl"]as? String ?? "" != ""{
            let url = URL(string: item["imageurl"]as? String ?? "")
            if url != nil{
                let data = try? Data(contentsOf: url!) //make sure your image in this url does exist, otherwise unwrap in a if let check / try-catch
                cell.imgvw.image = UIImage(data: data!)
            }
        }
        return cell
     }


    @IBOutlet weak var apiTable: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    override func viewWillAppear(_ animated: Bool) {
        guard let url = URL(string: "https://www.simplifiedcoding.net/demos/marvel/")
            else {return}
        let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
            guard let dataResponse = data,
                error == nil else {
                    print(error?.localizedDescription ?? "Response Error")
                    return }
            do{
                //here dataResponse received from a network request
                let jsonResponse = try JSONSerialization.jsonObject(with:
                    dataResponse, options: []) as? [[String:Any]] ?? [[:]]
                print("jsonResponse---->",jsonResponse) //Response result

                self.dataarray = jsonResponse
                DispatchQueue.main.async {



                    self.apiTable.reloadData()
                }
            } catch let parsingError {
                print("Error", parsingError)
            }
        }
        task.resume()
    }

}

Including .cpp files

There are many reasons to discourage including a .cpp file, but it isn't strictly disallowed. Your example should compile fine.

The problem is probably that you're compiling both main.cpp and foop.cpp, which means two copies of foop.cpp are being linked together. The linker is complaining about the duplication.

How to do a GitHub pull request

In order to make a pull request you need to do the following steps:

  1. Fork a repository (to which you want to make a pull request). Just click the fork button the the repository page and you will have a separate github repository preceded with your github username.
  2. Clone the repository to your local machine. The Github software that you installed on your local machine can do this for you. Click the clone button beside the repository name.
  3. Make local changes/commits to the files
  4. sync the changes
  5. go to your github forked repository and click the "Compare & Review" green button besides the branch button. (The button has icon - no text)
  6. A new page will open showing your changes and then click the pull request link, that will send the request to the original owner of the repository you forked.

It took me a while to figure this, hope this will help someone.

IIS error, Unable to start debugging on the webserver

If you are using active directory login u need to check password and username.

How to make bootstrap column height to 100% row height?

You can solve that using display table.

Here is the updated JSFiddle that solves your problem.

CSS

.body {
    display: table;
    background-color: green;
}

.left-side {
    background-color: blue;
    float: none;
    display: table-cell;
    border: 1px solid;
}

.right-side {
    background-color: red;
    float: none;
    display: table-cell;
    border: 1px solid;
}

HTML

<div class="row body">
        <div class="col-xs-9 left-side">
            <p>sdfsdf</p>
            <p>sdfsdf</p>
            <p>sdfsdf</p>
            <p>sdfsdf</p>
            <p>sdfsdf</p>
            <p>sdfsdf</p>
        </div>
        <div class="col-xs-3 right-side">
            asdfdf
        </div>
    </div>

NameError: name 'self' is not defined

If you have arrived here via google, please make sure to check that you have given self as the first parameter to a class function. Especially if you try to reference values for that object instance inside the class function.

def foo():
    print(self.bar)

>NameError: name 'self' is not defined

def foo(self):
    print(self.bar)

Google Maps API warning: NoApiKeys

Google maps requires an API key for new projects since june 2016. For more information take a look at the Google Developers Blog. Also more information in german you'll find at this blog post from the clickstorm Blog.

Java Look and Feel (L&F)

You can also use JTattoo (http://www.jtattoo.net/), it has a couple of cool themes that can be used.

Just download the jar and import it into your classpath, or add it as a maven dependency:

<dependency>
        <groupId>com.jtattoo</groupId>
        <artifactId>JTattoo</artifactId>
        <version>1.6.11</version>
</dependency>

Here is a list of some of the cool themes they have available:

  • com.jtattoo.plaf.acryl.AcrylLookAndFeel
  • com.jtattoo.plaf.aero.AeroLookAndFeel
  • com.jtattoo.plaf.aluminium.AluminiumLookAndFeel
  • com.jtattoo.plaf.bernstein.BernsteinLookAndFeel
  • com.jtattoo.plaf.fast.FastLookAndFeel
  • com.jtattoo.plaf.graphite.GraphiteLookAndFeel
  • com.jtattoo.plaf.hifi.HiFiLookAndFeel
  • com.jtattoo.plaf.luna.LunaLookAndFeel
  • com.jtattoo.plaf.mcwin.McWinLookAndFeel
  • com.jtattoo.plaf.mint.MintLookAndFeel
  • com.jtattoo.plaf.noire.NoireLookAndFeel
  • com.jtattoo.plaf.smart.SmartLookAndFeel
  • com.jtattoo.plaf.texture.TextureLookAndFeel
  • com.jtattoo.plaf.custom.flx.FLXLookAndFeel

Regards

Duplicate headers received from server

Double quotes around the filename in the header is the standard per MDN web docs. Omitting the quotes creates multiple opportunities for problems arising from characters in the filename.

How to set default font family in React Native?

Set in package.json

"rnpm": {
  "assets": [
     "./assets/fonts/"
  ]
}

And link react-native link

How to get last items of a list in Python?

The last 9 elements can be read from left to right using numlist[-9:], or from right to left using numlist[:-10:-1], as you want.

>>> a=range(17)
>>> print a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
>>> print a[-9:]
[8, 9, 10, 11, 12, 13, 14, 15, 16]
>>> print a[:-10:-1]
[16, 15, 14, 13, 12, 11, 10, 9, 8]

Using DISTINCT along with GROUP BY in SQL Server

Use DISTINCT to remove duplicate GROUPING SETS from the GROUP BY clause

In a completely silly example using GROUPING SETS() in general (or the special grouping sets ROLLUP() or CUBE() in particular), you could use DISTINCT in order to remove the duplicate values produced by the grouping sets again:

SELECT DISTINCT actors
FROM (VALUES('a'), ('a'), ('b'), ('b')) t(actors)
GROUP BY CUBE(actors, actors)

With DISTINCT:

actors
------
NULL
a
b

Without DISTINCT:

actors
------
a
b
NULL
a
b
a
b

But why, apart from making an academic point, would you do that?

Use DISTINCT to find unique aggregate function values

In a less far-fetched example, you might be interested in the DISTINCT aggregated values, such as, how many different duplicate numbers of actors are there?

SELECT DISTINCT COUNT(*)
FROM (VALUES('a'), ('a'), ('b'), ('b')) t(actors)
GROUP BY actors

Answer:

count
-----
2

Use DISTINCT to remove duplicates with more than one GROUP BY column

Another case, of course, is this one:

SELECT DISTINCT actors, COUNT(*)
FROM (VALUES('a', 1), ('a', 1), ('b', 1), ('b', 2)) t(actors, id)
GROUP BY actors, id

With DISTINCT:

actors  count
-------------
a       2
b       1

Without DISTINCT:

actors  count
-------------
a       2
b       1
b       1

For more details, I've written some blog posts, e.g. about GROUPING SETS and how they influence the GROUP BY operation, or about the logical order of SQL operations (as opposed to the lexical order of operations).

What is the purpose of the return statement?

Difference between "return" and "print" can also be found in the following example:

RETURN:

def bigger(a, b):
    if a > b:
        return a
    elif a <b:
        return b
    else:
        return a

The above code will give correct results for all inputs.

PRINT:

def bigger(a, b):
    if a > b:
        print a
    elif a <b:
        print b
    else:
        print a

NOTE: This will fail for many test cases.

ERROR:

----  

FAILURE: Test case input: 3, 8.

            Expected result: 8  

FAILURE: Test case input: 4, 3.

            Expected result: 4  

FAILURE: Test case input: 3, 3.

            Expected result: 3  

You passed 0 out of 3 test cases

Split String by delimiter position using oracle SQL

You want to use regexp_substr() for this. This should work for your example:

select regexp_substr(val, '[^/]+/[^/]+', 1, 1) as part1,
       regexp_substr(val, '[^/]+$', 1, 1) as part2
from (select 'F/P/O' as val from dual) t

Here, by the way, is the SQL Fiddle.

Oops. I missed the part of the question where it says the last delimiter. For that, we can use regex_replace() for the first part:

select regexp_replace(val, '/[^/]+$', '', 1, 1) as part1,
       regexp_substr(val, '[^/]+$', 1, 1) as part2
from (select 'F/P/O' as val from dual) t

And here is this corresponding SQL Fiddle.

How do I remove my IntelliJ license in 2019.3?

I think there are more solutions!

You can start the app, and here are 3 things you can do:

  1. If the app shows for the first time the "import settings" dialog and then the "create/open a project" dialog, you can click on Settings > Manage License... > Remove License, and that removes for all Jetbrains products*.
  2. If you open products like IntelliJ IDEA and have projects currently active (like the app open automatically the all IDE without prompt), then click on File > Close Project, and follow the first step.
  3. Inside any app of IntelliJ, click on Help > Register... > Remove license.

*In case you have a license for a pack of products. If not, you have to remove the license per product individually. Check the 3rd step.

Error: "an object reference is required for the non-static field, method or property..."

Change your signatures to private static bool siprimo(long a) and private static long volteado(long a) and see where that gets you.

Adding ID's to google map markers

Marker already has unique id

marker.__gm_id

How to safely call an async method in C# without await

This is called fire and forget, and there is an extension for that.

Consumes a task and doesn't do anything with it. Useful for fire-and-forget calls to async methods within async methods.

Install nuget package.

Use:

MyAsyncMethod().Forget();

Looking for simple Java in-memory cache

You can easily use imcache. A sample code is below.

void example(){
    Cache<Integer,Integer> cache = CacheBuilder.heapCache().
    cacheLoader(new CacheLoader<Integer, Integer>() {
        public Integer load(Integer key) {
            return null;
        }
    }).capacity(10000).build(); 
}

How do you use Intent.FLAG_ACTIVITY_CLEAR_TOP to clear the Activity Stack?

For this, I use FLAG_ACTIVITY_CLEAR_TOP flag for starting Intent
(without FLAG_ACTIVITY_NEW_TASK)

and launchMode = "singleTask" in manifest for launched activity.

Seems like it works as I need - activity does not restart and all other activities are closed.

Center image in div horizontally

Every solution posted here assumes that you know the dimensions of your img, which is not a common scenario. Also, planting the dimensions into the solution is painful.

Simply set:

/* for the img inside your div */
display: block;
margin-left: auto;
margin-right: auto;

or

/* for the img inside your div */
display: block;
margin: 0 auto;

That's all.

Note, that you'll also have to set an initial min-width for your outer div.

Get current date, given a timezone in PHP?

If you have access to PHP 5.3, the intl extension is very nice for doing things like this.

Here's an example from the manual:

$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
    'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
$fmt->format(0); //0 for current time/date

In your case, you can do:

$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
        'America/New_York');
 $fmt->format($datetime); //where $datetime may be a DateTime object, an integer representing a Unix timestamp value (seconds since epoch, UTC) or an array in the format output by localtime(). 

As you can set a Timezone such as America/New_York, this is much better than using a GMT or UTC offset, as this takes into account the day light savings periods as well.

Finaly, as the intl extension uses ICU data, which contains a lot of very useful features when it comes to creating your own date/time formats.

Differences between fork and exec

The use of fork and exec exemplifies the spirit of UNIX in that it provides a very simple way to start new processes.

The fork call basically makes a duplicate of the current process, identical in almost every way. Not everything is copied over (for example, resource limits in some implementations) but the idea is to create as close a copy as possible.

The new process (child) gets a different process ID (PID) and has the PID of the old process (parent) as its parent PID (PPID). Because the two processes are now running exactly the same code, they can tell which is which by the return code of fork - the child gets 0, the parent gets the PID of the child. This is all, of course, assuming the fork call works - if not, no child is created and the parent gets an error code.

The exec call is a way to basically replace the entire current process with a new program. It loads the program into the current process space and runs it from the entry point.

So, fork and exec are often used in sequence to get a new program running as a child of a current process. Shells typically do this whenever you try to run a program like find - the shell forks, then the child loads the find program into memory, setting up all command line arguments, standard I/O and so forth.

But they're not required to be used together. It's perfectly acceptable for a program to fork itself without execing if, for example, the program contains both parent and child code (you need to be careful what you do, each implementation may have restrictions). This was used quite a lot (and still is) for daemons which simply listen on a TCP port and fork a copy of themselves to process a specific request while the parent goes back to listening.

Similarly, programs that know they're finished and just want to run another program don't need to fork, exec and then wait for the child. They can just load the child directly into their process space.

Some UNIX implementations have an optimized fork which uses what they call copy-on-write. This is a trick to delay the copying of the process space in fork until the program attempts to change something in that space. This is useful for those programs using only fork and not exec in that they don't have to copy an entire process space.

If the exec is called following fork (and this is what happens mostly), that causes a write to the process space and it is then copied for the child process.

Note that there is a whole family of exec calls (execl, execle, execve and so on) but exec in context here means any of them.

The following diagram illustrates the typical fork/exec operation where the bash shell is used to list a directory with the ls command:

+--------+
| pid=7  |
| ppid=4 |
| bash   |
+--------+
    |
    | calls fork
    V
+--------+             +--------+
| pid=7  |    forks    | pid=22 |
| ppid=4 | ----------> | ppid=7 |
| bash   |             | bash   |
+--------+             +--------+
    |                      |
    | waits for pid 22     | calls exec to run ls
    |                      V
    |                  +--------+
    |                  | pid=22 |
    |                  | ppid=7 |
    |                  | ls     |
    V                  +--------+
+--------+                 |
| pid=7  |                 | exits
| ppid=4 | <---------------+
| bash   |
+--------+
    |
    | continues
    V

jQuery select element in parent window

I looked for a solution to this problem, and came across the present page. I implemented the above solution:

$("#testdiv",opener.document) //doesn't work

But it doesn't work. Maybe it did work in previous jQuery versions, but it doesn't seem to work now.

I found this working solution on another stackoverflow page: how to access parent window object using jquery?

From which I got this working solution:

window.opener.$("#testdiv") //This works.

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

if path.exists(Score_file):
      try : 
         with open(Score_file , "rb") as prev_Scr:

            return Unpickler(prev_Scr).load()

    except EOFError : 

        return dict() 

How do I reset a sequence in Oracle?

You can use the CYCLE option, shown below:

CREATE SEQUENCE test_seq
MINVALUE 0
MAXVALUE 100
START WITH 0
INCREMENT BY 1
CYCLE;

In this case, when the sequence reaches MAXVALUE (100), it will recycle to the MINVALUE (0).

In the case of a decremented sequence, the sequence would recycle to the MAXVALUE.

Check if Variable is Empty - Angular 2

Lets say we have a variable called x, as below:

var x;

following statement is valid,

x = 10;
x = "a";
x = 0;
x = undefined;
x = null;

1. Number:

x = 10;
if(x){
//True
}

and for x = undefined or x = 0 (be careful here)

if(x){
 //False
}

2. String x = null , x = undefined or x = ""

if(x){
  //False
}

3 Boolean x = false and x = undefined,

if(x){
  //False
}

By keeping above in mind we can easily check, whether variable is empty, null, 0 or undefined in Angular js. Angular js doest provide separate API to check variable values emptiness.

Accessing elements of Python dictionary by index

Given that it is a dictionary you access it by using the keys. Getting the dictionary stored under "Apple", do the following:

>>> mydict["Apple"]
{'American': '16', 'Mexican': 10, 'Chinese': 5}

And getting how many of them are American (16), do like this:

>>> mydict["Apple"]["American"]
'16'

Is it possible to set a custom font for entire of application?

Tom's solution works great, but only works with TextView and EditText.

If you want to cover most of the views (RadioGroup, TextView, Checkbox...), I created a method doing that :

protected void changeChildrenFont(ViewGroup v, Typeface font){
    for(int i = 0; i < v.getChildCount(); i++){

        // For the ViewGroup, we'll have to use recursivity
        if(v.getChildAt(i) instanceof ViewGroup){
            changeChildrenFont((ViewGroup) v.getChildAt(i), font);
        }
        else{
            try {
                Object[] nullArgs = null;
                //Test wether setTypeface and getTypeface methods exists
                Method methodTypeFace = v.getChildAt(i).getClass().getMethod("setTypeface", new Class[] {Typeface.class, Integer.TYPE});
                //With getTypefaca we'll get back the style (Bold, Italic...) set in XML
                Method methodGetTypeFace = v.getChildAt(i).getClass().getMethod("getTypeface", new Class[] {});
                Typeface typeFace = ((Typeface)methodGetTypeFace.invoke(v.getChildAt(i), nullArgs));
                //Invoke the method and apply the new font with the defined style to the view if the method exists (textview,...)
                methodTypeFace.invoke(v.getChildAt(i), new Object[] {font, typeFace == null ? 0 : typeFace.getStyle()});
            }
            //Will catch the view with no such methods (listview...)
            catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

This method will get back the style of the view set in XML (bold, italic...) and apply them if they exists.

For the ListView, I always create an adapter, and I set the font inside getView.

Deserialize JSON with Jackson into Polymorphic Types - A Complete Example is giving me a compile error

If using the fasterxml then,

these changes might be needed

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.node.ObjectNode;

in main method--

use

SimpleModule module =
  new SimpleModule("PolymorphicAnimalDeserializerModule");

instead of

new SimpleModule("PolymorphicAnimalDeserializerModule",
      new Version(1, 0, 0, null));

and in Animal deserialize() function, make below changes

//Iterator<Entry<String, JsonNode>> elementsIterator =  root.getFields();
Iterator<Entry<String, JsonNode>> elementsIterator = root.fields();

//return mapper.readValue(root, animalClass);
return  mapper.convertValue(root, animalClass); 

This works for fasterxml.jackson. If it still complains of the class fields. Use the same format as in the json for the field names (with "_" -underscore). as this
//mapper.setPropertyNamingStrategy(new CamelCaseNamingStrategy()); might not be supported.

abstract class Animal
{
  public String name;
}

class Dog extends Animal
{
  public String breed;
  public String leash_color;
}

class Cat extends Animal
{
  public String favorite_toy;
}

class Bird extends Animal
{
  public String wing_span;
  public String preferred_food;
}

using awk with column value conditions

Depending on the AWK implementation are you using == is ok or not.

Have you tried ~?. For example, if you want $1 to be "hello":

awk '$1 ~ /^hello$/{ print $3; }' <infile>

^ means $1 start, and $ is $1 end.

setting request headers in selenium

With the solutions already discussed above the most reliable one is using Browsermob-Proxy

But while working with the remote grid machine, Browsermob-proxy isn't really helpful.

This is how I fixed the problem in my case. Hopefully, might be helpful for anyone with a similar setup.

  1. Add the ModHeader extension to the chrome browser

How to download the Modheader? Link

ChromeOptions options = new ChromeOptions();
options.addExtensions(new File(C://Downloads//modheader//modheader.crx));

// Set the Desired capabilities 
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(ChromeOptions.CAPABILITY, options);

// Instantiate the chrome driver with capabilities
WebDriver driver = new RemoteWebDriver(new URL(YOUR_HUB_URL), options);
  1. Go to the browser extensions and capture the Local Storage context ID of the ModHeader

Capture ID from ModHeader

  1. Navigate to the URL of the ModHeader to set the Local Storage Context

.

// set the context on the extension so the localStorage can be accessed
driver.get("chrome-extension://idgpnmonknjnojddfkpgkljpfnnfcklj/_generated_background_page.html");

Where `idgpnmonknjnojddfkpgkljpfnnfcklj` is the value captured from the Step# 2
  1. Now add the headers to the request using Javascript

.

   ((Javascript)driver).executeScript(
         "localStorage.setItem('profiles', JSON.stringify([{  title: 'Selenium', hideComment: true, appendMode: '', 
             headers: [                        
               {enabled: true, name: 'token-1', value: 'value-1', comment: ''},
               {enabled: true, name: 'token-2', value: 'value-2', comment: ''}
             ],                          
             respHeaders: [],
             filters: []
          }]));");

Where token-1, value-1, token-2, value-2 are the request headers and values that are to be added.

  1. Now navigate to the required web-application.

    driver.get("your-desired-website");

bash: pip: command not found

The problem seems that your python version and the library yoiu want to install is not matching versionally. Ex: If Django is Django3 and your python version is 2.7, you may get this error.

"After installing is running 'python' still ran Python 2.6 and PATH was not updated."

1- Install latest version of Python 2- Change your PATH manually as python38 and compare them. 3- Try to reinstall.

I solved this problem as replacing PATH manually with the latest version of Python. As for Windows: ;C:\python38\Scripts

How to increment a pointer address and pointer's value?

The following is an instantiation of the various "just print it" suggestions. I found it instructive.

#include "stdio.h"

int main() {
    static int x = 5;
    static int *p = &x;
    printf("(int) p   => %d\n",(int) p);
    printf("(int) p++ => %d\n",(int) p++);
    x = 5; p = &x;
    printf("(int) ++p => %d\n",(int) ++p);
    x = 5; p = &x;
    printf("++*p      => %d\n",++*p);
    x = 5; p = &x;
    printf("++(*p)    => %d\n",++(*p));
    x = 5; p = &x;
    printf("++*(p)    => %d\n",++*(p));
    x = 5; p = &x;
    printf("*p++      => %d\n",*p++);
    x = 5; p = &x;
    printf("(*p)++    => %d\n",(*p)++);
    x = 5; p = &x;
    printf("*(p)++    => %d\n",*(p)++);
    x = 5; p = &x;
    printf("*++p      => %d\n",*++p);
    x = 5; p = &x;
    printf("*(++p)    => %d\n",*(++p));
    return 0;
}

It returns

(int) p   => 256688152
(int) p++ => 256688152
(int) ++p => 256688156
++*p      => 6
++(*p)    => 6
++*(p)    => 6
*p++      => 5
(*p)++    => 5
*(p)++    => 5
*++p      => 0
*(++p)    => 0

I cast the pointer addresses to ints so they could be easily compared.

I compiled it with GCC.

DLL References in Visual C++

You mention adding the additional include directory (C/C++|General) and additional lib dependency (Linker|Input), but have you also added the additional library directory (Linker|General)?

Including a sample error message might also help people answer the question since it's not even clear if the error is during compilation or linking.

Why check both isset() and !empty()

Empty just check is the refered variable/array has an value if you check the php doc(empty) you'll see this things are considered emtpy

* "" (an empty string)
* 0 (0 as an integer)
* "0" (0 as a string)
* NULL
* FALSE
* array() (an empty array)
* var $var; (a variable declared, but without a value in a class)

while isset check if the variable isset and not null which can also be found in the php doc(isset)

Dynamic WHERE clause in LINQ

A simple Approach can be if your Columns are of Simple Type like String

public static IEnumerable<MyObject> WhereQuery(IEnumerable<MyObject> source, string columnName, string propertyValue)
{
   return source.Where(m => { return m.GetType().GetProperty(columnName).GetValue(m, null).ToString().StartsWith(propertyValue); });
}

UTF-8, UTF-16, and UTF-32

I made some tests to compare database performance between UTF-8 and UTF-16 in MySQL.

Update Speeds

UTF-8

Enter image description here

UTF-16

Enter image description here

Insert Speeds

Enter image description here

Enter image description here

Delete Speeds

Enter image description here

Enter image description here

What does "connection reset by peer" mean?

This means that a TCP RST was received and the connection is now closed. This occurs when a packet is sent from your end of the connection but the other end does not recognize the connection; it will send back a packet with the RST bit set in order to forcibly close the connection.

This can happen if the other side crashes and then comes back up or if it calls close() on the socket while there is data from you in transit, and is an indication to you that some of the data that you previously sent may not have been received.

It is up to you whether that is an error; if the information you were sending was only for the benefit of the remote client then it may not matter that any final data may have been lost. However you should close the socket and free up any other resources associated with the connection.

Want to move a particular div to right

This will do the job:

_x000D_
_x000D_
<div style="position:absolute; right:0;">Hello world</div>
_x000D_
_x000D_
_x000D_

how to call a function from another function in Jquery

I assume you don't want to rebind the event, but call the handler.

You can use trigger() to trigger events:

$('#billing_state_id').trigger('change');

If your handler doesn't rely on the event context and you don't want to trigger other handlers for the event, you could also name the function:

function someFunction() {
    //do stuff
}

$(document).ready(function(){
    //Load City by State
    $('#billing_state_id').live('change', someFunction);   
    $('#click_me').live('click', function() {
       //do something
       someFunction();
    });
  });

Also note that live() is deprecated, on() is the new hotness.

pandas: multiple conditions while indexing data frame - unexpected behavior

As you can see, the AND operator drops every row in which at least one value equals -1. On the other hand, the OR operator requires both values to be equal to -1 to drop them.

That's right. Remember that you're writing the condition in terms of what you want to keep, not in terms of what you want to drop. For df1:

df1 = df[(df.a != -1) & (df.b != -1)]

You're saying "keep the rows in which df.a isn't -1 and df.b isn't -1", which is the same as dropping every row in which at least one value is -1.

For df2:

df2 = df[(df.a != -1) | (df.b != -1)]

You're saying "keep the rows in which either df.a or df.b is not -1", which is the same as dropping rows where both values are -1.

PS: chained access like df['a'][1] = -1 can get you into trouble. It's better to get into the habit of using .loc and .iloc.

Flexbox: center horizontally and vertically

1 - Set CSS on parent div to display: flex;

2 - Set CSS on parent div to flex-direction: column;
Note that this will make all content within that div line up top to bottom. This will work best if the parent div only contains the child and nothing else.

3 - Set CSS on parent div to justify-content: center;

Here is an example of what the CSS will look like:

_x000D_
_x000D_
.parentDivClass {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  justify-content: center;_x000D_
}
_x000D_
_x000D_
_x000D_

Number to String in a formula field

CSTR({number_field}, 0, '')

The second placeholder is for decimals.

The last placeholder is for thousands separator.

Use of min and max functions in C++

fmin and fmax are specifically for use with floating point numbers (hence the "f"). If you use it for ints, you may suffer performance or precision losses due to conversion, function call overhead, etc. depending on your compiler/platform.

std::min and std::max are template functions (defined in header <algorithm>) which work on any type with a less-than (<) operator, so they can operate on any data type that allows such a comparison. You can also provide your own comparison function if you don't want it to work off <.

This is safer since you have to explicitly convert arguments to match when they have different types. The compiler won't let you accidentally convert a 64-bit int into a 64-bit float, for example. This reason alone should make the templates your default choice. (Credit to Matthieu M & bk1e)

Even when used with floats the template may win in performance. A compiler always has the option of inlining calls to template functions since the source code is part of the compilation unit. Sometimes it's impossible to inline a call to a library function, on the other hand (shared libraries, absence of link-time optimization, etc.).

Edit a specific Line of a Text File in C#

When you create a StreamWriter it always create a file from scratch, you will have to create a third file and copy from target and replace what you need, and then replace the old one. But as I can see what you need is XML manipulation, you might want to use XmlDocument and modify your file using Xpath.

How do you set the EditText keyboard to only consist of numbers on Android?

<EditText
        android:id="@+id/editText3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:ems="10"
        android:inputType="number" />

I have tried every thing now try this one it shows other characters but you cant enter in the editText

edit.setRawInputType(Configuration.KEYBOARD_12KEY);

enter image description here

Command to get nth line of STDOUT

Is Perl easily available to you?

$ perl -n -e 'if ($. == 7) { print; exit(0); }'

Obviously substitute whatever number you want for 7.

How can I recover a lost commit in Git?

Another way to get to the deleted commit is with the git fsck command.

git fsck --lost-found

This will output something like at the last line:

dangling commit xyz

We can check that it is the same commit using reflog as suggested in other answers. Now we can do a git merge

git merge xyz

Note:
We cannot get the commit back with fsck if we have already run a git gc command which will remove the reference to the dangling commit.

Substitute multiple whitespace with single whitespace in Python

A simple possibility (if you'd rather avoid REs) is

' '.join(mystring.split())

The split and join perform the task you're explicitly asking about -- plus, they also do the extra one that you don't talk about but is seen in your example, removing trailing spaces;-).

CSS: fixed to bottom and centered

I have encased the 'problem div in another div' lets call this div the enclose div... make the enclose div in css have a width of 100% and postion fixed with a bottom of 0... then insert the problem div into the enclose div this is how it would look

#problem {margin-right:auto;margin-left:auto; /*what ever other styles*/}
#enclose {position:fixed;bottom:0px;width:100%;}

then in html...

<div id="enclose">
    <div id="problem">
    <!--this is where the text/markup would go-->
    </div>
</div>

There ya go!
-Hypertextie

SQL Server: Get data for only the past year

For some reason none of the results above worked for me.

This selects the last 365 days.

 SELECT ... From ... WHERE date BETWEEN CURDATE() - INTERVAL 1 YEAR AND CURDATE()

Copy multiple files in Python

import os
import shutil
os.chdir('C:\\') #Make sure you add your source and destination path below

dir_src = ("C:\\foooo\\")
dir_dst = ("C:\\toooo\\")

for filename in os.listdir(dir_src):
    if filename.endswith('.txt'):
        shutil.copy( dir_src + filename, dir_dst)
    print(filename)

MySQL: Insert record if not exists in table

INSERT doesn't allow WHERE in the syntax.

What you can do: create a UNIQUE INDEX on the field which should be unique (name), then use either:

  • normal INSERT (and handle the error if the name already exists)
  • INSERT IGNORE (which will fail silently cause a warning (instead of error) if name already exists)
  • INSERT ... ON DUPLICATE KEY UPDATE (which will execute the UPDATE at the end if name already exists, see documentation)

How to convert string to date to string in Swift iOS?

First, you need to convert your string to NSDate with its format. Then, you change the dateFormatter to your simple format and convert it back to a String.

Swift 3

let dateString = "Thu, 22 Oct 2015 07:45:17 +0000"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEE, dd MMM yyyy hh:mm:ss +zzzz"
dateFormatter.locale = Locale.init(identifier: "en_GB")

let dateObj = dateFormatter.date(from: dateString)

dateFormatter.dateFormat = "MM-dd-yyyy"
print("Dateobj: \(dateFormatter.string(from: dateObj!))")

The printed result is: Dateobj: 10-22-2015

XPath test if node value is number

The one I found very useful is the following:

<xsl:choose>
  <xsl:when test="not(number(myNode))">
      <!-- myNode is a not a number or empty(NaN) or zero -->      
  </xsl:when>
  <xsl:otherwise>
      <!-- myNode is a number (!= zero) -->        
  </xsl:otherwise>
</xsl:choose>

how to get right offset of an element? - jQuery

Brendon Crawford had the best answer here (in comment), so I'll move it to an answer until he does (and maybe expand a little).

var offset = $('#whatever').offset();

offset.right = $(window).width() - (offset.left + $('#whatever').outerWidth(true));
offset.bottom = $(window).height() - (offset.top + $('#whatever').outerHeight(true));

What are the differences between JSON and JSONP?

“JSONP is JSON with extra code” would be too easy for the real world. No, you gotta have little discrepancies. What’s the fun in programming if everything just works?

Turns out JSON is not a subset of JavaScript. If all you do is take a JSON object and wrap it in a function call, one day you will be bitten by strange syntax errors, like I was today.

How can I get the last character in a string?

Since in Javascript a string is a char array, you can access the last character by the length of the string.

var lastChar = myString[myString.length -1];

Best way to read a large file into a byte array in C#?

I'd say BinaryReader is fine, but can be refactored to this, instead of all those lines of code for getting the length of the buffer:

public byte[] FileToByteArray(string fileName)
{
    byte[] fileData = null;

    using (FileStream fs = File.OpenRead(fileName)) 
    { 
        using (BinaryReader binaryReader = new BinaryReader(fs))
        {
            fileData = binaryReader.ReadBytes((int)fs.Length); 
        }
    }
    return fileData;
}

Should be better than using .ReadAllBytes(), since I saw in the comments on the top response that includes .ReadAllBytes() that one of the commenters had problems with files > 600 MB, since a BinaryReader is meant for this sort of thing. Also, putting it in a using statement ensures the FileStream and BinaryReader are closed and disposed.

Get names of all keys in the collection

I know this question is 10 years old but there is no C# solution and this took me hours to figure out. I'm using the .NET driver and System.Linq to return a list of the keys.

var map = new BsonJavaScript("function() { for (var key in this) { emit(key, null); } }");
var reduce = new BsonJavaScript("function(key, stuff) { return null; }");
var options = new MapReduceOptions<BsonDocument, BsonDocument>();
var result = await collection.MapReduceAsync(map, reduce, options);
var list = result.ToEnumerable().Select(item => item["_id"].ToString());

send mail from linux terminal in one line

For Ubuntu users: First You need to install mailutils

sudo apt-get install mailutils

Setup an email server, if you are using gmail or smtp. follow this link. then use this command to send email.

echo "this is a test mail" | mail -s "Subject of mail" [email protected]

In case you are using gmail and still you are getting some authentication error then you need to change setting of gmail:

Turn on Access for less secure apps from here

In JavaScript can I make a "click" event fire programmatically for a file input element?

It works :

For security reasons on Firefox and Opera, you can't fire the click on file input, but you can simulate with MouseEvents :

<script>
click=function(element){
    if(element!=null){
        try {element.click();}
        catch(e) {
            var evt = document.createEvent("MouseEvents");
            evt.initMouseEvent("click",true,true,window,0,0,0,0,0,false,false,false,false,0,null);
            element.dispatchEvent(evt);
            }
        }
    };
</script>

<input type="button" value="upload" onclick="click(document.getElementById('inputFile'));"><input type="file" id="inputFile" style="display:none">

How to enable relation view in phpmyadmin

first select the table you you would like to make the relation with >> then go to operation , for each table there is difference operation setting, >> inside operation "storage engine" choose innoDB option

innoDB will allow you to view the "relation view" which will help you make the foreign key

enter image description here

Intersect Two Lists in C#

From performance point of view if two lists contain number of elements that differ significantly, you can try such approach (using conditional operator ?:):

1.First you need to declare a converter:

Converter<string, int> del = delegate(string s) { return Int32.Parse(s); };

2.Then you use a conditional operator:

var r = data1.Count > data2.Count ?
 data2.ConvertAll<int>(del).Intersect(data1) :
 data1.Select(v => v.ToString()).Intersect(data2).ToList<string>().ConvertAll<int>(del);

You convert elements of shorter list to match the type of longer list. Imagine an execution speed if your first set contains 1000 elements and second only 10 (or opposite as it doesn't matter) ;-)

As you want to have a result as List, in a last line you convert the result (only result) back to int.

CSS file not refreshing in browser

I had this issue, I was scratching my head for the best part of two days.

Turns out I completely forgot I had CloudFlare setup on the domain I was live testing on.

CloudFlare caches your JavaScript and CSS. Turned on development mode and BAM!

Seriously... two whole days.

Joining pairs of elements of a list

just to be pythonic :-)

>>> x = ['a1sd','23df','aaa','ccc','rrrr', 'ssss', 'e', '']
>>> [x[i] + x[i+1] for i in range(0,len(x),2)]
['a1sd23df', 'aaaccc', 'rrrrssss', 'e']

in case the you want to be alarmed if the list length is odd you can try:

[x[i] + x[i+1] if not len(x) %2 else 'odd index' for i in range(0,len(x),2)]

Best of Luck

python pandas: Remove duplicates by columns A, keeping the row with the highest value in column B

Easiest way to do this:

# First you need to sort this DF as Column A as ascending and column B as descending 
# Then you can drop the duplicate values in A column 
# Optional - you can reset the index and get the nice data frame again
# I'm going to show you all in one step. 

d = {'A': [1,1,2,3,1,2,3,1], 'B': [30, 40,50,42,38,30,25,32]}
df = pd.DataFrame(data=d)
df

    A   B
0   1   30
1   1   40
2   2   50
3   3   42
4   1   38
5   2   30
6   3   25
7   1   32


df = df.sort_values(['A','B'], ascending =[True,False]).drop_duplicates(['A']).reset_index(drop=True)

df

    A   B
0   1   40
1   2   50
2   3   42

Best practice for Django project working directory structure

Here is what I follow on My system.

  1. All Projects: There is a projects directory in my home folder i.e. ~/projects. All the projects rest inside it.

  2. Individual Project: I follow a standardized structure template used by many developers called django-skel for individual projects. It basically takes care of all your static file and media files and all.

  3. Virtual environment: I have a virtualenvs folder inside my home to store all virtual environments in the system i.e. ~/virtualenvs . This gives me flexibility that I know what all virtual environments I have and can look use easily

The above 3 are the main partitions of My working environment.

All the other parts you mentioned are mostly dependent on project to project basis (i.e. you might use different databases for different projects). So they should reside in their individual projects.

Copying data from one SQLite database to another

I needed to move data from a sql server compact database to sqlite, so using sql server 2008 you can right click on the table and select 'Script Table To' and then 'Data to Inserts'. Copy the insert statements remove the 'GO' statements and it executed successfully when applied to the sqlite database using the 'DB Browser for Sqlite' app.

What is your most productive shortcut with Vim?

<Ctrl> + W, V to split the screen vertically
<Ctrl> + W, W to shift between the windows

!python % [args] to run the script I am editing in this window

ZF in visual mode to fold arbitrary lines

How to access URL segment(s) in blade in Laravel 5?

An easy way to get the first or last segment, in case you are unsure of the path length.

$segments = request()->segments();
$last  = end($segments);
$first = reset($segments);

Can we have functions inside functions in C++?

Local classes have already been mentioned, but here is a way to let them appear even more as local functions, using an operator() overload and an anonymous class:

int main() {
    struct {
        unsigned int operator() (unsigned int val) const {
            return val<=1 ? 1 : val*(*this)(val-1);
        }
    } fac;

    std::cout << fac(5) << '\n';
}

I don't advise on using this, it's just a funny trick (can do, but imho shouldn't).


2014 Update:

With the rise of C++11 a while back, you can now have local functions whose syntax is a little reminiscient of JavaScript:

auto fac = [] (unsigned int val) {
    return val*42;
};

Getting request payload from POST request in Java servlet

Simple answer:
Use getReader() to read the body of the request

More info:
There are two methods for reading the data in the body:

  1. getReader() returns a BufferedReader that will allow you to read the body of the request.

  2. getInputStream() returns a ServletInputStream if you need to read binary data.

Note from the docs: "[Either method] may be called to read the body, not both."

How much overhead does SSL impose?

Assuming you don't count connection set-up (as you indicated in your update), it strongly depends on the cipher chosen. Network overhead (in terms of bandwidth) will be negligible. CPU overhead will be dominated by cryptography. On my mobile Core i5, I can encrypt around 250 MB per second with RC4 on a single core. (RC4 is what you should choose for maximum performance.) AES is slower, providing "only" around 50 MB/s. So, if you choose correct ciphers, you won't manage to keep a single current core busy with the crypto overhead even if you have a fully utilized 1 Gbit line. [Edit: RC4 should not be used because it is no longer secure. However, AES hardware support is now present in many CPUs, which makes AES encryption really fast on such platforms.]

Connection establishment, however, is different. Depending on the implementation (e.g. support for TLS false start), it will add round-trips, which can cause noticable delays. Additionally, expensive crypto takes place on the first connection establishment (above-mentioned CPU could only accept 14 connections per core per second if you foolishly used 4096-bit keys and 100 if you use 2048-bit keys). On subsequent connections, previous sessions are often reused, avoiding the expensive crypto.

So, to summarize:

Transfer on established connection:

  • Delay: nearly none
  • CPU: negligible
  • Bandwidth: negligible

First connection establishment:

  • Delay: additional round-trips
  • Bandwidth: several kilobytes (certificates)
  • CPU on client: medium
  • CPU on server: high

Subsequent connection establishments:

  • Delay: additional round-trip (not sure if one or multiple, may be implementation-dependant)
  • Bandwidth: negligible
  • CPU: nearly none

Force IE compatibility mode off using tags

As suggested in this answer to a related question, "edge" mode can be set in the Web.Config file. This will make it apply to all HTML returned from the application without the need to insert it into individual pages:

<configuration>
    <system.webServer>
        <httpProtocol>
            <customHeaders>
                <add name="X-UA-Compatible" value="IE=edge" />
            </customHeaders>
        </httpProtocol>
    </system.webServer>
</configuration>

This same step can also be accomplished by modifying the "HTTP Response Headers" using IIS Manager for the IIS server, entire website, or specific applications.

How to compare DateTime in C#?

Here's a typical simple example in the Unity milieu

using UnityEngine;

public class Launch : MonoBehaviour
{
    void Start()
    {
        Debug.Log("today " + System.DateTime.Now.ToString("MM/dd/yyyy"));

        // don't allow the app to be run after June 10th
        System.DateTime lastDay = new System.DateTime(2020, 6, 10);
        System.DateTime today = System.DateTime.Now;

        if (lastDay < today) {
            Debug.Log("quit the app");
            Application.Quit();
        }
        UnityEngine.SceneManagement.SceneManager.LoadScene("Welcome");
    }
}

Select elements by attribute

To select elements having a certain attribute, see the answers above.

To determine if a given jQuery element has a specific attribute I'm using a small plugin that returns true if the first element in ajQuery collection has this attribute:

/** hasAttr
 ** helper plugin returning boolean if the first element of the collection has a certain attribute
 **/
$.fn.hasAttr = function(attr) {
   return 0 < this.length
       && 'undefined' !== typeof attr
       && undefined !== attr
       && this[0].hasAttribute(attr)
}

How to wait until an element exists?

You can try this:

const wait_until_element_appear = setInterval(() => {
    if ($(element).length !== 0) {
        // some code
        clearInterval(wait_until_element_appear);
    }
}, 0);

This solution works very good for me

How to change string into QString?

If by string you mean std::string you can do it with this method:

QString QString::fromStdString(const std::string & str)

std::string str = "Hello world";
QString qstr = QString::fromStdString(str);

If by string you mean Ascii encoded const char * then you can use this method:

QString QString::fromAscii(const char * str, int size = -1)

const char* str = "Hello world";
QString qstr = QString::fromAscii(str);

If you have const char * encoded with system encoding that can be read with QTextCodec::codecForLocale() then you should use this method:

QString QString::fromLocal8Bit(const char * str, int size = -1)

const char* str = "zazólc gesla jazn";      // latin2 source file and system encoding
QString qstr = QString::fromLocal8Bit(str);

If you have const char * that's UTF8 encoded then you'll need to use this method:

QString QString::fromUtf8(const char * str, int size = -1)

const char* str = read_raw("hello.txt"); // assuming hello.txt is UTF8 encoded, and read_raw() reads bytes from file into memory and returns pointer to the first byte as const char*
QString qstr = QString::fromUtf8(str);

There's also method for const ushort * containing UTF16 encoded string:

QString QString::fromUtf16(const ushort * unicode, int size = -1)

const ushort* str = read_raw("hello.txt"); // assuming hello.txt is UTF16 encoded, and read_raw() reads bytes from file into memory and returns pointer to the first byte as const ushort*
QString qstr = QString::fromUtf16(str);

How do I get the list of keys in a Dictionary?

Marc Gravell's answer should work for you. myDictionary.Keys returns an object that implements ICollection<TKey>, IEnumerable<TKey> and their non-generic counterparts.

I just wanted to add that if you plan on accessing the value as well, you could loop through the dictionary like this (modified example):

Dictionary<string, int> data = new Dictionary<string, int>();
data.Add("abc", 123);
data.Add("def", 456);

foreach (KeyValuePair<string, int> item in data)
{
    Console.WriteLine(item.Key + ": " + item.Value);
}

How to convert CLOB to VARCHAR2 inside oracle pl/sql

Quote (read [here][1])-

When you use CAST to convert a CLOB value into a character datatype or a BLOB value into the RAW datatype, the database implicitly converts the LOB value to character or raw data and then explicitly casts the resulting value into the target datatype.

So, something like this should work-

report := CAST(report_clob AS VARCHAR2(100));

Or better yet use it as CAST(report_clob AS VARCHAR2(100)) where ever you are trying to use the BLOB as VARCHAR [1]: http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions016.htm

Perform an action in every sub-directory using Bash

Use find command.

In GNU find, you can use -execdir parameter:

find . -type d -execdir realpath "{}" ';'

or by using -exec parameter:

find . -type d -exec sh -c 'cd -P "$0" && pwd -P' {} \;

or with xargs command:

find . -type d -print0 | xargs -0 -L1 sh -c 'cd "$0" && pwd && echo Do stuff'

Or using for loop:

for d in */; { echo "$d"; }

For recursivity try extended globbing (**/) instead (enable by: shopt -s extglob).


For more examples, see: How to go to each directory and execute a command? at SO

Storing money in a decimal column - what precision and scale?

If you are looking for a one-size-fits-all, I'd suggest DECIMAL(19, 4) is a popular choice (a quick Google bears this out). I think this originates from the old VBA/Access/Jet Currency data type, being the first fixed point decimal type in the language; Decimal only came in 'version 1.0' style (i.e. not fully implemented) in VB6/VBA6/Jet 4.0.

The rule of thumb for storage of fixed point decimal values is to store at least one more decimal place than you actually require to allow for rounding. One of the reasons for mapping the old Currency type in the front end to DECIMAL(19, 4) type in the back end was that Currency exhibited bankers' rounding by nature, whereas DECIMAL(p, s) rounded by truncation.

An extra decimal place in storage for DECIMAL allows a custom rounding algorithm to be implemented rather than taking the vendor's default (and bankers' rounding is alarming, to say the least, for a designer expecting all values ending in .5 to round away from zero).

Yes, DECIMAL(24, 8) sounds like overkill to me. Most currencies are quoted to four or five decimal places. I know of situations where a decimal scale of 8 (or more) is required but this is where a 'normal' monetary amount (say four decimal places) has been pro rata'd, implying the decimal precision should be reduced accordingly (also consider a floating point type in such circumstances). And no one has that much money nowadays to require a decimal precision of 24 :)

However, rather than a one-size-fits-all approach, some research may be in order. Ask your designer or domain expert about accounting rules which may be applicable: GAAP, EU, etc. I vaguely recall some EU intra-state transfers with explicit rules for rounding to five decimal places, therefore using DECIMAL(p, 6) for storage. Accountants generally seem to favour four decimal places.


PS Avoid SQL Server's MONEY data type because it has serious issues with accuracy when rounding, among other considerations such as portability etc. See Aaron Bertrand's blog.


Microsoft and language designers chose banker's rounding because hardware designers chose it [citation?]. It is enshrined in the Institute of Electrical and Electronics Engineers (IEEE) standards, for example. And hardware designers chose it because mathematicians prefer it. See Wikipedia; to paraphrase: The 1906 edition of Probability and Theory of Errors called this 'the computer's rule' ("computers" meaning humans who perform computations).

Send attachments with PHP Mail()?

You can try using the following code:

    $filename = 'myfile';
    $path = 'your path goes here';
    $file = $path . "/" . $filename;

    $mailto = '[email protected]';
    $subject = 'Subject';
    $message = 'My message';

    $content = file_get_contents($file);
    $content = chunk_split(base64_encode($content));

    // a random hash will be necessary to send mixed content
    $separator = md5(time());

    // carriage return type (RFC)
    $eol = "\r\n";

    // main header (multipart mandatory)
    $headers = "From: name <[email protected]>" . $eol;
    $headers .= "MIME-Version: 1.0" . $eol;
    $headers .= "Content-Type: multipart/mixed; boundary=\"" . $separator . "\"" . $eol;
    $headers .= "Content-Transfer-Encoding: 7bit" . $eol;
    $headers .= "This is a MIME encoded message." . $eol;

    // message
    $body = "--" . $separator . $eol;
    $body .= "Content-Type: text/plain; charset=\"iso-8859-1\"" . $eol;
    $body .= "Content-Transfer-Encoding: 8bit" . $eol;
    $body .= $message . $eol;

    // attachment
    $body .= "--" . $separator . $eol;
    $body .= "Content-Type: application/octet-stream; name=\"" . $filename . "\"" . $eol;
    $body .= "Content-Transfer-Encoding: base64" . $eol;
    $body .= "Content-Disposition: attachment" . $eol;
    $body .= $content . $eol;
    $body .= "--" . $separator . "--";

    //SEND Mail
    if (mail($mailto, $subject, $body, $headers)) {
        echo "mail send ... OK"; // or use booleans here
    } else {
        echo "mail send ... ERROR!";
        print_r( error_get_last() );
    }

Edit 14-June-2018

for more readability in some of email provider use

$body .= $eol . $message . $eol . $eol; and $body .= $eol . $content . $eol . $eol;

Getting RSA private key from PEM BASE64 Encoded private key file

This is PKCS#1 format of a private key. Try this code. It doesn't use Bouncy Castle or other third-party crypto providers. Just java.security and sun.security for DER sequece parsing. Also it supports parsing of a private key in PKCS#8 format (PEM file that has a header "-----BEGIN PRIVATE KEY-----").

import sun.security.util.DerInputStream;
import sun.security.util.DerValue;

import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPrivateCrtKeySpec;
import java.util.Base64;

public static PrivateKey pemFileLoadPrivateKeyPkcs1OrPkcs8Encoded(File pemFileName) throws GeneralSecurityException, IOException {
        // PKCS#8 format
        final String PEM_PRIVATE_START = "-----BEGIN PRIVATE KEY-----";
        final String PEM_PRIVATE_END = "-----END PRIVATE KEY-----";

        // PKCS#1 format
        final String PEM_RSA_PRIVATE_START = "-----BEGIN RSA PRIVATE KEY-----";
        final String PEM_RSA_PRIVATE_END = "-----END RSA PRIVATE KEY-----";

        Path path = Paths.get(pemFileName.getAbsolutePath());

        String privateKeyPem = new String(Files.readAllBytes(path));

        if (privateKeyPem.indexOf(PEM_PRIVATE_START) != -1) { // PKCS#8 format
            privateKeyPem = privateKeyPem.replace(PEM_PRIVATE_START, "").replace(PEM_PRIVATE_END, "");
            privateKeyPem = privateKeyPem.replaceAll("\\s", "");

            byte[] pkcs8EncodedKey = Base64.getDecoder().decode(privateKeyPem);

            KeyFactory factory = KeyFactory.getInstance("RSA");
            return factory.generatePrivate(new PKCS8EncodedKeySpec(pkcs8EncodedKey));

        } else if (privateKeyPem.indexOf(PEM_RSA_PRIVATE_START) != -1) {  // PKCS#1 format

            privateKeyPem = privateKeyPem.replace(PEM_RSA_PRIVATE_START, "").replace(PEM_RSA_PRIVATE_END, "");
            privateKeyPem = privateKeyPem.replaceAll("\\s", "");

            DerInputStream derReader = new DerInputStream(Base64.getDecoder().decode(privateKeyPem));

            DerValue[] seq = derReader.getSequence(0);

            if (seq.length < 9) {
                throw new GeneralSecurityException("Could not parse a PKCS1 private key.");
            }

            // skip version seq[0];
            BigInteger modulus = seq[1].getBigInteger();
            BigInteger publicExp = seq[2].getBigInteger();
            BigInteger privateExp = seq[3].getBigInteger();
            BigInteger prime1 = seq[4].getBigInteger();
            BigInteger prime2 = seq[5].getBigInteger();
            BigInteger exp1 = seq[6].getBigInteger();
            BigInteger exp2 = seq[7].getBigInteger();
            BigInteger crtCoef = seq[8].getBigInteger();

            RSAPrivateCrtKeySpec keySpec = new RSAPrivateCrtKeySpec(modulus, publicExp, privateExp, prime1, prime2, exp1, exp2, crtCoef);

            KeyFactory factory = KeyFactory.getInstance("RSA");

            return factory.generatePrivate(keySpec);
        }

        throw new GeneralSecurityException("Not supported format of a private key");
    }

HTML Table width in percentage, table rows separated equally

Use the property table-layout:fixed; on the table to get equally spaced cells. If a column has a width set, then no matter what the content is, it will be the specified width. Columns without a width set will divide whatever room is left over among themselves.

<table style='table-layout:fixed;'>
    <tbody>
        <tr>
            <td>gobble de gook</td>
            <td>mibs</td>
        </tr>
    </tbody>
</table>

Just to throw it out there, you could also use <colgroup><col span='#' style='width:#%;'/></colgroup>, which doesn't require repetition of style per table data or giving the table an id to use in a style sheet. I think setting the widths on the first row is enough though.

Null check in VB

Change your Ands to AndAlsos

A standard And will test both expressions. If comp.Container is Nothing, then the second expression will raise a NullReferenceException because you're accessing a property on a null object.

AndAlso will short-circuit the logical evaluation. If comp.Container is Nothing, then the 2nd expression will not be evaluated.

How can I style the border and title bar of a window in WPF?

I found a more straight forward solution from @DK comment in this question, the solution is written by Alex and described here with source, To make customized window:

  1. download the sample project here
  2. edit the generic.xaml file to customize the layout.
  3. enjoy :).

How can I undo a mysql statement that I just executed?

You can stop a query which is being processed by this

Find the Id of the query process by => show processlist;

Then => kill id;

.NET Out Of Memory Exception - Used 1.3GB but have 16GB installed

There is no difference until you compile to same target architecture. I suppose you are compiling for 32 bit architecture in both cases.

It's worth mentioning that OutOfMemoryException can also be raised if you get 2GB of memory allocated by a single collection in CLR (say List<T>) on both architectures 32 and 64 bit.

To be able to benefit from memory goodness on 64 bit architecture, you have to compile your code targeting 64 bit architecture. After that, naturally, your binary will run only on 64 bit, but will benefit from possibility having more space available in RAM.

Why use the params keyword?

Might sound stupid, But Params doesn't allow multidimensional array. Whereas you can pass a multidimensional array to a function.

How to export SQL Server 2005 query to CSV

In management studio, set query options to output to file, and in options->query results set output to file to output using comma as delimiter.

Basic example of using .ajax() with JSONP?

<!DOCTYPE html>
<html>
<head>
<style>img{ height: 100px; float: left; }</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<title>An JSONP example </title>
</head>
<body>
<!-- DIV FOR SHOWING IMAGES -->
<div id="images">
</div>
<!-- SCRIPT FOR GETTING IMAGES FROM FLICKER.COM USING JSONP -->
<script>
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
{
  format: "json"
},
//RETURNED RESPONSE DATA IS LOOPED AND ONLY IMAGE IS APPENDED TO IMAGE DIV
function(data) {
  $.each(data.items, function(i,item){
  $("<img/>").attr("src", item.media.m).appendTo("#images");

 });
});</script>
</body>
</html> 

The above code helps in getting images from the Flicker API. This uses the GET method for getting images using JSONP. It can be found in detail in here

How do I change the select box arrow

Working with just one selector:

select {
    width: 268px;
    padding: 5px;
    font-size: 16px;
    line-height: 1;
    border: 0;
    border-radius: 5px;
    height: 34px;
    background: url(http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png) no-repeat right #ddd;
    -webkit-appearance: none;
    background-position-x: 244px;
}

fiddler

Remove Item from ArrayList

How about this? Just give it a thought-

import java.util.ArrayList;

class Solution
{
        public static void main (String[] args){

             ArrayList<String> List_Of_Array = new ArrayList<String>();
             List_Of_Array.add("A");
             List_Of_Array.add("B");
             List_Of_Array.add("C");
             List_Of_Array.add("D");
             List_Of_Array.add("E");
             List_Of_Array.add("F");
             List_Of_Array.add("G");
             List_Of_Array.add("H");

             int i[] = {1,3,5};

             for (int j = 0; j < i.length; j++) {
                 List_Of_Array.remove(i[j]-j);
             }

             System.out.println(List_Of_Array);

        }


}

And the output was-

[A, C, E, G, H]

Check if a string is html or not

A little bit of validation with:

/<(?=.*? .*?\/ ?>|br|hr|input|!--|wbr)[a-z]+.*?>|<([a-z]+).*?<\/\1>/i.test(htmlStringHere) 

This searches for empty tags (some predefined) and / terminated XHTML empty tags and validates as HTML because of the empty tag OR will capture the tag name and attempt to find it's closing tag somewhere in the string to validate as HTML.

Explained demo: http://regex101.com/r/cX0eP2

Update:

Complete validation with:

/<(br|basefont|hr|input|source|frame|param|area|meta|!--|col|link|option|base|img|wbr|!DOCTYPE).*?>|<(a|abbr|acronym|address|applet|article|aside|audio|b|bdi|bdo|big|blockquote|body|button|canvas|caption|center|cite|code|colgroup|command|datalist|dd|del|details|dfn|dialog|dir|div|dl|dt|em|embed|fieldset|figcaption|figure|font|footer|form|frameset|head|header|hgroup|h1|h2|h3|h4|h5|h6|html|i|iframe|ins|kbd|keygen|label|legend|li|map|mark|menu|meter|nav|noframes|noscript|object|ol|optgroup|output|p|pre|progress|q|rp|rt|ruby|s|samp|script|section|select|small|span|strike|strong|style|sub|summary|sup|table|tbody|td|textarea|tfoot|th|thead|time|title|tr|track|tt|u|ul|var|video).*?<\/\2>/i.test(htmlStringHere) 

This does proper validation as it contains ALL HTML tags, empty ones first followed by the rest which need a closing tag.

Explained demo here: http://regex101.com/r/pE1mT5

UnmodifiableMap (Java Collections) vs ImmutableMap (Google)

ImmutableMap does not accept null values whereas Collections.unmodifiableMap() does. In addition it will never change after construction, while UnmodifiableMap may. From the JavaDoc:

An immutable, hash-based Map with reliable user-specified iteration order. Does not permit null keys or values.

Unlike Collections.unmodifiableMap(java.util.Map), which is a view of a separate map which can still change, an instance of ImmutableMap contains its own data and will never change. ImmutableMap is convenient for public static final maps ("constant maps") and also lets you easily make a "defensive copy" of a map provided to your class by a caller.

Why is my locally-created script not allowed to run under the RemoteSigned execution policy?

Is the file being blocked? I had the same issue and was able to resolve it by right clicking the .PS1 file, Properties and choosing Unblock.

Eclipse gives “Java was started but returned exit code 13”

enter image description hereI got this fixed by doing the below steps,

  1. The eclipse finds the JAVA executables from 'C:\ProgramData\Oracle\Java\javapath'

    2.The folder structure will contain shortcuts to the below executables, i. java.exe
    ii. javaw.exe
    iii. javaws.exe 3.For me the executable paths were pointing to my (ProgramFiles(x84)) folder location

  2. I corrected it to Program Files path(64 bit) and the issue got resolved

Please find the screenshot for the same.

Spring Boot and how to configure connection details to MongoDB?

spring.data.mongodb.host and spring.data.mongodb.port are not supported if you’re using the Mongo 3.0 Java driver. In such cases, spring.data.mongodb.uri should be used to provide all of the configuration, like this:

spring.data.mongodb.uri=mongodb://user:[email protected]:12345

Disable building workspace process in Eclipse

Building workspace is about incremental build of any evolution detected in one of the opened projects in the currently used workspace.

You can also disable it through the menu "Project / Build automatically".

But I would recommend first to check:

  • if a Project Clean all / Build result in the same kind of long wait (after disabling this option)
  • if you have (this time with building automatically activated) some validation options you could disable to see if they have an influence on the global compilation time (Preferences / Validations, or Preferences / XML / ... if you have WTP installed)
  • if a fresh eclipse installation referencing the same workspace (see this eclipse.ini for more) results in the same issue (with building automatically activated)

Note that bug 329657 (open in 2011, in progress in 2014) is about interrupting a (too lengthy) build, instead of cancelling it:

There is an important difference between build interrupt and cancel.

  • When a build is cancelled, it typically handles this by discarding incremental build state and letting the next build be a full rebuild. This can be quite expensive in some projects.
    As a user I think I would rather wait for the 5 second incremental build to finish rather than cancel and result in a 30 second rebuild afterwards.

  • The idea with interrupt is that a builder could more efficiently handle interrupt by saving its intermediate state and resuming on the next invocation.
    In practice this is hard to implement so the most common boundary is when we check for interrupt before/after calling each builder in the chain.

 

How to give the background-image path in CSS?

Use the below.

background-image: url("././images/image.png");

This shall work.

Escape string Python for MySQL

{!a} applies ascii() and hence escapes non-ASCII characters like quotes and even emoticons. Here is an example

cursor.execute("UPDATE skcript set author='{!a}',Count='{:d}' where url='{!s}'".format(authors),leng,url))

Python3 docs

How to loop through file names returned by find?

based on other answers and comment of @phk, using fd #3:
(which still allows to use stdin inside the loop)

while IFS= read -r f <&3; do
    echo "$f"

done 3< <(find . -iname "*filename*")

WHERE IS NULL, IS NOT NULL or NO WHERE clause depending on SQL Server parameter value

Here is how you can solve this using a single WHERE clause:

WHERE (@myParm = value1 AND MyColumn IS NULL)
OR  (@myParm = value2 AND MyColumn IS NOT NULL)
OR  (@myParm = value3)

A naïve usage of the CASE statement does not work, by this I mean the following:

SELECT Field1, Field2 FROM MyTable
WHERE CASE @myParam
    WHEN value1 THEN MyColumn IS NULL
    WHEN value2 THEN MyColumn IS NOT NULL
    WHEN value3 THEN TRUE
END

It is possible to solve this using a case statement, see onedaywhen's answer

What is the idiomatic Go equivalent of C's ternary operator?

As pointed out (and hopefully unsurprisingly), using if+else is indeed the idiomatic way to do conditionals in Go.

In addition to the full blown var+if+else block of code, though, this spelling is also used often:

index := val
if val <= 0 {
    index = -val
}

and if you have a block of code that is repetitive enough, such as the equivalent of int value = a <= b ? a : b, you can create a function to hold it:

func min(a, b int) int {
    if a <= b {
        return a
    }
    return b
}

...

value := min(a, b)

The compiler will inline such simple functions, so it's fast, more clear, and shorter.

Check if string doesn't contain another string

Use this as your WHERE condition

WHERE CHARINDEX('Apples', column) = 0 

Collections.sort with multiple fields

Use Comparator interface with methods introduced in JDK1.8: comparing and thenComparing, or more concrete methods: comparingXXX and thenComparingXXX.

For example, if we wanna sort a list of persons by their id firstly, then age, then name:

            Comparator<Person> comparator = Comparator.comparingLong(Person::getId)
                    .thenComparingInt(Person::getAge)
                    .thenComparing(Person::getName);
            personList.sort(comparator);

MySQL dump by query

Combining much of above here is my real practical example, selecting records based on both meterid & timestamp. I have needed this command for years. Executes really quickly.

mysqldump -uuser -ppassword main_dbo trHourly --where="MeterID =5406 AND TIMESTAMP<'2014-10-13 05:00:00'" --no-create-info --skip-extended-insert | grep  '^INSERT' > 5406.sql

Python requests library how to pass Authorization header with single token

i founded here, its ok with me for linkedin: https://auth0.com/docs/flows/guides/auth-code/call-api-auth-code so my code with with linkedin login here:

ref = 'https://api.linkedin.com/v2/me'
headers = {"content-type": "application/json; charset=UTF-8",'Authorization':'Bearer {}'.format(access_token)}
Linkedin_user_info = requests.get(ref1, headers=headers).json()

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;

  }
}

Need to remove href values when printing in Chrome

I encountered a similar problem only with a nested img in my anchor:

<a href="some/link">
   <img src="some/src">
</a>

When I applied

@media print {
   a[href]:after {
      content: none !important;
   }
}

I lost my img and the entire anchor width for some reason, so instead I used:

@media print {
   a[href]:after {
      visibility: hidden;
   }
}

which worked perfectly.

Bonus tip: inspect print preview

How to create a shared library with cmake?

I'm trying to learn how to do this myself, and it seems you can install the library like this:

cmake_minimum_required(VERSION 2.4.0)

project(mycustomlib)

# Find source files
file(GLOB SOURCES src/*.cpp)

# Include header files
include_directories(include)

# Create shared library
add_library(${PROJECT_NAME} SHARED ${SOURCES})

# Install library
install(TARGETS ${PROJECT_NAME} DESTINATION lib/${PROJECT_NAME})

# Install library headers
file(GLOB HEADERS include/*.h)
install(FILES ${HEADERS} DESTINATION include/${PROJECT_NAME})

NGINX - No input file specified. - php Fast/CGI

This answers did not help me, my php adminer showed me "No input file specified" error anyway. But I knew I changed php-version before. So, I found the reason: it is not nginx, it is php.ini doc_root parameter! I found

doc_root =

in php.ini and changed it to

;doc_root =

After this patch my adminer work good.

PHP header(Location: ...): Force URL change in address bar

// Register user's name and ID

if ((!isset($_SESSION['name'])) && (!isset($_SESSION['user_id'])))  {
    $row = mysql_fetch_assoc($login_result);
    $_SESSION['name'] = $row['name'];
    $_SESSION['user_id'] = $row['user_id'];
}

header("Location: http://localhost:8080/meet2eat/index.php");

change to

// Register user's name and ID

if ((!isset($_SESSION['name'])) && (!isset($_SESSION['user_id'])))  {
    $row = mysql_fetch_assoc($login_result);
    $_SESSION['name'] = $row['name'];
    $_SESSION['user_id'] = $row['user_id'];
header("Location: http://localhost:8080/meet2eat/index.php");
}

how to get the ipaddress of a virtual box running on local machine

Login to virtual machine use below command to check ip address. (anyone will work)

  1. ifconfig
  2. ip addr show

If you used NAT for your virtual machine settings(your machine ip will be 10.0.2.15), then you have to use port forwarding to connect to machine. IP address will be 127.0.0.1

If you used bridged networking/Host only networking, then you will have separate Ip address. Use that IP address to connect virtual machine

C++ Convert string (or char*) to wstring (or wchar_t*)

use this code to convert your string to wstring

std::wstring string2wString(const std::string& s){
    int len;
    int slength = (int)s.length() + 1;
    len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0); 
    wchar_t* buf = new wchar_t[len];
    MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len);
    std::wstring r(buf);
    delete[] buf;
    return r;
}

int main(){
    std::wstring str="your string";
    std::wstring wStr=string2wString(str);
    return 0;
}

How can I scale an entire web page with CSS?

As Johannes says -- not enough rep to comment directly on his answer -- you can indeed do this as long as all elements' "dimensions are specified as a multiple of the font's size. Meaning, everything where you used %, em or ex units". Although I think % are based on containing element, not font-size.

And you wouldn't normally use these relative units for images, given they are composed of pixels, but there's a trick which makes this a lot more practical.

If you define body{font-size: 62.5%}; then 1em will be equivalent to 10px. As far as I know this works across all main browsers.

Then you can specify your (e.g.) 100px square images with width: 10em; height: 10em; and assuming Firefox's scaling is set to default, the images will be their natural size.

Make body{font-size: 125%}; and everything - including images - wil be double original size.

Get the decimal part from a double

var decPlaces = (int)(((decimal)number % 1) * 100);

This presumes your number only has two decimal places.

Check if an array item is set in JS

The most effective way:

if (array.indexOf(element) > -1) {
   alert('Bingooo')
}

W3Schools

What's the source of Error: getaddrinfo EAI_AGAIN?

I started getting this error (different stack trace though) after making a trivial update to my GraphQL API application that is operated inside a docker container. For whatever reason, the container was having difficulty resolving a back-end service being used by the API.

After poking around to see if some change had been made in the docker base image I was building from (node:13-alpine, incidentally), I decided to try the oldest computer science trick of rebooting... I stopped and started the docker container and all went back to normal.

Clearly, this isn't a meaningful solution to the underlying problem - I am merely posting this since it did clear up the issue for me without going too deep down rabbit holes.

WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()'

This is just a warning and it will probably be fixed before 2019 with plugin updates so don't worry about it. I would recommend you to use compatible versions of your plugins and gradle.

You can check your plugin version and gradle version here for better experience and performance.

https://developer.android.com/studio/releases/gradle-plugin

Try using the stable versions for a smooth and warning/error free code.