Programs & Examples On #Qmenubar

The QMenuBar class, part of the Qt framework, provides a horizontal menu bar.

Pass multiple arguments into std::thread

Had the same problem. I was passing a non-const reference of custom class and the constructor complained (some tuple template errors). Replaced the reference with pointer and it worked.

How to concatenate two layers in keras?

You can experiment with model.summary() (notice the concatenate_XX (Concatenate) layer size)

# merge samples, two input must be same shape
inp1 = Input(shape=(10,32))
inp2 = Input(shape=(10,32))
cc1 = concatenate([inp1, inp2],axis=0) # Merge data must same row column
output = Dense(30, activation='relu')(cc1)
model = Model(inputs=[inp1, inp2], outputs=output)
model.summary()

# merge row must same column size
inp1 = Input(shape=(20,10))
inp2 = Input(shape=(32,10))
cc1 = concatenate([inp1, inp2],axis=1)
output = Dense(30, activation='relu')(cc1)
model = Model(inputs=[inp1, inp2], outputs=output)
model.summary()

# merge column must same row size
inp1 = Input(shape=(10,20))
inp2 = Input(shape=(10,32))
cc1 = concatenate([inp1, inp2],axis=1)
output = Dense(30, activation='relu')(cc1)
model = Model(inputs=[inp1, inp2], outputs=output)
model.summary()

You can view notebook here for detail: https://nbviewer.jupyter.org/github/anhhh11/DeepLearning/blob/master/Concanate_two_layer_keras.ipynb

When do we need curly braces around shell variables?

The end of the variable name is usually signified by a space or newline. But what if we don't want a space or newline after printing the variable value? The curly braces tell the shell interpreter where the end of the variable name is.

Classic Example 1) - shell variable without trailing whitespace

TIME=10

# WRONG: no such variable called 'TIMEsecs'
echo "Time taken = $TIMEsecs"

# What we want is $TIME followed by "secs" with no whitespace between the two.
echo "Time taken = ${TIME}secs"

Example 2) Java classpath with versioned jars

# WRONG - no such variable LATESTVERSION_src
CLASSPATH=hibernate-$LATESTVERSION_src.zip:hibernate_$LATEST_VERSION.jar

# RIGHT
CLASSPATH=hibernate-${LATESTVERSION}_src.zip:hibernate_$LATEST_VERSION.jar

(Fred's answer already states this but his example is a bit too abstract)

Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state

The other answers in my case did not work. I had to restart windows before I could debug the application again.

Add php variable inside echo statement as href link address?

as simple as that: echo '<a href="'.$link_address.'">Link</a>';

How to change my Git username in terminal?

  1. EDIT: In addition to changing your name and email You may also need to change your credentials:
  • To change locally for just one repository, enter in terminal, from within the repository

    git config credential.username "new_username"
    
  • To change globally use

    git config --global credential.username "new_username"
    

    (EDIT EXPLAINED: If you don't change also the user.email and user.name, you will be able to push your changes, but they will be registered in git under the previous user)

  1. Next time you push, you will be asked to enter your password

    Password for 'https://<new_username>@github.com':

HTML5 Canvas Rotate Image

This is the simplest code to draw a rotated and scaled image:

function drawImage(ctx, image, x, y, w, h, degrees){
  ctx.save();
  ctx.translate(x+w/2, y+h/2);
  ctx.rotate(degrees*Math.PI/180.0);
  ctx.translate(-x-w/2, -y-h/2);
  ctx.drawImage(image, x, y, w, h);
  ctx.restore();
}

Given two directory trees, how can I find out which files differ by content?

Meld is also a great tool for comparing two directories:

meld dir1/ dir2/

Meld has many options for comparing files or directories. If two files differ, it's easy to enter file comparison mode and see the exact differences.

Bootstrap modal appearing under background

The easiest solution I found, that worked for all my cases, was an answer in a similar post:

Here it is:

.modal {
  background: rgba(0, 0, 0, 0.5); 
}
.modal-backdrop {
  display: none;
}

Basically, the original backdrop is not used. Instead you use the modal as the backdrop. The result is that it looks and behaves exactly as the original should've. It avoids all the issues with z-indexes (for me changing z-index to 0 solved the issue, but created a new problem with my nav menu being between the modal and backdrop) and is simple.

Credit goes to @Jevin O. Sewaruth for posting the original answer.

Sorting a tab delimited file

I wanted a solution for Gnu sort on Windows, but none of the above solutions worked for me on the command line.

Using Lloyd's clue, the following batch file (.bat) worked for me.

Type the tab character within the double quotes.

C:\>cat foo.bat

sort -k3 -t"    " tabfile.txt

Isn't the size of character in Java 2 bytes?

Java stores all it's "chars" internally as two bytes. However, when they become strings etc, the number of bytes will depend on your encoding.

Some characters (ASCII) are single byte, but many others are multi-byte.

Java supports Unicode, thus according to:

Java Character Docs

The max value supported is "\uFFFF" (hex FFFF, dec 65535), or 11111111 11111111 binary (two bytes).

Turning a Comma Separated string into individual rows

Nice to see that it have been solved in the 2016 version, but for all of those that is not on that, here are two generalized and simplified versions of the methods above.

The XML-method is shorter, but of course requires the string to allow for the xml-trick (no 'bad' chars.)

XML-Method:

create function dbo.splitString(@input Varchar(max), @Splitter VarChar(99)) returns table as
Return
    SELECT Split.a.value('.', 'VARCHAR(max)') AS Data FROM
    ( SELECT CAST ('<M>' + REPLACE(@input, @Splitter, '</M><M>') + '</M>' AS XML) AS Data 
    ) AS A CROSS APPLY Data.nodes ('/M') AS Split(a); 

Recursive method:

create function dbo.splitString(@input Varchar(max), @Splitter Varchar(99)) returns table as
Return
  with tmp (DataItem, ix) as
   ( select @input  , CHARINDEX('',@Input)  --Recu. start, ignored val to get the types right
     union all
     select Substring(@input, ix+1,ix2-ix-1), ix2
     from (Select *, CHARINDEX(@Splitter,@Input+@Splitter,ix+1) ix2 from tmp) x where ix2<>0
   ) select DataItem from tmp where ix<>0

Function in action

Create table TEST_X (A int, CSV Varchar(100));
Insert into test_x select 1, 'A,B';
Insert into test_x select 2, 'C,D';

Select A,data from TEST_X x cross apply dbo.splitString(x.CSV,',') Y;

Drop table TEST_X

XML-METHOD 2: Unicode Friendly (Addition courtesy of Max Hodges) create function dbo.splitString(@input nVarchar(max), @Splitter nVarchar(99)) returns table as Return SELECT Split.a.value('.', 'NVARCHAR(max)') AS Data FROM ( SELECT CAST ('<M>' + REPLACE(@input, @Splitter, '</M><M>') + '</M>' AS XML) AS Data ) AS A CROSS APPLY Data.nodes ('/M') AS Split(a);

How do I determine whether my calculation of pi is accurate?

Since I'm the current world record holder for the most digits of pi, I'll add my two cents:

Unless you're actually setting a new world record, the common practice is just to verify the computed digits against the known values. So that's simple enough.

In fact, I have a webpage that lists snippets of digits for the purpose of verifying computations against them: http://www.numberworld.org/digits/Pi/


But when you get into world-record territory, there's nothing to compare against.

Historically, the standard approach for verifying that computed digits are correct is to recompute the digits using a second algorithm. So if either computation goes bad, the digits at the end won't match.

This does typically more than double the amount of time needed (since the second algorithm is usually slower). But it's the only way to verify the computed digits once you've wandered into the uncharted territory of never-before-computed digits and a new world record.


Back in the days where supercomputers were setting the records, two different AGM algorithms were commonly used:

These are both O(N log(N)^2) algorithms that were fairly easy to implement.

However, nowadays, things are a bit different. In the last three world records, instead of performing two computations, we performed only one computation using the fastest known formula (Chudnovsky Formula):

Enter image description here

This algorithm is much harder to implement, but it is a lot faster than the AGM algorithms.

Then we verify the binary digits using the BBP formulas for digit extraction.

Enter image description here

This formula allows you to compute arbitrary binary digits without computing all the digits before it. So it is used to verify the last few computed binary digits. Therefore it is much faster than a full computation.

The advantage of this is:

  1. Only one expensive computation is needed.

The disadvantage is:

  1. An implementation of the Bailey–Borwein–Plouffe (BBP) formula is needed.
  2. An additional step is needed to verify the radix conversion from binary to decimal.

I've glossed over some details of why verifying the last few digits implies that all the digits are correct. But it is easy to see this since any computation error will propagate to the last digits.


Now this last step (verifying the conversion) is actually fairly important. One of the previous world record holders actually called us out on this because, initially, I didn't give a sufficient description of how it worked.

So I've pulled this snippet from my blog:

N = # of decimal digits desired
p = 64-bit prime number

Enter image description here

Compute A using base 10 arithmetic and B using binary arithmetic.

Enter image description here

If A = B, then with "extremely high probability", the conversion is correct.


For further reading, see my blog post Pi - 5 Trillion Digits.

How to get selected value from Dropdown list in JavaScript

Hope it's working for you

 function GetSelectedItem()
 {
     var index = document.getElementById(select1).selectedIndex;

     alert("value =" + document.getElementById(select1).value); // show selected value
     alert("text =" + document.getElementById(select1).options[index].text); // show selected text 
 }

python: iterate a specific range in a list

listOfStuff =([a,b], [c,d], [e,f], [f,g])

for item in listOfStuff[1:3]:
    print item

You have to iterate over a slice of your tuple. The 1 is the first element you need and 3 (actually 2+1) is the first element you don't need.

Elements in a list are numerated from 0:

listOfStuff =([a,b], [c,d], [e,f], [f,g])
               0      1      2      3

[1:3] takes elements 1 and 2.

Open Url in default web browser

A simpler way which eliminates checking if the app can open the url.

  loadInBrowser = () => {
    Linking.openURL(this.state.url).catch(err => console.error("Couldn't load page", err));
  };

Calling it with a button.

<Button title="Open in Browser" onPress={this.loadInBrowser} />

How to submit an HTML form on loading the page?

You missed the closing tag for the input fields, and you can choose any one of the events, ex: onload, onclick etc.

(a) Onload event:

<script type="text/javascript">
$(document).ready(function(){
     $('#frm1').submit();
});
</script>

(b) Onclick Event:

<form name="frm1" id="frm1" action="../somePage" method="post">
    Please Waite... 
    <input type="hidden" name="uname" id="uname" value=<?php echo $uname;?> />
    <input type="hidden" name="price" id="price" value=<?php echo $price;?> />
    <input type="text" name="submit" id="submit" value="submit">
</form>
<script type="text/javascript">
$('#submit').click(function(){
     $('#frm1').submit();
});
</script>

Set default host and port for ng serve in config file

This changed in the latest Angular CLI.

The file name changed to angular.json, and the structure also changed.

This is what you should do:

"projects": {
    "project-name": {
        ...
        "architect": {
            "serve": {
                "options": {
                  "host": "foo.bar",
                  "port": 80
                }
            }
        }
        ...
    }
}

How to add a response header on nginx when using proxy_pass?

There is a module called HttpHeadersMoreModule that gives you more control over headers. It does not come with Nginx and requires additional installation. With it, you can do something like this:

location ... {
  more_set_headers "Server: my_server";
}

That will "set the Server output header to the custom value for any status code and any content type". It will replace headers that are already set or add them if unset.

Are email addresses case sensitive?

Per @l3x, it depends.

There are clearly two sets of general situations where the correct answer can be different, along with a third which is not as general:

a) You are a user sending private mails:

Very few modern email systems implement case sensitivity, so you are probably fine to ignore case and choose whatever case you feel like using. There is no guarantee that all your mails will be delivered - but so few mails would be negatively affected that you should not worry about it.

b) You are developing mail software:

See RFC5321 2.4 excerpt at the bottom.

When you are developing mail software, you want to be RFC-compliant. You can make your own users' email addresses case insensitive if you want to (and you probably should). But in order to be RFC compliant, you MUST treat outside addresses as case sensitive.

c) Managing business-owned lists of email addresses as an employee:

It is possible that the same email recipient is added to a list more than once - but using different case. In this situation though the addresses are technically different, it might result in a recipient receiving duplicate emails. How you treat this situation is similar to situation a) in that you are probably fine to treat them as duplicates and to remove a duplicate entry. It is better to treat these as special cases however, by sending a "reminder" mail to both addresses to ask them if the case of the email address is accurate.

From a legal standpoint, if you remove a duplicate without acknowledgement/permission from both addresses, you can be held responsible for leaking private information/authentication to an unauthorised address simply because two actually-separate recipients have the same address with different cases.

Excerpt from RFC5321 2.4:

The local-part of a mailbox MUST BE treated as case sensitive. Therefore, SMTP implementations MUST take care to preserve the case of mailbox local-parts. In particular, for some hosts, the user "smith" is different from the user "Smith". However, exploiting the case sensitivity of mailbox local-parts impedes interoperability and is discouraged.

What is a difference between unsigned int and signed int in C?

Here is the very nice link which explains the storage of signed and unsigned INT in C -

http://answers.yahoo.com/question/index?qid=20090516032239AAzcX1O

Taken from this above article -

"process called two's complement is used to transform positive numbers into negative numbers. The side effect of this is that the most significant bit is used to tell the computer if the number is positive or negative. If the most significant bit is a 1, then the number is negative. If it's 0, the number is positive."

Changing file extension in Python

>> file = r'C:\Docs\file.2020.1.1.xls'
>> ext = '.'+ os.path.realpath(file).split('.')[-1:][0]
>> filefinal = file.replace(ext,'.zip')
>> os.rename(file ,filefinal) 

Bad logic for repeating extension, sample: 'C:\Docs\.xls_aaa.xls.xls'

Android: Clear the back stack

Kotlin example:

      val intent = Intent(this@LoginActivity, MainActivity::class.java)
      intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK
      startActivity(intent)
      finish()

Collections.emptyList() returns a List<Object>?

Since Java 8 this kind of code compiles as expected and the type parameter gets inferred by the compiler.

public Person(String name) {
    this(name, Collections.emptyList()); // Inferred to List<String> in Java 8
}

public Person(String name, List<String> nicknames) {
    this.name = name;
    this.nicknames = nicknames;
}

The new thing in Java 8 is that the target type of an expression will be used to infer type parameters of its sub-expressions. Before Java 8 only direct assignments and arguments to methods where used for type parameter inference.

In this case the parameter type of the constructor will be the target type for Collections.emptyList(), and the return value type will get chosen to match the parameter type.

This mechanism was added in Java 8 mainly to be able to compile lambda expressions, but it improves type inferences generally.

Java is getting closer to proper Hindley–Milner type inference with every release!

ResultSet exception - before start of result set

Basically you are positioning the cursor before the first row and then requesting data. You need to move the cursor to the first row.

 result.next();
 String foundType = result.getString(1);

It is common to do this in an if statement or loop.

if(result.next()){
   foundType = result.getString(1);
}

How to center the text in a JLabel?

String text = "In early March, the city of Topeka, Kansas," + "<br>" +
              "temporarily changed its name to Google..." + "<br>" + "<br>" +
              "...in an attempt to capture a spot" + "<br>" +
              "in Google's new broadband/fiber-optics project." + "<br>" + "<br>" +"<br>" +
              "source: http://en.wikipedia.org/wiki/Google_server#Oil_Tanker_Data_Center";
JLabel label = new JLabel("<html><div style='text-align: center;'>" + text + "</div></html>");

change array size

Use a List (where T is any type or Object) when you want to add/remove data, since resizing arrays is expensive. You can read more about Arrays considered somewhat harmful whereas a List can be added to New records can be appended to the end. It adjusts its size as needed.

A List can be initalized in following ways

Using collection initializer.

List<string> list1 = new List<string>()
{
    "carrot",
    "fox",
    "explorer"
};

Using var keyword with collection initializer.

var list2 = new List<string>()
{
    "carrot",
    "fox",
    "explorer"
};

Using new array as parameter.

string[] array = { "carrot", "fox", "explorer" };
List<string> list3 = new List<string>(array);

Using capacity in constructor and assign.

List<string> list4 = new List<string>(3);
list4.Add(null); // Add empty references. (Not Recommended)
list4.Add(null);
list4.Add(null);
list4[0] = "carrot"; // Assign those references.
list4[1] = "fox";
list4[2] = "explorer";

Using Add method for each element.

List<string> list5 = new List<string>();
list5.Add("carrot");
list5.Add("fox");
list5.Add("explorer");

Thus for an Object List you can allocate and assign the properties of objects inline with the List initialization. Object initializers and collection initializers share similar syntax.

class Test
{
    public int A { get; set; }
    public string B { get; set; }
}

Initialize list with collection initializer.

List<Test> list1 = new List<Test>()
{
    new Test(){ A = 1, B = "Jessica"},
    new Test(){ A = 2, B = "Mandy"}
};

Initialize list with new objects.

List<Test> list2 = new List<Test>();
list2.Add(new Test() { A = 3, B = "Sarah" });
list2.Add(new Test() { A = 4, B = "Melanie" });

Android Studio - Emulator - eglSurfaceAttrib not implemented

I've found the same thing, but only on emulators that have the Use Host GPU setting ticked. Try turning that off, you'll no longer see those warnings (and the emulator will run horribly, horribly slowly..)

In my experience those warnings are harmless. Notice that the "error" is EGL_SUCCESS, which would seem to indicate no error at all!

Convert Enum to String

As of C#6 the best way to get the name of an enum is the new nameof operator:

nameof(MyEnum.EnumValue);

// Ouputs
> "EnumValue"

This works at compile time, with the enum being replaced by the string in the compiled result, which in turn means this is the fastest way possible.

Any use of enum names does interfere with code obfuscation, if you consider obfuscation of enum names to be worthwhile or important - that's probably a whole other question.

Virtual Serial Port for Linux

You can use a pty ("pseudo-teletype", where a serial port is a "real teletype") for this. From one end, open /dev/ptyp5, and then attach your program to /dev/ttyp5; ttyp5 will act just like a serial port, but will send/receive everything it does via /dev/ptyp5.

If you really need it to talk to a file called /dev/ttys2, then simply move your old /dev/ttys2 out of the way and make a symlink from ptyp5 to ttys2.

Of course you can use some number other than ptyp5. Perhaps pick one with a high number to avoid duplicates, since all your login terminals will also be using ptys.

Wikipedia has more about ptys: http://en.wikipedia.org/wiki/Pseudo_terminal

Latex - Change margins of only a few pages

I was struggling a lot with different solutions including \vspace{-Xmm} on the top and bottom of the page and dealing with warnings and errors. Finally I found this answer:

You can change the margins of just one or more pages and then restore it to its default:

\usepackage{geometry}
...
... 
...
\newgeometry{top=5mm, bottom=10mm}     % use whatever margins you want for left, right, top and bottom.
...
... %<The contents of enlarged page(s)>
...    
\restoregeometry     %so it does not affect the rest of the pages.
...
... 
...

PS:

1- This can also fix the following warning:

LaTeX Warning: Float too large for page by ...pt on input line ...

2- For more detailed answer look at this.

3- I just found that this is more elaboration on Kevin Chen's answer.

Multiple "style" attributes in a "span" tag: what's supposed to happen?

In HTML, SGML and XML, (1) attributes cannot be repeated, and should only be defined in an element once.

So your example:

<span style="color:blue" style="font-style:italic">Test</span>

is non-conformant to the HTML standard, and will result in undefined behaviour, which explains why different browsers are rendering it differently.


Since there is no defined way to interpret this, browsers can interpret it however they want and merge them, or ignore them as they wish.

(1): Every article I can find states that attributes are "key/value" pairs or "attribute-value" pairs, heavily implying the keys must be unique. The best source I can find states:

Attribute names (id and status in this example) are subject to the same restrictions as other names in XML; they need not be unique across the whole DTD, however, but only within the list of attributes for a given element. (Emphasis mine.)

What is the best way to redirect a page using React Router?

Actually it depends on your use case.

1) You want to protect your route from unauthorized users

If that is the case you can use the component called <Redirect /> and can implement the following logic:

import React from 'react'
import  { Redirect } from 'react-router-dom'

const ProtectedComponent = () => {
  if (authFails)
    return <Redirect to='/login'  />
  }
  return <div> My Protected Component </div>
}

Keep in mind that if you want <Redirect /> to work the way you expect, you should place it inside of your component's render method so that it should eventually be considered as a DOM element, otherwise it won't work.

2) You want to redirect after a certain action (let's say after creating an item)

In that case you can use history:

myFunction() {
  addSomeStuff(data).then(() => {
      this.props.history.push('/path')
    }).catch((error) => {
      console.log(error)
    })

or

myFunction() {
  addSomeStuff()
  this.props.history.push('/path')
}

In order to have access to history, you can wrap your component with an HOC called withRouter. When you wrap your component with it, it passes match location and history props. For more detail please have a look at the official documentation for withRouter.

If your component is a child of a <Route /> component, i.e. if it is something like <Route path='/path' component={myComponent} />, you don't have to wrap your component with withRouter, because <Route /> passes match, location, and history to its child.

3) Redirect after clicking some element

There are two options here. You can use history.push() by passing it to an onClick event:

<div onClick={this.props.history.push('/path')}> some stuff </div>

or you can use a <Link /> component:

 <Link to='/path' > some stuff </Link>

I think the rule of thumb with this case is to try to use <Link /> first, I suppose especially because of performance.

filemtime "warning stat failed for"

in my case it was not related to the path or filename. If filemtime(), fileatime() or filectime() don't work, try stat().

$filedate = date_create(date("Y-m-d", filectime($file)));

becomes

$stat = stat($directory.$file);
$filedate = date_create(date("Y-m-d", $stat['ctime']));

that worked for me.

Complete snippet for deleting files by number of days:

$directory = $_SERVER['DOCUMENT_ROOT'].'/directory/';
$files = array_slice(scandir($directory), 2);
foreach($files as $file)
{
    $extension      = substr($file, -3, 3); 
    if ($extension == 'jpg') // in case you only want specific files deleted
    {
        $stat = stat($directory.$file);
        $filedate = date_create(date("Y-m-d", $stat['ctime']));
        $today = date_create(date("Y-m-d"));
        $days = date_diff($filedate, $today, true);
        if ($days->days > 1) 
        { 
            unlink($directory.$file);
        }
    } 
}

How can I use random numbers in groovy?

There is no such method as java.util.Random.getRandomDigits.

To get a random number use nextInt:

return random.nextInt(10 ** num)

Also you should create the random object once when your application starts:

Random random = new Random()

You should not create a new random object every time you want a new random number. Doing this destroys the randomness.

What is a magic number, and why is it bad?

Another advantage of extracting a magic number as a constant gives the possibility to clearly document the business information.

public class Foo {
    /** 
     * Max age in year to get child rate for airline tickets
     * 
     * The value of the constant is {@value}
     */
    public static final int MAX_AGE_FOR_CHILD_RATE = 2;

    public void computeRate() {
         if (person.getAge() < MAX_AGE_FOR_CHILD_RATE) {
               applyChildRate();
         }
    }
}

Iterating over arrays in Python 3

You can use

    nditer

Here I calculated no. of positive and negative coefficients in a logistic regression:

b=sentiment_model.coef_
pos_coef=0
neg_coef=0
for i in np.nditer(b):
    if i>0:
    pos_coef=pos_coef+1
    else:
    neg_coef=neg_coef+1
print("no. of positive coefficients is : {}".format(pos_coef))
print("no. of negative coefficients is : {}".format(neg_coef))

Output:

no. of positive coefficients is : 85035
no. of negative coefficients is : 36199

LINQ: combining join and group by

Once you've done this

group p by p.SomeId into pg  

you no longer have access to the range variables used in the initial from. That is, you can no longer talk about p or bp, you can only talk about pg.

Now, pg is a group and so contains more than one product. All the products in a given pg group have the same SomeId (since that's what you grouped by), but I don't know if that means they all have the same BaseProductId.

To get a base product name, you have to pick a particular product in the pg group (As you are doing with SomeId and CountryCode), and then join to BaseProducts.

var result = from p in Products                         
 group p by p.SomeId into pg                         
 // join *after* group
 join bp in BaseProducts on pg.FirstOrDefault().BaseProductId equals bp.Id         
 select new ProductPriceMinMax { 
       SomeId = pg.FirstOrDefault().SomeId, 
       CountryCode = pg.FirstOrDefault().CountryCode, 
       MinPrice = pg.Min(m => m.Price), 
       MaxPrice = pg.Max(m => m.Price),
       BaseProductName = bp.Name  // now there is a 'bp' in scope
 };

That said, this looks pretty unusual and I think you should step back and consider what you are actually trying to retrieve.

Spring Boot yaml configuration for a list of strings

@Value("${your.elements}")    
private String[] elements;

yml file:

your:
 elements: element1, element2, element3

VBA - Range.Row.Count

You should use UsedRange instead like so:

Sub test()
    Dim sh As Worksheet
    Dim rn As Range
    Set sh = ThisWorkbook.Sheets("Sheet1")

    Dim k As Long

    Set rn = sh.UsedRange
    k = rn.Rows.Count + rn.Row - 1
End Sub

The + rn.Row - 1 part is because the UsedRange only starts at the first row and column used, so if you have something in row 3 to 10, but rows 1 and 2 is empty, rn.Rows.Count would be 8

How to resolve "git pull,fatal: unable to access 'https://github.com...\': Empty reply from server"

If unsetting using

git config --global --unset-all https.proxy

doesn't work for you .

Then check if the environment variable http_proxy and https_proxy are set . Check using this command : -

env | grep -i proxy

If this variable is set to something , then you can just unset it using :-

   https_proxy=""

how to bypass Access-Control-Allow-Origin?

Have you tried actually adding the Access-Control-Allow-Origin header to the response sent from your server? Like, Access-Control-Allow-Origin: *?

How to ping a server only once from within a batch file?

Just write the command "ping your server IP" without the double quote. save file name as filename.bat and then run the batch file as administrator

Iterate through a C array

I think you should store the size somewhere.

The null-terminated-string kind of model for determining array length is a bad idea. For instance, getting the size of the array will be O(N) when it could very easily have been O(1) otherwise.

Having that said, a good solution might be glib's Arrays, they have the added advantage of expanding automatically if you need to add more items.

P.S. to be completely honest, I haven't used much of glib, but I think it's a (very) reputable library.

Cannot read property 'style' of undefined -- Uncaught Type Error

Add your <script> to the bottom of your <body>, or add an event listener for DOMContentLoaded following this StackOverflow question.

If that script executes in the <head> section of the code, document.getElementsByClassName(...) will return an empty array because the DOM is not loaded yet.

You're getting the Type Error because you're referencing search_span[0], but search_span[0] is undefined.

This works when you execute it in Dev Tools because the DOM is already loaded.

How do I solve the INSTALL_FAILED_DEXOPT error?

As this seems to be a problem I have myself encountered multiple times and this time none of the shared solutions helped me, I'll still post what helped me personally and what I believe may help someone else in future:

Go to your project's directory and find build/intermediates/dex-cache/cache file. Remove it - as name suggests, it's a cached dex file that may be outdated if you have made changes to your project's dependencies, build tools version etc.

What is the proper use of an EventEmitter?

TL;DR:

No, don't subscribe manually to them, don't use them in services. Use them as is shown in the documentation only to emit events in components. Don't defeat angular's abstraction.

Answer:

No, you should not subscribe manually to it.

EventEmitter is an angular2 abstraction and its only purpose is to emit events in components. Quoting a comment from Rob Wormald

[...] EventEmitter is really an Angular abstraction, and should be used pretty much only for emitting custom Events in components. Otherwise, just use Rx as if it was any other library.

This is stated really clear in EventEmitter's documentation.

Use by directives and components to emit custom Events.

What's wrong about using it?

Angular2 will never guarantee us that EventEmitter will continue being an Observable. So that means refactoring our code if it changes. The only API we must access is its emit() method. We should never subscribe manually to an EventEmitter.

All the stated above is more clear in this Ward Bell's comment (recommended to read the article, and the answer to that comment). Quoting for reference

Do NOT count on EventEmitter continuing to be an Observable!

Do NOT count on those Observable operators being there in the future!

These will be deprecated soon and probably removed before release.

Use EventEmitter only for event binding between a child and parent component. Do not subscribe to it. Do not call any of those methods. Only call eve.emit()

His comment is in line with Rob's comment long time ago.

So, how to use it properly?

Simply use it to emit events from your component. Take a look a the following example.

@Component({
    selector : 'child',
    template : `
        <button (click)="sendNotification()">Notify my parent!</button>
    `
})
class Child {
    @Output() notifyParent: EventEmitter<any> = new EventEmitter();
    sendNotification() {
        this.notifyParent.emit('Some value to send to the parent');
    }
}

@Component({
    selector : 'parent',
    template : `
        <child (notifyParent)="getNotification($event)"></child>
    `
})
class Parent {
    getNotification(evt) {
        // Do something with the notification (evt) sent by the child!
    }
}

How not to use it?

class MyService {
    @Output() myServiceEvent : EventEmitter<any> = new EventEmitter();
}

Stop right there... you're already wrong...

Hopefully these two simple examples will clarify EventEmitter's proper usage.

ORDER BY items must appear in the select list if SELECT DISTINCT is specified

Distinct and Group By generally do the same kind of thing, for different purposes... They both create a 'working" table in memory based on the columns being Grouped on, (or selected in the Select Distinct clause) - and then populate that working table as the query reads data, adding a new "row" only when the values indicate the need to do so...

The only difference is that in the Group By there are additional "columns" in the working table for any calculated aggregate fields, like Sum(), Count(), Avg(), etc. that need to updated for each original row read. Distinct doesn't have to do this... In the special case where you Group By only to get distinct values, (And there are no aggregate columns in output), then it is probably exactly the same query plan.... It would be interesting to review the query execution plan for the two options and see what it did...

Certainly Distinct is the way to go for readability if that is what you are doing (When your purpose is to eliminate duplicate rows, and you are not calculating any aggregate columns)

How to undo a git merge with conflicts

Latest Git:

git merge --abort

This attempts to reset your working copy to whatever state it was in before the merge. That means that it should restore any uncommitted changes from before the merge, although it cannot always do so reliably. Generally you shouldn't merge with uncommitted changes anyway.

Prior to version 1.7.4:

git reset --merge

This is older syntax but does the same as the above.

Prior to version 1.6.2:

git reset --hard

which removes all uncommitted changes, including the uncommitted merge. Sometimes this behaviour is useful even in newer versions of Git that support the above commands.

Get program path in VB.NET?

For a console application you can use System.Reflection.Assembly.GetExecutingAssembly().Location as long as the call is made within the code of the console app itself, if you call this from within another dll or plugin this will return the location of that DLL and not the executable.

Getting a list of all subdirectories in the current directory

Although this question is answered a long time ago. I want to recommend to use the pathlib module since this is a robust way to work on Windows and Unix OS.

So to get all paths in a specific directory including subdirectories:

from pathlib import Path
paths = list(Path('myhomefolder', 'folder').glob('**/*.txt'))

# all sorts of operations
file = paths[0]
file.name
file.stem
file.parent
file.suffix

etc.

Finding current executable's path without /proc/self/exe

AFAIK, no such way. And there is also an ambiguity: what would you like to get as the answer if the same executable has multiple hard-links "pointing" to it? (Hard-links don't actually "point", they are the same file, just at another place in the file system hierarchy.)

Once execve() successfully executes a new binary, all information about the arguments to the original program is lost.

C++ templates that accept only certain types

I think all prior answers have lost sight of the forest for the trees.

Java generics are not the same as templates; they use type erasure, which is a dynamic technique, rather than compile time polymorphism, which is static technique. It should be obvious why these two very different tactics do not gel well.

Rather than attempt to use a compile time construct to simulate a run time one, let's look at what extends actually does: according to Stack Overflow and Wikipedia, extends is used to indicate subclassing.

C++ also supports subclassing.

You also show a container class, which is using type erasure in the form of a generic, and extends to perform a type check. In C++, you have to do the type erasure machinery yourself, which is simple: make a pointer to the superclass.

Let's wrap it into a typedef, to make it easier to use, rather than make a whole class, et voila:

typedef std::list<superclass*> subclasses_of_superclass_only_list;

For example:

class Shape { };
class Triangle : public Shape { };

typedef std::list<Shape*> only_shapes_list;
only_shapes_list shapes;

shapes.push_back(new Triangle()); // Works, triangle is kind of shape
shapes.push_back(new int(30)); // Error, int's are not shapes

Now, it seems List is an interface, representing a sort of collection. An interface in C++ would merely be an abstract class, that is, a class that implements nothing but pure virtual methods. Using this method, you could easily implement your java example in C++, without any Concepts or template specializations. It would also perform as slow as Java style generics due to the virtual table look ups, but this can often be an acceptable loss.

How to count frequency of characters in a string?

This is similar to xunil154's answer, except that a string is made a char array and a linked hashmap is used to maintain the insertion order of the characters.

String text = "aasjjikkk";
char[] charArray = text.toCharArray();
Map<Character, Integer> freqList = new LinkedHashMap<Character, Integer>();

        for(char key : charArray) {
            if(freqList.containsKey(key)) {
               freqList.put(key, freqList.get(key) + 1);
            } else
                freqList.put(key, 1);
        }

Click event on select option element in chrome

I found that the following worked for me - instead on using on click, use on change e.g.:

 jQuery('#element select').on('change',  (function() {

       //your code here

}));

Check for special characters in string

I suggest using RegExp .test() function to check for a pattern match, and the only thing you need to change is remove the start/end of line anchors (and the * quantifier is also redundant) in the regex:

_x000D_
_x000D_
var format = /[ `!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]/;_x000D_
//            ^                                       ^   _x000D_
document.write(format.test("My@string-with(some%text)") + "<br/>");_x000D_
document.write(format.test("My string with spaces") + "<br/>");_x000D_
document.write(format.test("MyStringContainingNoSpecialChars"));
_x000D_
_x000D_
_x000D_

The anchors (like ^ start of string/line, $ end od string/line and \b word boundaries) can restrict matches at specific places in a string. When using ^ the regex engine checks if the next subpattern appears right at the start of the string (or line if /m modifier is declared in the regex). Same case with $: the preceding subpattern should match right at the end of the string.

In your case, you want to check the existence of the special character from the set anywhere in the string. Even if it is only one, you want to return false. Thus, you should remove the anchors, and the quantifier *. The * quantifier would match even an empty string, thus we must remove it in order to actually check for the presence of at least 1 special character (actually, without any quantifiers we check for exactly one occurrence, same as if we were using {1} limiting quantifier).

More specific solutions

What characters are "special" for you?

  • All chars other than ASCII chars: /[^\x00-\x7F]/ (demo)
  • All chars other than printable ASCII chars: /[^ -~]/ (demo)
  • Any printable ASCII chars other than space, letters and digits: /[!-\/:-@[-`{-~]/ (demo)
  • Any Unicode punctuation proper chars, the \p{P} Unicode property class:
    • ECMAScript 2018: /\p{P}/u
    • ES6+:
/[!-#%-*,-\/:;?@[-\]_{}\u00A1\u00A7\u00AB\u00B6\u00B7\u00BB\u00BF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061E\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u09FD\u0A76\u0AF0\u0C84\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166D\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E4E\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65\u{10100}-\u{10102}\u{1039F}\u{103D0}\u{1056F}\u{10857}\u{1091F}\u{1093F}\u{10A50}-\u{10A58}\u{10A7F}\u{10AF0}-\u{10AF6}\u{10B39}-\u{10B3F}\u{10B99}-\u{10B9C}\u{10F55}-\u{10F59}\u{11047}-\u{1104D}\u{110BB}\u{110BC}\u{110BE}-\u{110C1}\u{11140}-\u{11143}\u{11174}\u{11175}\u{111C5}-\u{111C8}\u{111CD}\u{111DB}\u{111DD}-\u{111DF}\u{11238}-\u{1123D}\u{112A9}\u{1144B}-\u{1144F}\u{1145B}\u{1145D}\u{114C6}\u{115C1}-\u{115D7}\u{11641}-\u{11643}\u{11660}-\u{1166C}\u{1173C}-\u{1173E}\u{1183B}\u{11A3F}-\u{11A46}\u{11A9A}-\u{11A9C}\u{11A9E}-\u{11AA2}\u{11C41}-\u{11C45}\u{11C70}\u{11C71}\u{11EF7}\u{11EF8}\u{12470}-\u{12474}\u{16A6E}\u{16A6F}\u{16AF5}\u{16B37}-\u{16B3B}\u{16B44}\u{16E97}-\u{16E9A}\u{1BC9F}\u{1DA87}-\u{1DA8B}\u{1E95E}\u{1E95F}]/u

         ? ES5 (demo):

/(?:[!-#%-\*,-\/:;\?@\[-\]_\{\}\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061E\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u09FD\u0A76\u0AF0\u0C84\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166D\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E4E\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]|\uD800[\uDD00-\uDD02\uDF9F\uDFD0]|\uD801\uDD6F|\uD802[\uDC57\uDD1F\uDD3F\uDE50-\uDE58\uDE7F\uDEF0-\uDEF6\uDF39-\uDF3F\uDF99-\uDF9C]|\uD803[\uDF55-\uDF59]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC8\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9]|\uD805[\uDC4B-\uDC4F\uDC5B\uDC5D\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDE60-\uDE6C\uDF3C-\uDF3E]|\uD806[\uDC3B\uDE3F-\uDE46\uDE9A-\uDE9C\uDE9E-\uDEA2]|\uD807[\uDC41-\uDC45\uDC70\uDC71\uDEF7\uDEF8]|\uD809[\uDC70-\uDC74]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3B\uDF44]|\uD81B[\uDE97-\uDE9A]|\uD82F\uDC9F|\uD836[\uDE87-\uDE8B]|\uD83A[\uDD5E\uDD5F])/
  • All Unicode symbols (not punctuation proper), \p{S}:
    • ECMAScript 2018: /\p{S}/u
    • ES6+:
/[$+^`|~\u00A2-\u00A6\u00A8\u00A9\u00AC\u00AE-\u00B1\u00B4\u00B8\u00D7\u00F7\u02C2-\u02C5\u02D2-\u02DF\u02E5-\u02EB\u02ED\u02EF-\u02FF\u0375\u0384\u0385\u03F6\u0482\u058D-\u058F\u0606-\u0608\u060B\u060E\u060F\u06DE\u06E9\u06FD\u06FE\u07F6\u07FE\u07FF\u09F2\u09F3\u09FA\u09FB\u0AF1\u0B70\u0BF3-\u0BFA\u0C7F\u0D4F\u0D79\u0E3F\u0F01-\u0F03\u0F13\u0F15-\u0F17\u0F1A-\u0F1F\u0F34\u0F36\u0F38\u0FBE-\u0FC5\u0FC7-\u0FCC\u0FCE\u0FCF\u0FD5-\u0FD8\u109E\u109F\u1390-\u1399\u17DB\u1940\u19DE-\u19FF\u1B61-\u1B6A\u1B74-\u1B7C\u1FBD\u1FBF-\u1FC1\u1FCD-\u1FCF\u1FDD-\u1FDF\u1FED-\u1FEF\u1FFD\u1FFE\u2044\u2052\u207A-\u207C\u208A-\u208C\u20A0-\u20BF\u2100\u2101\u2103-\u2106\u2108\u2109\u2114\u2116-\u2118\u211E-\u2123\u2125\u2127\u2129\u212E\u213A\u213B\u2140-\u2144\u214A-\u214D\u214F\u218A\u218B\u2190-\u2307\u230C-\u2328\u232B-\u2426\u2440-\u244A\u249C-\u24E9\u2500-\u2767\u2794-\u27C4\u27C7-\u27E5\u27F0-\u2982\u2999-\u29D7\u29DC-\u29FB\u29FE-\u2B73\u2B76-\u2B95\u2B98-\u2BC8\u2BCA-\u2BFE\u2CE5-\u2CEA\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFB\u3004\u3012\u3013\u3020\u3036\u3037\u303E\u303F\u309B\u309C\u3190\u3191\u3196-\u319F\u31C0-\u31E3\u3200-\u321E\u322A-\u3247\u3250\u3260-\u327F\u328A-\u32B0\u32C0-\u32FE\u3300-\u33FF\u4DC0-\u4DFF\uA490-\uA4C6\uA700-\uA716\uA720\uA721\uA789\uA78A\uA828-\uA82B\uA836-\uA839\uAA77-\uAA79\uAB5B\uFB29\uFBB2-\uFBC1\uFDFC\uFDFD\uFE62\uFE64-\uFE66\uFE69\uFF04\uFF0B\uFF1C-\uFF1E\uFF3E\uFF40\uFF5C\uFF5E\uFFE0-\uFFE6\uFFE8-\uFFEE\uFFFC\uFFFD\u{10137}-\u{1013F}\u{10179}-\u{10189}\u{1018C}-\u{1018E}\u{10190}-\u{1019B}\u{101A0}\u{101D0}-\u{101FC}\u{10877}\u{10878}\u{10AC8}\u{1173F}\u{16B3C}-\u{16B3F}\u{16B45}\u{1BC9C}\u{1D000}-\u{1D0F5}\u{1D100}-\u{1D126}\u{1D129}-\u{1D164}\u{1D16A}-\u{1D16C}\u{1D183}\u{1D184}\u{1D18C}-\u{1D1A9}\u{1D1AE}-\u{1D1E8}\u{1D200}-\u{1D241}\u{1D245}\u{1D300}-\u{1D356}\u{1D6C1}\u{1D6DB}\u{1D6FB}\u{1D715}\u{1D735}\u{1D74F}\u{1D76F}\u{1D789}\u{1D7A9}\u{1D7C3}\u{1D800}-\u{1D9FF}\u{1DA37}-\u{1DA3A}\u{1DA6D}-\u{1DA74}\u{1DA76}-\u{1DA83}\u{1DA85}\u{1DA86}\u{1ECAC}\u{1ECB0}\u{1EEF0}\u{1EEF1}\u{1F000}-\u{1F02B}\u{1F030}-\u{1F093}\u{1F0A0}-\u{1F0AE}\u{1F0B1}-\u{1F0BF}\u{1F0C1}-\u{1F0CF}\u{1F0D1}-\u{1F0F5}\u{1F110}-\u{1F16B}\u{1F170}-\u{1F1AC}\u{1F1E6}-\u{1F202}\u{1F210}-\u{1F23B}\u{1F240}-\u{1F248}\u{1F250}\u{1F251}\u{1F260}-\u{1F265}\u{1F300}-\u{1F6D4}\u{1F6E0}-\u{1F6EC}\u{1F6F0}-\u{1F6F9}\u{1F700}-\u{1F773}\u{1F780}-\u{1F7D8}\u{1F800}-\u{1F80B}\u{1F810}-\u{1F847}\u{1F850}-\u{1F859}\u{1F860}-\u{1F887}\u{1F890}-\u{1F8AD}\u{1F900}-\u{1F90B}\u{1F910}-\u{1F93E}\u{1F940}-\u{1F970}\u{1F973}-\u{1F976}\u{1F97A}\u{1F97C}-\u{1F9A2}\u{1F9B0}-\u{1F9B9}\u{1F9C0}-\u{1F9C2}\u{1F9D0}-\u{1F9FF}\u{1FA60}-\u{1FA6D}]/u

         ? ES5 (demo):

/(?:[$+^`|~\xA2-\xA6\xA8\xA9\xAC\xAE-\xB1\xB4\xB8\xD7\xF7\u02C2-\u02C5\u02D2-\u02DF\u02E5-\u02EB\u02ED\u02EF-\u02FF\u0375\u0384\u0385\u03F6\u0482\u058D-\u058F\u0606-\u0608\u060B\u060E\u060F\u06DE\u06E9\u06FD\u06FE\u07F6\u07FE\u07FF\u09F2\u09F3\u09FA\u09FB\u0AF1\u0B70\u0BF3-\u0BFA\u0C7F\u0D4F\u0D79\u0E3F\u0F01-\u0F03\u0F13\u0F15-\u0F17\u0F1A-\u0F1F\u0F34\u0F36\u0F38\u0FBE-\u0FC5\u0FC7-\u0FCC\u0FCE\u0FCF\u0FD5-\u0FD8\u109E\u109F\u1390-\u1399\u17DB\u1940\u19DE-\u19FF\u1B61-\u1B6A\u1B74-\u1B7C\u1FBD\u1FBF-\u1FC1\u1FCD-\u1FCF\u1FDD-\u1FDF\u1FED-\u1FEF\u1FFD\u1FFE\u2044\u2052\u207A-\u207C\u208A-\u208C\u20A0-\u20BF\u2100\u2101\u2103-\u2106\u2108\u2109\u2114\u2116-\u2118\u211E-\u2123\u2125\u2127\u2129\u212E\u213A\u213B\u2140-\u2144\u214A-\u214D\u214F\u218A\u218B\u2190-\u2307\u230C-\u2328\u232B-\u2426\u2440-\u244A\u249C-\u24E9\u2500-\u2767\u2794-\u27C4\u27C7-\u27E5\u27F0-\u2982\u2999-\u29D7\u29DC-\u29FB\u29FE-\u2B73\u2B76-\u2B95\u2B98-\u2BC8\u2BCA-\u2BFE\u2CE5-\u2CEA\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFB\u3004\u3012\u3013\u3020\u3036\u3037\u303E\u303F\u309B\u309C\u3190\u3191\u3196-\u319F\u31C0-\u31E3\u3200-\u321E\u322A-\u3247\u3250\u3260-\u327F\u328A-\u32B0\u32C0-\u32FE\u3300-\u33FF\u4DC0-\u4DFF\uA490-\uA4C6\uA700-\uA716\uA720\uA721\uA789\uA78A\uA828-\uA82B\uA836-\uA839\uAA77-\uAA79\uAB5B\uFB29\uFBB2-\uFBC1\uFDFC\uFDFD\uFE62\uFE64-\uFE66\uFE69\uFF04\uFF0B\uFF1C-\uFF1E\uFF3E\uFF40\uFF5C\uFF5E\uFFE0-\uFFE6\uFFE8-\uFFEE\uFFFC\uFFFD]|\uD800[\uDD37-\uDD3F\uDD79-\uDD89\uDD8C-\uDD8E\uDD90-\uDD9B\uDDA0\uDDD0-\uDDFC]|\uD802[\uDC77\uDC78\uDEC8]|\uD805\uDF3F|\uD81A[\uDF3C-\uDF3F\uDF45]|\uD82F\uDC9C|\uD834[\uDC00-\uDCF5\uDD00-\uDD26\uDD29-\uDD64\uDD6A-\uDD6C\uDD83\uDD84\uDD8C-\uDDA9\uDDAE-\uDDE8\uDE00-\uDE41\uDE45\uDF00-\uDF56]|\uD835[\uDEC1\uDEDB\uDEFB\uDF15\uDF35\uDF4F\uDF6F\uDF89\uDFA9\uDFC3]|\uD836[\uDC00-\uDDFF\uDE37-\uDE3A\uDE6D-\uDE74\uDE76-\uDE83\uDE85\uDE86]|\uD83B[\uDCAC\uDCB0\uDEF0\uDEF1]|\uD83C[\uDC00-\uDC2B\uDC30-\uDC93\uDCA0-\uDCAE\uDCB1-\uDCBF\uDCC1-\uDCCF\uDCD1-\uDCF5\uDD10-\uDD6B\uDD70-\uDDAC\uDDE6-\uDE02\uDE10-\uDE3B\uDE40-\uDE48\uDE50\uDE51\uDE60-\uDE65\uDF00-\uDFFF]|\uD83D[\uDC00-\uDED4\uDEE0-\uDEEC\uDEF0-\uDEF9\uDF00-\uDF73\uDF80-\uDFD8]|\uD83E[\uDC00-\uDC0B\uDC10-\uDC47\uDC50-\uDC59\uDC60-\uDC87\uDC90-\uDCAD\uDD00-\uDD0B\uDD10-\uDD3E\uDD40-\uDD70\uDD73-\uDD76\uDD7A\uDD7C-\uDDA2\uDDB0-\uDDB9\uDDC0-\uDDC2\uDDD0-\uDDFF\uDE60-\uDE6D])/
  • All Unicode punctuation and symbols, \p{P} and \p{S}:
    • ECMAScript 2018: /[\p{P}\p{S}]/u
    • ES6+:
/[!-\/:-@[-`{-~\u00A1-\u00A9\u00AB\u00AC\u00AE-\u00B1\u00B4\u00B6-\u00B8\u00BB\u00BF\u00D7\u00F7\u02C2-\u02C5\u02D2-\u02DF\u02E5-\u02EB\u02ED\u02EF-\u02FF\u0375\u037E\u0384\u0385\u0387\u03F6\u0482\u055A-\u055F\u0589\u058A\u058D-\u058F\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0606-\u060F\u061B\u061E\u061F\u066A-\u066D\u06D4\u06DE\u06E9\u06FD\u06FE\u0700-\u070D\u07F6-\u07F9\u07FE\u07FF\u0830-\u083E\u085E\u0964\u0965\u0970\u09F2\u09F3\u09FA\u09FB\u09FD\u0A76\u0AF0\u0AF1\u0B70\u0BF3-\u0BFA\u0C7F\u0C84\u0D4F\u0D79\u0DF4\u0E3F\u0E4F\u0E5A\u0E5B\u0F01-\u0F17\u0F1A-\u0F1F\u0F34\u0F36\u0F38\u0F3A-\u0F3D\u0F85\u0FBE-\u0FC5\u0FC7-\u0FCC\u0FCE-\u0FDA\u104A-\u104F\u109E\u109F\u10FB\u1360-\u1368\u1390-\u1399\u1400\u166D\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DB\u1800-\u180A\u1940\u1944\u1945\u19DE-\u19FF\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B6A\u1B74-\u1B7C\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u1FBD\u1FBF-\u1FC1\u1FCD-\u1FCF\u1FDD-\u1FDF\u1FED-\u1FEF\u1FFD\u1FFE\u2010-\u2027\u2030-\u205E\u207A-\u207E\u208A-\u208E\u20A0-\u20BF\u2100\u2101\u2103-\u2106\u2108\u2109\u2114\u2116-\u2118\u211E-\u2123\u2125\u2127\u2129\u212E\u213A\u213B\u2140-\u2144\u214A-\u214D\u214F\u218A\u218B\u2190-\u2426\u2440-\u244A\u249C-\u24E9\u2500-\u2775\u2794-\u2B73\u2B76-\u2B95\u2B98-\u2BC8\u2BCA-\u2BFE\u2CE5-\u2CEA\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E4E\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFB\u3001-\u3004\u3008-\u3020\u3030\u3036\u3037\u303D-\u303F\u309B\u309C\u30A0\u30FB\u3190\u3191\u3196-\u319F\u31C0-\u31E3\u3200-\u321E\u322A-\u3247\u3250\u3260-\u327F\u328A-\u32B0\u32C0-\u32FE\u3300-\u33FF\u4DC0-\u4DFF\uA490-\uA4C6\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA700-\uA716\uA720\uA721\uA789\uA78A\uA828-\uA82B\uA836-\uA839\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAA77-\uAA79\uAADE\uAADF\uAAF0\uAAF1\uAB5B\uABEB\uFB29\uFBB2-\uFBC1\uFD3E\uFD3F\uFDFC\uFDFD\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE66\uFE68-\uFE6B\uFF01-\uFF0F\uFF1A-\uFF20\uFF3B-\uFF40\uFF5B-\uFF65\uFFE0-\uFFE6\uFFE8-\uFFEE\uFFFC\uFFFD\u{10100}-\u{10102}\u{10137}-\u{1013F}\u{10179}-\u{10189}\u{1018C}-\u{1018E}\u{10190}-\u{1019B}\u{101A0}\u{101D0}-\u{101FC}\u{1039F}\u{103D0}\u{1056F}\u{10857}\u{10877}\u{10878}\u{1091F}\u{1093F}\u{10A50}-\u{10A58}\u{10A7F}\u{10AC8}\u{10AF0}-\u{10AF6}\u{10B39}-\u{10B3F}\u{10B99}-\u{10B9C}\u{10F55}-\u{10F59}\u{11047}-\u{1104D}\u{110BB}\u{110BC}\u{110BE}-\u{110C1}\u{11140}-\u{11143}\u{11174}\u{11175}\u{111C5}-\u{111C8}\u{111CD}\u{111DB}\u{111DD}-\u{111DF}\u{11238}-\u{1123D}\u{112A9}\u{1144B}-\u{1144F}\u{1145B}\u{1145D}\u{114C6}\u{115C1}-\u{115D7}\u{11641}-\u{11643}\u{11660}-\u{1166C}\u{1173C}-\u{1173F}\u{1183B}\u{11A3F}-\u{11A46}\u{11A9A}-\u{11A9C}\u{11A9E}-\u{11AA2}\u{11C41}-\u{11C45}\u{11C70}\u{11C71}\u{11EF7}\u{11EF8}\u{12470}-\u{12474}\u{16A6E}\u{16A6F}\u{16AF5}\u{16B37}-\u{16B3F}\u{16B44}\u{16B45}\u{16E97}-\u{16E9A}\u{1BC9C}\u{1BC9F}\u{1D000}-\u{1D0F5}\u{1D100}-\u{1D126}\u{1D129}-\u{1D164}\u{1D16A}-\u{1D16C}\u{1D183}\u{1D184}\u{1D18C}-\u{1D1A9}\u{1D1AE}-\u{1D1E8}\u{1D200}-\u{1D241}\u{1D245}\u{1D300}-\u{1D356}\u{1D6C1}\u{1D6DB}\u{1D6FB}\u{1D715}\u{1D735}\u{1D74F}\u{1D76F}\u{1D789}\u{1D7A9}\u{1D7C3}\u{1D800}-\u{1D9FF}\u{1DA37}-\u{1DA3A}\u{1DA6D}-\u{1DA74}\u{1DA76}-\u{1DA83}\u{1DA85}-\u{1DA8B}\u{1E95E}\u{1E95F}\u{1ECAC}\u{1ECB0}\u{1EEF0}\u{1EEF1}\u{1F000}-\u{1F02B}\u{1F030}-\u{1F093}\u{1F0A0}-\u{1F0AE}\u{1F0B1}-\u{1F0BF}\u{1F0C1}-\u{1F0CF}\u{1F0D1}-\u{1F0F5}\u{1F110}-\u{1F16B}\u{1F170}-\u{1F1AC}\u{1F1E6}-\u{1F202}\u{1F210}-\u{1F23B}\u{1F240}-\u{1F248}\u{1F250}\u{1F251}\u{1F260}-\u{1F265}\u{1F300}-\u{1F6D4}\u{1F6E0}-\u{1F6EC}\u{1F6F0}-\u{1F6F9}\u{1F700}-\u{1F773}\u{1F780}-\u{1F7D8}\u{1F800}-\u{1F80B}\u{1F810}-\u{1F847}\u{1F850}-\u{1F859}\u{1F860}-\u{1F887}\u{1F890}-\u{1F8AD}\u{1F900}-\u{1F90B}\u{1F910}-\u{1F93E}\u{1F940}-\u{1F970}\u{1F973}-\u{1F976}\u{1F97A}\u{1F97C}-\u{1F9A2}\u{1F9B0}-\u{1F9B9}\u{1F9C0}-\u{1F9C2}\u{1F9D0}-\u{1F9FF}\u{1FA60}-\u{1FA6D}]/u

         ? ES5 (demo):

/(?:[!-\/:-@\[-`\{-~\xA1-\xA9\xAB\xAC\xAE-\xB1\xB4\xB6-\xB8\xBB\xBF\xD7\xF7\u02C2-\u02C5\u02D2-\u02DF\u02E5-\u02EB\u02ED\u02EF-\u02FF\u0375\u037E\u0384\u0385\u0387\u03F6\u0482\u055A-\u055F\u0589\u058A\u058D-\u058F\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0606-\u060F\u061B\u061E\u061F\u066A-\u066D\u06D4\u06DE\u06E9\u06FD\u06FE\u0700-\u070D\u07F6-\u07F9\u07FE\u07FF\u0830-\u083E\u085E\u0964\u0965\u0970\u09F2\u09F3\u09FA\u09FB\u09FD\u0A76\u0AF0\u0AF1\u0B70\u0BF3-\u0BFA\u0C7F\u0C84\u0D4F\u0D79\u0DF4\u0E3F\u0E4F\u0E5A\u0E5B\u0F01-\u0F17\u0F1A-\u0F1F\u0F34\u0F36\u0F38\u0F3A-\u0F3D\u0F85\u0FBE-\u0FC5\u0FC7-\u0FCC\u0FCE-\u0FDA\u104A-\u104F\u109E\u109F\u10FB\u1360-\u1368\u1390-\u1399\u1400\u166D\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DB\u1800-\u180A\u1940\u1944\u1945\u19DE-\u19FF\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B6A\u1B74-\u1B7C\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u1FBD\u1FBF-\u1FC1\u1FCD-\u1FCF\u1FDD-\u1FDF\u1FED-\u1FEF\u1FFD\u1FFE\u2010-\u2027\u2030-\u205E\u207A-\u207E\u208A-\u208E\u20A0-\u20BF\u2100\u2101\u2103-\u2106\u2108\u2109\u2114\u2116-\u2118\u211E-\u2123\u2125\u2127\u2129\u212E\u213A\u213B\u2140-\u2144\u214A-\u214D\u214F\u218A\u218B\u2190-\u2426\u2440-\u244A\u249C-\u24E9\u2500-\u2775\u2794-\u2B73\u2B76-\u2B95\u2B98-\u2BC8\u2BCA-\u2BFE\u2CE5-\u2CEA\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E4E\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFB\u3001-\u3004\u3008-\u3020\u3030\u3036\u3037\u303D-\u303F\u309B\u309C\u30A0\u30FB\u3190\u3191\u3196-\u319F\u31C0-\u31E3\u3200-\u321E\u322A-\u3247\u3250\u3260-\u327F\u328A-\u32B0\u32C0-\u32FE\u3300-\u33FF\u4DC0-\u4DFF\uA490-\uA4C6\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA700-\uA716\uA720\uA721\uA789\uA78A\uA828-\uA82B\uA836-\uA839\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAA77-\uAA79\uAADE\uAADF\uAAF0\uAAF1\uAB5B\uABEB\uFB29\uFBB2-\uFBC1\uFD3E\uFD3F\uFDFC\uFDFD\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE66\uFE68-\uFE6B\uFF01-\uFF0F\uFF1A-\uFF20\uFF3B-\uFF40\uFF5B-\uFF65\uFFE0-\uFFE6\uFFE8-\uFFEE\uFFFC\uFFFD]|\uD800[\uDD00-\uDD02\uDD37-\uDD3F\uDD79-\uDD89\uDD8C-\uDD8E\uDD90-\uDD9B\uDDA0\uDDD0-\uDDFC\uDF9F\uDFD0]|\uD801\uDD6F|\uD802[\uDC57\uDC77\uDC78\uDD1F\uDD3F\uDE50-\uDE58\uDE7F\uDEC8\uDEF0-\uDEF6\uDF39-\uDF3F\uDF99-\uDF9C]|\uD803[\uDF55-\uDF59]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC8\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9]|\uD805[\uDC4B-\uDC4F\uDC5B\uDC5D\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDE60-\uDE6C\uDF3C-\uDF3F]|\uD806[\uDC3B\uDE3F-\uDE46\uDE9A-\uDE9C\uDE9E-\uDEA2]|\uD807[\uDC41-\uDC45\uDC70\uDC71\uDEF7\uDEF8]|\uD809[\uDC70-\uDC74]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3F\uDF44\uDF45]|\uD81B[\uDE97-\uDE9A]|\uD82F[\uDC9C\uDC9F]|\uD834[\uDC00-\uDCF5\uDD00-\uDD26\uDD29-\uDD64\uDD6A-\uDD6C\uDD83\uDD84\uDD8C-\uDDA9\uDDAE-\uDDE8\uDE00-\uDE41\uDE45\uDF00-\uDF56]|\uD835[\uDEC1\uDEDB\uDEFB\uDF15\uDF35\uDF4F\uDF6F\uDF89\uDFA9\uDFC3]|\uD836[\uDC00-\uDDFF\uDE37-\uDE3A\uDE6D-\uDE74\uDE76-\uDE83\uDE85-\uDE8B]|\uD83A[\uDD5E\uDD5F]|\uD83B[\uDCAC\uDCB0\uDEF0\uDEF1]|\uD83C[\uDC00-\uDC2B\uDC30-\uDC93\uDCA0-\uDCAE\uDCB1-\uDCBF\uDCC1-\uDCCF\uDCD1-\uDCF5\uDD10-\uDD6B\uDD70-\uDDAC\uDDE6-\uDE02\uDE10-\uDE3B\uDE40-\uDE48\uDE50\uDE51\uDE60-\uDE65\uDF00-\uDFFF]|\uD83D[\uDC00-\uDED4\uDEE0-\uDEEC\uDEF0-\uDEF9\uDF00-\uDF73\uDF80-\uDFD8]|\uD83E[\uDC00-\uDC0B\uDC10-\uDC47\uDC50-\uDC59\uDC60-\uDC87\uDC90-\uDCAD\uDD00-\uDD0B\uDD10-\uDD3E\uDD40-\uDD70\uDD73-\uDD76\uDD7A\uDD7C-\uDDA2\uDDB0-\uDDB9\uDDC0-\uDDC2\uDDD0-\uDDFF\uDE60-\uDE6D])/

Unable to allocate array with shape and data type

In my case, adding a dtype attribute changed dtype of the array to a smaller type(from float64 to uint8), decreasing array size enough to not throw MemoryError in Windows(64 bit).

from

mask = np.zeros(edges.shape)

to

mask = np.zeros(edges.shape,dtype='uint8')

How to update a record using sequelize for node?

There are two ways you can update the record in sequelize.

First, if you have a unique identifier then you can use where clause or else if you want to update multiple records with the same identifier.

You can either create the whole object to update or a specific column

const objectToUpdate = {
title: 'Hello World',
description: 'Hello World'
}

models.Locale.update(objectToUpdate, { where: { id: 2}})

Only Update a specific column

models.Locale.update({ title: 'Hello World'}, { where: { id: 2}})

Second, you can use find a query to find it and use set and save function to update the DB.


const objectToUpdate = {
title: 'Hello World',
description: 'Hello World'
}

models.Locale.findAll({ where: { title: 'Hello World'}}).then((result) => {
   if(result){
   // Result is array because we have used findAll. We can use findOne as well if you want one row and update that.
        result[0].set(objectToUpdate);
        result[0].save(); // This is a promise
}
})

Always use transaction while updating or creating a new row. that way it will roll back any updates if there is any error or if you doing any multiple updates:


models.sequelize.transaction((tx) => {
    models.Locale.update(objectToUpdate, { transaction: t, where: {id: 2}});
})

Python: Maximum recursion depth exceeded

You can increment the stack depth allowed - with this, deeper recursive calls will be possible, like this:

import sys
sys.setrecursionlimit(10000) # 10000 is an example, try with different values

... But I'd advise you to first try to optimize your code, for instance, using iteration instead of recursion.

How to check identical array in most efficient way?

So, what's wrong with checking each element iteratively?

function arraysEqual(arr1, arr2) {
    if(arr1.length !== arr2.length)
        return false;
    for(var i = arr1.length; i--;) {
        if(arr1[i] !== arr2[i])
            return false;
    }

    return true;
}

Calculate last day of month in JavaScript

I find this to be the best solution for me. Let the Date object calculate it for you.

var today = new Date();
var lastDayOfMonth = new Date(today.getFullYear(), today.getMonth()+1, 0);

Setting day parameter to 0 means one day less than first day of the month which is last day of the previous month.

How to delete from select in MySQL?

If you want to delete all duplicates, but one out of each set of duplicates, this is one solution:

DELETE posts
FROM posts
LEFT JOIN (
    SELECT id
    FROM posts
    GROUP BY id
    HAVING COUNT(id) = 1

    UNION

    SELECT id
    FROM posts
    GROUP BY id
    HAVING COUNT(id) != 1
) AS duplicate USING (id)
WHERE duplicate.id IS NULL;

How can I get the status code from an http error in Axios?

Axios. get('foo.com')
.then((response) => {})
.catch((error) => {
    if(error. response){
       console.log(error. response. data)
       console.log(error. response. status);

      }
})

Mysql - delete from multiple tables with one query

The documentation for DELETE tells you the multi-table syntax.

DELETE [LOW_PRIORITY] [QUICK] [IGNORE]
    tbl_name[.*] [, tbl_name[.*]] ...
    FROM table_references
    [WHERE where_condition]

Or:

DELETE [LOW_PRIORITY] [QUICK] [IGNORE]
    FROM tbl_name[.*] [, tbl_name[.*]] ...
    USING table_references
    [WHERE where_condition]

Rails 3 check if attribute changed

ActiveModel::Dirty didn't work for me because the @model.update_attributes() hid the changes. So this is how I detected changes it in an update method in a controller:

def update
  @model = Model.find(params[:id])
  detect_changes

  if @model.update_attributes(params[:model])
    do_stuff if attr_changed?
  end
end

private

def detect_changes
  @changed = []
  @changed << :attr if @model.attr != params[:model][:attr]
end

def attr_changed?
  @changed.include :attr
end

If you're trying to detect a lot of attribute changes it could get messy though. Probably shouldn't do this in a controller, but meh.

How to block until an event is fired in c#

If the current method is async then you can use TaskCompletionSource. Create a field that the event handler and the current method can access.

    TaskCompletionSource<bool> tcs = null;

    private async void Button_Click(object sender, RoutedEventArgs e)
    {
        tcs = new TaskCompletionSource<bool>();
        await tcs.Task;
        WelcomeTitle.Text = "Finished work";
    }

    private void Button_Click2(object sender, RoutedEventArgs e)
    {
        tcs?.TrySetResult(true);
    }

This example uses a form that has a textblock named WelcomeTitle and two buttons. When the first button is clicked it starts the click event but stops at the await line. When the second button is clicked the task is completed and the WelcomeTitle text is updated. If you want to timeout as well then change

await tcs.Task;

to

await Task.WhenAny(tcs.Task, Task.Delay(25000));
if (tcs.Task.IsCompleted)
    WelcomeTitle.Text = "Task Completed";
else
    WelcomeTitle.Text = "Task Timed Out";

403 Forbidden error when making an ajax Post request in Django framework

You must change your folder chmod 755 and file(.php ,.html) chmod 644.

How to show Snackbar when Activity starts?

Try this

Snackbar.make(findViewById(android.R.id.content), "Got the Result", Snackbar.LENGTH_LONG)
                        .setAction("Submit", mOnClickListener)
                        .setActionTextColor(Color.RED)
                        .show();

In C - check if a char exists in a char array

I believe the original question said:

a character belongs to a list/array of invalid characters

and not:

belongs to a null-terminated string

which, if it did, then strchr would indeed be the most suitable answer. If, however, there is no null termination to an array of chars or if the chars are in a list structure, then you will need to either create a null-terminated string and use strchr or manually iterate over the elements in the collection, checking each in turn. If the collection is small, then a linear search will be fine. A large collection may need a more suitable structure to improve the search times - a sorted array or a balanced binary tree for example.

Pick whatever works best for you situation.

Choosing a file in Python with simple Dialog

Another option to consider is Zenity: http://freecode.com/projects/zenity.

I had a situation where I was developing a Python server application (no GUI component) and hence didn't want to introduce a dependency on any python GUI toolkits, but I wanted some of my debug scripts to be parameterized by input files and wanted to visually prompt the user for a file if they didn't specify one on the command line. Zenity was a perfect fit. To achieve this, invoke "zenity --file-selection" using the subprocess module and capture the stdout. Of course this solution isn't Python-specific.

Zenity supports multiple platforms and happened to already be installed on our dev servers so it facilitated our debugging/development without introducing an unwanted dependency.

Can't find SDK folder inside Android studio path, and SDK manager not opening

So I was trying to root one of my old phones and process required Android SDK. When I searched Android SDK, all i could do was download and install Android Studio. Everything went fine and smooth, till I tried to look for SDK in installation. I could not find it under Android Studio installation. But after a little search on Google and Android Studio configuration on my computer, I was able to find it at

        C:\Users\username\Android\sdk

I hope that helps.

Setting equal heights for div's with jQuery

This is my version of setting blocks in the same hight... For example you have a divthat contains divs with the name "col"

$('.col').parent().each(function() {
    var height = 0,
        column = $(this).find('.col');
    column.each(function() {
        if ($(this).height() > height) height = $(this).height();
    });
    column.height(height);
});

Send data from activity to fragment in Android

Also You can access activity data from fragment:

Activity:

public class MyActivity extends Activity {

    private String myString = "hello";

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

    public String getMyData() {
        return myString;
    }
}

Fragment:

public class MyFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        MyActivity activity = (MyActivity) getActivity();
        String myDataFromActivity = activity.getMyData();
        return view;
    }
}

How to read until EOF from cin in C++

The only way you can read a variable amount of data from stdin is using loops. I've always found that the std::getline() function works very well:

std::string line;
while (std::getline(std::cin, line))
{
    std::cout << line << std::endl;
}

By default getline() reads until a newline. You can specify an alternative termination character, but EOF is not itself a character so you cannot simply make one call to getline().

How Do I Convert an Integer to a String in Excel VBA?

Try the CStr() function

Dim myVal as String;
Dim myNum as Integer;

myVal = "My number is:"
myVal = myVal & CStr(myNum);

ASP.NET Identity's default Password Hasher - How does it work and is it secure?

Because these days ASP.NET is open source, you can find it on GitHub: AspNet.Identity 3.0 and AspNet.Identity 2.0.

From the comments:

/* =======================
 * HASHED PASSWORD FORMATS
 * =======================
 * 
 * Version 2:
 * PBKDF2 with HMAC-SHA1, 128-bit salt, 256-bit subkey, 1000 iterations.
 * (See also: SDL crypto guidelines v5.1, Part III)
 * Format: { 0x00, salt, subkey }
 *
 * Version 3:
 * PBKDF2 with HMAC-SHA256, 128-bit salt, 256-bit subkey, 10000 iterations.
 * Format: { 0x01, prf (UInt32), iter count (UInt32), salt length (UInt32), salt, subkey }
 * (All UInt32s are stored big-endian.)
 */

What is the purpose of Order By 1 in SQL select statement?

Also see:

http://www.techonthenet.com/sql/order_by.php

For a description of order by. I learned something! :)

I've also used this in the past when I wanted to add an indeterminate number of filters to a sql statement. Sloppy I know, but it worked. :P

Conda command is not recognized on Windows 10

In Windows, you will have to set the path to the location where you installed Anaconda3 to.

For me, I installed anaconda3 into C:\Anaconda3. Therefore you need to add C:\Anaconda3 as well as C:\Anaconda3\Scripts\ to your path variable, e.g. set PATH=%PATH%;C:\Anaconda3;C:\Anaconda3\Scripts\.

You can do this via powershell (see above, https://msdn.microsoft.com/en-us/library/windows/desktop/bb776899(v=vs.85).aspx ), or hit the windows key ? enter environment ? choose from settings ? edit environment variables for your account ? select Path variable ? Edit ? New.

To test it, open a new dos shell, and you should be able to use conda commands now. E.g., try conda --version.

Print DIV content by JQuery

You can follow these steps :

  1. wrap the div you want to print into another div.
  2. set the wrapper div display status to none in css.
  3. keep the div you want to print display status as block, anyway it will be hidden as its parent is hidden.
  4. simply call $('SelectorToPrint').printElement();

What's an appropriate HTTP status code to return by a REST API service for a validation failure?

There's a little bit more information about the semantics of these errors in RFC 2616, which documents HTTP 1.1.

Personally, I would probably use 400 Bad Request, but this is just my personal opinion without any factual support.

Chrome not rendering SVG referenced via <img> tag

Adding the width attribute to the [svg] tag (by editing the svg source XML) worked for me: eg:

<!-- This didn't render -->
<svg version="1.1" baseProfile="full" xmlns="http://www.w3.org/2000/svg">
...  
</svg>

<!-- This did -->
<svg version="1.1" baseProfile="full" width="1000" xmlns="http://www.w3.org/2000/svg">
...  
</svg>

T-SQL Subquery Max(Date) and Joins

Here's another way to do it without subqueries. This method will often outperform others, so it's worth testing both methods to see which gives the best performance.

SELECT
     PRT.PartID,
     PRT.PartNumber,
     PRT.Description,
     PRC1.Price,
     PRC1.PriceDate
FROM
     MyParts PRT
LEFT OUTER JOIN MyPrices PRC1 ON
     PRC1.PartID = PRT.PartID
LEFT OUTER JOIN MyPrices PRC2 ON
     PRC2.PartID = PRC1.PartID AND
     PRC2.PriceDate > PRC1.PriceDate
WHERE
     PRC2.PartID IS NULL

This will give multiple results if you have two prices with the same EXACT PriceDate (Most other solutions will do the same). Also, I there is nothing to account for the last price date being in the future. You may want to consider a check for that regardless of which method you end up using.

How to delete a workspace in Perforce (using p4v)?

From the "View" menu, select "Workspaces". You'll see all of the workspaces you've created. Select the workspaces you want to delete and click "Edit" -> "Delete Workspace", or right-click and select "Delete Workspace". If the workspace is "locked" to prevent changes, you'll get an error message.

To unlock the workspace, click "Edit" (or right-click and click "Edit Workspace") to pull up the workspace editor, uncheck the "locked" checkbox, and save your changes. You can delete the workspace once it's unlocked.

In my experience, the workspace will continue to be shown in the drop-down list until you click on it, at which point p4v will figure out you've deleted it and remove it from the list.

How does Java import work?

The classes which you are importing have to be on the classpath. So either the users of your Applet have to have the libraries in the right place or you simply provide those libraries by including them in your jar file. For example like this: Easiest way to merge a release into one JAR file

java.io.FileNotFoundException: the system cannot find the file specified

I have the same problem, but you know why? because I didn't put .txt in the end of my File and so it was File not a textFile, you shoud do just two things:

  1. Put your Text File in the Root Directory (e.x if you have a project called HelloWorld, just right-click on the HelloWorld file in the package Directory and create File
  2. Save as that File with any name that you want but with a .txt in the end of that I guess your problem is solved, but I write it to other peoples know that. Thanks.

Unlocking tables if thread is lost

how will I know that some tables are locked?

You can use SHOW OPEN TABLES command to view locked tables.

how do I unlock tables manually?

If you know the session ID that locked tables - 'SELECT CONNECTION_ID()', then you can run KILL command to terminate session and unlock tables.

How to remove item from a JavaScript object

_x000D_
_x000D_
var test = {'red':'#FF0000', 'blue':'#0000FF'};_x000D_
delete test.blue; // or use => delete test['blue'];_x000D_
console.log(test);
_x000D_
_x000D_
_x000D_

this deletes test.blue

Javascript .querySelector find <div> by innerTEXT

Since there are no limits to the length of text in a data attribute, use data attributes! And then you can use regular css selectors to select your element(s) like the OP wants.

_x000D_
_x000D_
for (const element of document.querySelectorAll("*")) {_x000D_
  element.dataset.myInnerText = element.innerText;_x000D_
}_x000D_
_x000D_
document.querySelector("*[data-my-inner-text='Different text.']").style.color="blue";
_x000D_
<div>SomeText, text continues.</div>_x000D_
<div>Different text.</div>
_x000D_
_x000D_
_x000D_

Ideally you do the data attribute setting part on document load and narrow down the querySelectorAll selector a bit for performance.

Get Selected value of a Combobox

Maybe you'll be able to set the event handlers programmatically, using something like (pseudocode)

sub myhandler(eventsource)
  process(eventsource.value)
end sub

for each cell
  cell.setEventHandler(myHandler)

But i dont know the syntax for achieving this in VB/VBA, or if is even possible.

How to delete all files older than 3 days when "Argument list too long"?

Another solution for the original question, esp. useful if you want to remove only SOME of the older files in a folder, would be smth like this:

find . -name "*.sess" -mtime +100 

and so on.. Quotes block shell wildcards, thus allowing you to "find" millions of files :)

Removing whitespace between HTML elements when using line breaks

You could use CSS. Setting display:block, or float:left on the images will let you have define your own spacing and format the HTML however you want but will affect the layout in ways that might or might not be appropriate.

Otherwise you are dealing with inline content so the HTML formatting is important - as the images will effectively act like words.

Bootstrap 4 navbar color

you can write !important in front of background-color property value like this it will change the color of links.

.nav-link {
    color: white !important;
}

how can I display tooltip or item information on mouse over?

The simplest way to get tooltips in most browsers is to set some text in the title attribute.

eg.

<img src="myimage.jpg" alt="a cat" title="My cat sat on a table" />

produces (hover your mouse over the image):

a cat http://www.imagechicken.com/uploads/1275939952008633500.jpg

Title attributes can be applied to most HTML elements.

Formatting MM/DD/YYYY dates in textbox in VBA

Private Sub txtBoxBDayHim_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
If KeyAscii >= 48 And KeyAscii <= 57 Or KeyAscii = 8 Then 'only numbers and backspace
    If KeyAscii = 8 Then 'if backspace, ignores + "/"
    Else
        If txtBoxBDayHim.TextLength = 10 Then 'limit textbox to 10 characters
        KeyAscii = 0
        Else
            If txtBoxBDayHim.TextLength = 2 Or txtBoxBDayHim.TextLength = 5 Then 'adds / automatically
            txtBoxBDayHim.Text = txtBoxBDayHim.Text + "/"
            End If
        End If
    End If
Else
KeyAscii = 0
End If
End Sub

This works for me. :)

Your code helped me a lot. Thanks!

I'm brazilian and my english is poor, sorry for any mistake.

JPA Criteria API - How to add JOIN clause (as general sentence as possible)

Warning! There's a numbers of errors on the Sun JPA 2 example and the resulting pasted content in Pascal's answer. Please consult this post.

This post and the Sun Java EE 6 JPA 2 example really held back my comprehension of JPA 2. After plowing through the Hibernate and OpenJPA manuals and thinking that I had a good understanding of JPA 2, I still got confused afterwards when returning to this post.

Converting Hexadecimal String to Decimal Integer

You could take advantage of ASCII value for each letter and take off 55, easy and fast:

int asciiOffset = 55;
char hex = Character.toUpperCase('A');  // Only A-F uppercase
int val = hex - asciiOffset;
System.out.println("hexadecimal:" + hex);
System.out.println("decimal:" + val);

Output:
hexadecimal:A
decimal:10

Android Button setOnClickListener Design

Implement Activity with View.OnClickListener like below.

public class MyActivity extends AppCompatActivity implements View.OnClickListener {

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

        Button button = findViewById(R.id.button);
        Button button2 = findViewById(R.id.button2);

        button.setOnClickListener(this);
        button2.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {

        int id = view.getId();

        switch (id) {

            case R.id.button:

                  // Write your code here first button

                break;

             case R.id.button2:

                  // Write your code here for second button

                break;

        }

    }

}

How to pass an event object to a function in Javascript?

  1. Modify the definition of the function check_me as::

     function check_me(ev) {
    
  2. Now you can access the methods and parameters of the event, in your case:

     ev.preventDefault();
    
  3. Then, you have to pass the parameter on the onclick in the inline call::

     <button type="button" onclick="check_me(event);">Click Me!</button>
    

A useful link to understand this.


Full example:

<!DOCTYPE html>
<html lang="en">
  <head>
    <script type="text/javascript">
      function check_me(ev) {
        ev.preventDefault();
        alert("Hello World!")
      }
    </script>
  </head>
  <body>
    <button type="button" onclick="check_me(event);">Click Me!</button>
  </body>
</html>









Alternatives (best practices):

Although the above is the direct answer to the question (passing an event object to an inline event), there are other ways of handling events that keep the logic separated from the presentation

A. Using addEventListener:

<!DOCTYPE html>
<html lang="en">
  <head>
  </head>
  <body>
    <button id='my_button' type="button">Click Me!</button>

    <!-- put the javascript at the end to guarantee that the DOM is ready to use-->
    <script type="text/javascript">
      function check_me(ev) {
        ev.preventDefault();
        alert("Hello World!")
      }
      
      <!-- add the event to the button identified #my_button -->
      document.getElementById("my_button").addEventListener("click", check_me);
    </script>
  </body>
</html>

B. Isolating Javascript:

Both of the above solutions are fine for a small project, or a hackish quick and dirty solution, but for bigger projects, it is better to keep the HTML separated from the Javascript.

Just put this two files in the same folder:

  • example.html:
<!DOCTYPE html>
<html lang="en">
  <head>
  </head>
  <body>
    <button id='my_button' type="button">Click Me!</button>

    <!-- put the javascript at the end to guarantee that the DOM is ready to use-->
    <script type="text/javascript" src="example.js"></script>
  </body>
</html>
  • example.js:
function check_me(ev) {
    ev.preventDefault();
    alert("Hello World!")
}
document.getElementById("my_button").addEventListener("click", check_me);

Increasing (or decreasing) the memory available to R processes

To increase the amount of memory allocated to R you can use memory.limit

memory.limit(size = ...)

Or

memory.size(max = ...)

About the arguments

  • size - numeric. If NA report the memory limit, otherwise request a new limit, in Mb. Only values of up to 4095 are allowed on 32-bit R builds, but see ‘Details’.
  • max - logical. If TRUE the maximum amount of memory obtained from the OS is reported, if FALSE the amount currently in use, if NA the memory limit.

Java recursive Fibonacci sequence

It is a basic sequence that display or get a output of 1 1 2 3 5 8 it is a sequence that the sum of previous number the current number will be display next.

Try to watch link below Java Recursive Fibonacci sequence Tutorial

public static long getFibonacci(int number){
if(number<=1) return number;
else return getFibonacci(number-1) + getFibonacci(number-2);
}

Click Here Watch Java Recursive Fibonacci sequence Tutorial for spoon feeding

What is the correct SQL type to store a .Net Timespan with values > 24:00:00?

There isn't a direct equivalent. Just store it numerically, e.g. number of seconds or something appropriate to your required accuracy.

How to remove white space characters from a string in SQL Server

In that case, it isn't space that is in prefix/suffix.
The 1st row looks OK. Do the following for the contents of 2nd row.

ASCII(RIGHT(ProductAlternateKey, 1))

and

ASCII(LEFT(ProductAlternateKey, 1))

How to listen for 'props' changes

I use props and variables computed properties if I need create logic after to receive the changes

export default {
name: 'getObjectDetail',
filters: {},
components: {},
props: {
    objectDetail: {
      type: Object,
      required: true
    }
},
computed: {
    _objectDetail: {
        let value = false
        ...

        if (someValidation)
        ...
    }
}

How do I write out a text file in C# with a code page other than UTF-8?

Change the Encoding of the stream writer. It's a property.

http://msdn.microsoft.com/en-us/library/system.io.streamwriter.encoding.aspx

So:

sw.Encoding = Encoding.GetEncoding(28591);

Prior to writing to the stream.

How to read and write to a text file in C++?

Default c++ mechanism for file IO is called streams. Streams can be of three flavors: input, output and inputoutput. Input streams act like sources of data. To read data from an input stream you use >> operator:

istream >> my_variable; //This code will read a value from stream into your variable.

Operator >> acts different for different types. If in the example above my_variable was an int, then a number will be read from the strem, if my_variable was a string, then a word would be read, etc. You can read more then one value from the stream by writing istream >> a >> b >> c; where a, b and c would be your variables.

Output streams act like sink to which you can write your data. To write your data to a stream, use << operator.

ostream << my_variable; //This code will write a value from your variable into stream.

As with input streams, you can write several values to the stream by writing something like this:

ostream << a << b << c;

Obviously inputoutput streams can act as both.

In your code sample you use cout and cin stream objects. cout stands for console-output and cin for console-input. Those are predefined streams for interacting with default console.

To interact with files, you need to use ifstream and ofstream types. Similar to cin and cout, ifstream stands for input-file-stream and ofstream stands for output-file-stream.

Your code might look like this:

#include <iostream>
#include <fstream>

using namespace std;

int start()
{
    cout << "Welcome...";

    // do fancy stuff

    return 0;
}

int main ()
{
    string usreq, usr, yn, usrenter;

    cout << "Is this your first time using TEST" << endl;
    cin >> yn;
    if (yn == "y")
    {
        ifstream iusrfile;
        ofstream ousrfile;
        iusrfile.open("usrfile.txt");
        iusrfile >> usr;
        cout << iusrfile; // I'm not sure what are you trying to do here, perhaps print iusrfile contents?
        iusrfile.close();
        cout << "Please type your Username. \n";
        cin >> usrenter;
        if (usrenter == usr)
        {
            start ();
        }
    }
    else
    {
        cout << "THAT IS NOT A REGISTERED USERNAME.";
    }

    return 0;
}

For further reading you might want to look at c++ I/O reference

Find all storage devices attached to a Linux machine

Using HAL (kernel 2.6.17 and up):


#! /bin/bash
hal-find-by-property --key volume.fsusage --string filesystem |
while read udi ; do
    # ignore optical discs
    if [[ "$(hal-get-property --udi $udi --key volume.is_disc)" == "false" ]]; then
        dev=$(hal-get-property --udi $udi --key block.device)   
        fs=$(hal-get-property --udi $udi --key volume.fstype) 
        echo $dev": "$fs
    fi 
done

Float to String format specifier

Firstly, as Etienne says, float in C# is Single. It is just the C# keyword for that data type.

So you can definitely do this:

float f = 13.5f;
string s = f.ToString("R");

Secondly, you have referred a couple of times to the number's "format"; numbers don't have formats, they only have values. Strings have formats. Which makes me wonder: what is this thing you have that has a format but is not a string? The closest thing I can think of would be decimal, which does maintain its own precision; however, calling simply decimal.ToString should have the effect you want in that case.

How about including some example code so we can see exactly what you're doing, and why it isn't achieving what you want?

AngularJS : When to use service instead of factory

The concept for all these providers is much simpler than it initially appears. If you dissect a provider you and pull out the different parts it becomes very clear.

To put it simply each one of these providers is a specialized version of the other, in this order: provider > factory > value / constant / service.

So long the provider does what you can you can use the provider further down the chain which would result in writing less code. If it doesn't accomplish what you want you can go up the chain and you'll just have to write more code.

This image illustrates what I mean, in this image you will see the code for a provider, with the portions highlighted showing you which portions of the provider could be used to create a factory, value, etc instead.

AngularJS providers, factories, services, etc are all the same thing
(source: simplygoodcode.com)

For more details and examples from the blog post where I got the image from go to: http://www.simplygoodcode.com/2015/11/the-difference-between-service-provider-and-factory-in-angularjs/

Pylint "unresolved import" error in Visual Studio Code

First make sure that you've installed the plugin, but it's likely that the workspace directory isn't properly set. Just check Pylint and edit the underlying settings.json file.

{
    "python.pythonPath": "/usr/local/bin/python3",
    "git.ignoreLimitWarning": true
}

Creating a PDF from a RDLC Report in the Background

You don't need to have a reportViewer control anywhere - you can create the LocalReport on the fly:

var lr = new LocalReport
{
    ReportPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? @"C:\", "Reports", "PathOfMyReport.rdlc"),
    EnableExternalImages = true
};

lr.DataSources.Add(new ReportDataSource("NameOfMyDataSet", model));

string mimeType, encoding, extension;

Warning[] warnings;
string[] streams;
var renderedBytes = lr.Render
    (
        "PDF",
        @"<DeviceInfo><OutputFormat>PDF</OutputFormat><HumanReadablePDF>False</HumanReadablePDF></DeviceInfo>",
        out mimeType,
        out encoding,
        out extension,
        out streams,
        out warnings
    );

var saveAs = string.Format("{0}.pdf", Path.Combine(tempPath, "myfilename"));

var idx = 0;
while (File.Exists(saveAs))
{
    idx++;
    saveAs = string.Format("{0}.{1}.pdf", Path.Combine(tempPath, "myfilename"), idx);
}

using (var stream = new FileStream(saveAs, FileMode.Create, FileAccess.Write))
{
    stream.Write(renderedBytes, 0, renderedBytes.Length);
    stream.Close();
}

lr.Dispose();

You can also add parameters: (lr.SetParameter()), handle subreports: (lr.SubreportProcessing+=YourHandler), or pretty much anything you can think of.

assembly to compare two numbers

input password program
.modle small
.stack 100h
.data
s pasword db 34
input pasword db "enter pasword","$"
valid db ?
invalid db?
.code
mov ax, @ data 
mov db, ax
mov ah,09h
mov dx, offest s pasword
int 21h
mov ah, 01h
cmp al, s pasword
je v
jmp nv
v:
mov ah, 09h
mov dx, offset valid 
int 21h
nv:
mov ah, 09h
mov dx, offset invalid 
int 21h
mov ah, 04ch 
int 21
end 

Remove file from SVN repository without deleting local copy

In TortoiseSVN, you can also Shift + right-click to get a menu that includes "Delete (keep local)".

How to normalize a histogram in MATLAB?

There is an excellent three part guide for Histogram Adjustments in MATLAB (broken original link, archive.org link), the first part is on Histogram Stretching.

IP to Location using Javascript

A rather inexpensive option would be to use the ipdata.co API, it's free upto 1500 requests a day.

This answer uses a 'test' API Key that is very limited and only meant for testing a few calls. Signup for your own Free API Key and get up to 1500 requests daily for development.

_x000D_
_x000D_
$.get("https://api.ipdata.co?api-key=test", function (response) {_x000D_
    $("#ip").html("IP: " + response.ip);_x000D_
    $("#city").html(response.city + ", " + response.region);_x000D_
    $("#response").html(JSON.stringify(response, null, 4));_x000D_
}, "jsonp");
_x000D_
<h1><a href="https://ipdata.co">ipdata.co</a> - IP geolocation API</h1>_x000D_
_x000D_
<div id="ip"></div>_x000D_
<div id="city"></div>_x000D_
<pre id="response"></pre>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

View the Fiddle at https://jsfiddle.net/ipdata/6wtf0q4g/922/

how to detect search engine bots with php?

I use this function ... part of the regex comes from prestashop but I added some more bot to it.

    public function isBot()
{
    $bot_regex = '/BotLink|bingbot|AhrefsBot|ahoy|AlkalineBOT|anthill|appie|arale|araneo|AraybOt|ariadne|arks|ATN_Worldwide|Atomz|bbot|Bjaaland|Ukonline|borg\-bot\/0\.9|boxseabot|bspider|calif|christcrawler|CMC\/0\.01|combine|confuzzledbot|CoolBot|cosmos|Internet Cruiser Robot|cusco|cyberspyder|cydralspider|desertrealm, desert realm|digger|DIIbot|grabber|downloadexpress|DragonBot|dwcp|ecollector|ebiness|elfinbot|esculapio|esther|fastcrawler|FDSE|FELIX IDE|ESI|fido|H?m?h?kki|KIT\-Fireball|fouineur|Freecrawl|gammaSpider|gazz|gcreep|golem|googlebot|griffon|Gromit|gulliver|gulper|hambot|havIndex|hotwired|htdig|iajabot|INGRID\/0\.1|Informant|InfoSpiders|inspectorwww|irobot|Iron33|JBot|jcrawler|Teoma|Jeeves|jobo|image\.kapsi\.net|KDD\-Explorer|ko_yappo_robot|label\-grabber|larbin|legs|Linkidator|linkwalker|Lockon|logo_gif_crawler|marvin|mattie|mediafox|MerzScope|NEC\-MeshExplorer|MindCrawler|udmsearch|moget|Motor|msnbot|muncher|muninn|MuscatFerret|MwdSearch|sharp\-info\-agent|WebMechanic|NetScoop|newscan\-online|ObjectsSearch|Occam|Orbsearch\/1\.0|packrat|pageboy|ParaSite|patric|pegasus|perlcrawler|phpdig|piltdownman|Pimptrain|pjspider|PlumtreeWebAccessor|PortalBSpider|psbot|Getterrobo\-Plus|Raven|RHCS|RixBot|roadrunner|Robbie|robi|RoboCrawl|robofox|Scooter|Search\-AU|searchprocess|Senrigan|Shagseeker|sift|SimBot|Site Valet|skymob|SLCrawler\/2\.0|slurp|ESI|snooper|solbot|speedy|spider_monkey|SpiderBot\/1\.0|spiderline|nil|suke|http:\/\/www\.sygol\.com|tach_bw|TechBOT|templeton|titin|topiclink|UdmSearch|urlck|Valkyrie libwww\-perl|verticrawl|Victoria|void\-bot|Voyager|VWbot_K|crawlpaper|wapspider|WebBandit\/1\.0|webcatcher|T\-H\-U\-N\-D\-E\-R\-S\-T\-O\-N\-E|WebMoose|webquest|webreaper|webs|webspider|WebWalker|wget|winona|whowhere|wlm|WOLP|WWWC|none|XGET|Nederland\.zoek|AISearchBot|woriobot|NetSeer|Nutch|YandexBot|YandexMobileBot|SemrushBot|FatBot|MJ12bot|DotBot|AddThis|baiduspider|SeznamBot|mod_pagespeed|CCBot|openstat.ru\/Bot|m2e/i';
    $userAgent = empty($_SERVER['HTTP_USER_AGENT']) ? FALSE : $_SERVER['HTTP_USER_AGENT'];
    $isBot = !$userAgent || preg_match($bot_regex, $userAgent);

    return $isBot;
}

Anyway take care that some bots uses browser like user agent to fake their identity
( I got many russian ip that has this behaviour on my site )

One distinctive feature of most of the bot is that they don't carry any cookie and so no session is attached to them.
( I am not sure how but this is for sure the best way to track them )

Access-Control-Allow-Origin: * in tomcat

Change this:

<init-param>
    <param-name>cors.supportedHeaders</param-name>
    <param-value>Content-Type, Last-Modified</param-value>
</init-param>

To this

<init-param>
    <param-name>cors.supportedHeaders</param-name>
    <param-value>Accept, Origin, X-Requested-With, Content-Type, Last-Modified</param-value>
</init-param>

I had to do this to get anything to work.

How to make Java work with SQL Server?

The driver you are using is the MS SQL server 2008 driver (sqljdbc4.jar). As stated in the MSDN page it requires Java 6+ to work.

http://msdn.microsoft.com/en-us/library/ms378526.aspx

sqljdbc4.jar class library requires a Java Runtime Environment (JRE) of version 6.0 or later.

I'd suggest using the 2005 driver which I beleive is in (sqljdbc.jar) or as Oxbow_Lakes says try the jTDS driver (http://jtds.sourceforge.net/).

automating telnet session using bash scripts

Play with tcpdump or wireshark and see what commands are sent to the server itself

Try this

printf (printf "$username\r\n$password\r\nwhoami\r\nexit\r\n") | ncat $target 23

Some servers require a delay with the password as it does not hold lines on the stack

printf (printf "$username\r\n";sleep 1;printf "$password\r\nwhoami\r\nexit\r\n") | ncat $target 23**

How to check the version before installing a package using apt-get?

As posted somewhere else, this works, too:

apt-cache madison <package_name>

Change default date time format on a single database in SQL Server

You can only change the language on the whole server, not individual databases. However if you need to support the UK you can run the following command before all inputs and outputs:

set language 'british english'

Or if you are having issues entering datatimes from your application you might want to consider a universal input type such as

1-Dec-2008

jquery 3.0 url.indexOf error

@choz answer is the correct way. If you have many usages and want to make sure it works everywhere without changes you can add these small migration-snippet:

/* Migration jQuery from 1.8 to 3.x */
jQuery.fn.load = function (callback) {
    var el = $(this);

    el.on('load', callback);

    return el;
};

In this case you got no erros on other nodes e.g. on $image like in @Korsmakolnikov answer!

const $image = $('img.image').load(function() {
  $(this).doSomething();
});

$image.doSomethingElseWithTheImage();

mysql alphabetical order

but result showing all records starting with a or c or d i want to show records only starting with b

You should use WHERE in that case:

select name from user where name = 'b' order by name

If you want to allow regex, you can use the LIKE operator there too if you want. Example:

select name from user where name like 'b%' order by name

That will select records starting with b. Following query on the other hand will select all rows where b is found anywhere in the column:

select name from user where name like '%b%' order by name

Default values in a C Struct

You could address the problem with an X-Macro

You would change your struct definition into:

#define LIST_OF_foo_MEMBERS \
    X(int,id) \
    X(int,route) \
    X(int,backup_route) \
    X(int,current_route)


#define X(type,name) type name;
struct foo {
    LIST_OF_foo_MEMBERS 
};
#undef X

And then you would be able to easily define a flexible function that sets all fields to dont_care.

#define X(type,name) in->name = dont_care;    
void setFooToDontCare(struct foo* in) {
    LIST_OF_foo_MEMBERS 
}
#undef X

Following the discussion here, one could also define a default value in this way:

#define X(name) dont_care,
const struct foo foo_DONT_CARE = { LIST_OF_STRUCT_MEMBERS_foo };
#undef X

Which translates into:

const struct foo foo_DONT_CARE = {dont_care, dont_care, dont_care, dont_care,};

And use it as in hlovdal answer, with the advantage that here maintenance is easier, i.e. changing the number of struct members will automatically update foo_DONT_CARE. Note that the last "spurious" comma is acceptable.

I first learned the concept of X-Macros when I had to address this problem.

It is extremely flexible to new fields being added to the struct. If you have different data types, you could define different dont_care values depending on the data type: from here, you could take inspiration from the function used to print the values in the second example.

If you are ok with an all int struct, then you could omit the data type from LIST_OF_foo_MEMBERS and simply change the X function of the struct definition into #define X(name) int name;

ORA-00918: column ambiguously defined in SELECT *

A query's projection can only have one instance of a given name. As your WHERE clause shows, you have several tables with a column called ID. Because you are selecting * your projection will have several columns called ID. Or it would have were it not for the compiler hurling ORA-00918.

The solution is quite simple: you will have to expand the projection to explicitly select named columns. Then you can either leave out the duplicate columns, retaining just (say) COACHES.ID or use column aliases: coaches.id as COACHES_ID.

Perhaps that strikes you as a lot of typing, but it is the only way. If it is any comfort, SELECT * is regarded as bad practice in production code: explicitly named columns are much safer.

How Should I Declare Foreign Key Relationships Using Code First Entity Framework (4.1) in MVC3?

If you have an Order class, adding a property that references another class in your model, for instance Customer should be enough to let EF know there's a relationship in there:

public class Order
{
    public int ID { get; set; }

    // Some other properties

    // Foreign key to customer
    public virtual Customer Customer { get; set; }
}

You can always set the FK relation explicitly:

public class Order
{
    public int ID { get; set; }

    // Some other properties

    // Foreign key to customer
    [ForeignKey("Customer")]
    public string CustomerID { get; set; }
    public virtual Customer Customer { get; set; }
}

The ForeignKeyAttribute constructor takes a string as a parameter: if you place it on a foreign key property it represents the name of the associated navigation property. If you place it on the navigation property it represents the name of the associated foreign key.

What this means is, if you where to place the ForeignKeyAttribute on the Customer property, the attribute would take CustomerID in the constructor:

public string CustomerID { get; set; }
[ForeignKey("CustomerID")]
public virtual Customer Customer { get; set; }

EDIT based on Latest Code You get that error because of this line:

[ForeignKey("Parent")]
public Patient Patient { get; set; }

EF will look for a property called Parent to use it as the Foreign Key enforcer. You can do 2 things:

1) Remove the ForeignKeyAttribute and replace it with the RequiredAttribute to mark the relation as required:

[Required]
public virtual Patient Patient { get; set; }

Decorating a property with the RequiredAttribute also has a nice side effect: The relation in the database is created with ON DELETE CASCADE.

I would also recommend making the property virtual to enable Lazy Loading.

2) Create a property called Parent that will serve as a Foreign Key. In that case it probably makes more sense to call it for instance ParentID (you'll need to change the name in the ForeignKeyAttribute as well):

public int ParentID { get; set; }

In my experience in this case though it works better to have it the other way around:

[ForeignKey("Patient")]
public int ParentID { get; set; }

public virtual Patient Patient { get; set; }

str_replace with array

str_replace with arrays just performs all the replacements sequentially. Use strtr instead to do them all at once:

$new_message = strtr($message, 'lmnopq...', 'abcdef...');

Why won't eclipse switch the compiler to Java 8?

I had the same problem even though I had:

  • a freshly downloaded JDK 1.8.0

  • JAVA_HOME is set

  • java -version on command line reports 1.8

  • Java in control panel is set to 1.8

  • downloaded Eclipse Mars

Eclipse only let me choose a compiler compliance level op to 1.7 in the compiler preferences, even though my installed JRE is 1.8.0. I also couldn't see a 1.8 in the Execution Environments underneath Installed JREs, only a JavaSE-1.7 (which I haven't even got installed!). When I clicked on that, it shows "jdk1.8.0" as a compatible JRE, so I selected that, but still no change.

Then I unzipped Eclipse Mars into a brand new directory, created a new project, and now I can select 1.8, hurrah! That greatly reduced the "Duplicate methods named spliterator..." errors I was getting when compiling my code under Java 1.8, however, there is still one left:

Duplicate default methods named spliterator with the parameters () and () are inherited from the types List and Set.

However, that's likely because I'm extending AbstractList and implementing Set, so I've fixed that for now by removing the implements Set because it doesn't really add anything in my case (other than signifying that my collection has only unique elements)

Regular Expression to find a string included between two characters while EXCLUDING the delimiters

This one specifically works for javascript's regular expression parser /[^[\]]+(?=])/g

just run this in the console

var regex = /[^[\]]+(?=])/g;
var str = "This is a test string [more or less]";
var match = regex.exec(str);
match;

Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null

i solved the problem i exlained...for example in the file we render the other component,other component name is same with me method of current component such as:

const Login = () => {

}

render(
  <Login/>
)

..for solve this we must change the method name

Microsoft Excel ActiveX Controls Disabled?

Here is the best answer that I have found on the Microsoft Excel Support Team Blog

For some users, Forms Controls (FM20.dll) are no longer working as expected after installing December 2014 updates. Issues are experienced at times such as when they open files with existing VBA projects using forms controls, try to insert a forms control in to a new worksheet or run third party software that may use these components.

You may received errors such as:

"Cannot insert object" "Object library invalid or contains references to object definitions that could not be found"

Additionally, you may be unable to use or change properties of an ActiveX control on a worksheet or receive an error when trying to refer to an ActiveX control as a member of a worksheet via code. Steps to follow after the update:

To resolve this issue, you must delete the cached versions of the control type libraries (extender files) on the client computer. To do this, you must search your hard disk for files that have the ".exd" file name extension and delete all the .exd files that you find. These .exd files will be re-created automatically when you use the new controls the next time that you use VBA. These extender files will be under the user's profile and may also be in other locations, such as the following:

%appdata%\Microsoft\forms

%temp%\Excel8.0

%temp%\VBE

Scripting solution:

Because this problem may affect more than one machine, it is also possible to create a scripting solution to delete the EXD files and run the script as part of the logon process using a policy. The script you would need should contain the following lines and would need to be run for each USER as the .exd files are USER specific.

del %temp%\vbe\*.exd

del %temp%\excel8.0\*.exd

del %appdata%\microsoft\forms\*.exd

del %appdata%\microsoft\local\*.exd

del %appdata%\Roaming\microsoft\forms\*.exd

del %temp%\word8.0\*.exd

del %temp%\PPT11.0\*.exd

Additional step:

If the steps above do not resolve your issue, another step that can be tested (see warning below):

  1. On a fully updated machine and after removing the .exd files, open the file in Excel with edit permissions.

    Open Visual Basic for Applications > modify the project by adding a comment or edit of some kind to any code module > Debug > Compile VBAProject.

    Save and reopen the file. Test for resolution. If resolved, provide this updated project to additional users.

    Warning: If this step resolves your issue, be aware that after deploying this updated project to the other users, these users will also need to have the updates applied on their systems and .exd files removed as well.

If this does not resolve your issue, it may be a different issue and further troubleshooting may be necessary.

Microsoft is currently working on this issue. Watch the blog for updates.

Source

How do I create a transparent Activity on Android?

Just add the following line to the activity tag in your manifest file that needs to look transparent.

android:theme="@android:style/Theme.Translucent"

Get last dirname/filename in a file path argument in Bash

Bash can get the last part of a path without having to call the external basename:

subdir="/path/to/whatever/${1##*/}"

Python truncate a long string

info = data[:min(len(data), 75)

GROUP_CONCAT ORDER BY

You can use ORDER BY inside the GROUP_CONCAT function in this way:

SELECT li.client_id, group_concat(li.percentage ORDER BY li.views ASC) AS views, 
group_concat(li.percentage ORDER BY li.percentage ASC) 
FROM li GROUP BY client_id

Is multiplication and division using shift operators in C actually faster?

I too wanted to see if I could Beat the House. this is a more general bitwise for any-number by any number multiplication. the macros I made are about 25% more to twice as slower than normal * multiplication. as said by others if it's close to a multiple of 2 or made up of few multiples of 2 you might win. like X*23 made up of (X<<4)+(X<<2)+(X<<1)+X is going to be slower then X*65 made up of (X<<6)+X.

#include <stdio.h>
#include <time.h>

#define MULTIPLYINTBYMINUS(X,Y) (-((X >> 30) & 1)&(Y<<30))+(-((X >> 29) & 1)&(Y<<29))+(-((X >> 28) & 1)&(Y<<28))+(-((X >> 27) & 1)&(Y<<27))+(-((X >> 26) & 1)&(Y<<26))+(-((X >> 25) & 1)&(Y<<25))+(-((X >> 24) & 1)&(Y<<24))+(-((X >> 23) & 1)&(Y<<23))+(-((X >> 22) & 1)&(Y<<22))+(-((X >> 21) & 1)&(Y<<21))+(-((X >> 20) & 1)&(Y<<20))+(-((X >> 19) & 1)&(Y<<19))+(-((X >> 18) & 1)&(Y<<18))+(-((X >> 17) & 1)&(Y<<17))+(-((X >> 16) & 1)&(Y<<16))+(-((X >> 15) & 1)&(Y<<15))+(-((X >> 14) & 1)&(Y<<14))+(-((X >> 13) & 1)&(Y<<13))+(-((X >> 12) & 1)&(Y<<12))+(-((X >> 11) & 1)&(Y<<11))+(-((X >> 10) & 1)&(Y<<10))+(-((X >> 9) & 1)&(Y<<9))+(-((X >> 8) & 1)&(Y<<8))+(-((X >> 7) & 1)&(Y<<7))+(-((X >> 6) & 1)&(Y<<6))+(-((X >> 5) & 1)&(Y<<5))+(-((X >> 4) & 1)&(Y<<4))+(-((X >> 3) & 1)&(Y<<3))+(-((X >> 2) & 1)&(Y<<2))+(-((X >> 1) & 1)&(Y<<1))+(-((X >> 0) & 1)&(Y<<0))
#define MULTIPLYINTBYSHIFT(X,Y) (((((X >> 30) & 1)<<31)>>31)&(Y<<30))+(((((X >> 29) & 1)<<31)>>31)&(Y<<29))+(((((X >> 28) & 1)<<31)>>31)&(Y<<28))+(((((X >> 27) & 1)<<31)>>31)&(Y<<27))+(((((X >> 26) & 1)<<31)>>31)&(Y<<26))+(((((X >> 25) & 1)<<31)>>31)&(Y<<25))+(((((X >> 24) & 1)<<31)>>31)&(Y<<24))+(((((X >> 23) & 1)<<31)>>31)&(Y<<23))+(((((X >> 22) & 1)<<31)>>31)&(Y<<22))+(((((X >> 21) & 1)<<31)>>31)&(Y<<21))+(((((X >> 20) & 1)<<31)>>31)&(Y<<20))+(((((X >> 19) & 1)<<31)>>31)&(Y<<19))+(((((X >> 18) & 1)<<31)>>31)&(Y<<18))+(((((X >> 17) & 1)<<31)>>31)&(Y<<17))+(((((X >> 16) & 1)<<31)>>31)&(Y<<16))+(((((X >> 15) & 1)<<31)>>31)&(Y<<15))+(((((X >> 14) & 1)<<31)>>31)&(Y<<14))+(((((X >> 13) & 1)<<31)>>31)&(Y<<13))+(((((X >> 12) & 1)<<31)>>31)&(Y<<12))+(((((X >> 11) & 1)<<31)>>31)&(Y<<11))+(((((X >> 10) & 1)<<31)>>31)&(Y<<10))+(((((X >> 9) & 1)<<31)>>31)&(Y<<9))+(((((X >> 8) & 1)<<31)>>31)&(Y<<8))+(((((X >> 7) & 1)<<31)>>31)&(Y<<7))+(((((X >> 6) & 1)<<31)>>31)&(Y<<6))+(((((X >> 5) & 1)<<31)>>31)&(Y<<5))+(((((X >> 4) & 1)<<31)>>31)&(Y<<4))+(((((X >> 3) & 1)<<31)>>31)&(Y<<3))+(((((X >> 2) & 1)<<31)>>31)&(Y<<2))+(((((X >> 1) & 1)<<31)>>31)&(Y<<1))+(((((X >> 0) & 1)<<31)>>31)&(Y<<0))
int main()
{
    int randomnumber=23;
    int randomnumber2=23;
    int checknum=23;
    clock_t start, diff;
    srand(time(0));
    start = clock();
    for(int i=0;i<1000000;i++)
    {
        randomnumber = rand() % 10000;
        randomnumber2 = rand() % 10000;
        checknum=MULTIPLYINTBYMINUS(randomnumber,randomnumber2);
        if (checknum!=randomnumber*randomnumber2)
        {
            printf("s %i and %i and %i",checknum,randomnumber,randomnumber2);
        }
    }
    diff = clock() - start;
    int msec = diff * 1000 / CLOCKS_PER_SEC;
    printf("MULTIPLYINTBYMINUS Time %d milliseconds", msec);
    start = clock();
    for(int i=0;i<1000000;i++)
    {
        randomnumber = rand() % 10000;
        randomnumber2 = rand() % 10000;
        checknum=MULTIPLYINTBYSHIFT(randomnumber,randomnumber2);
        if (checknum!=randomnumber*randomnumber2)
        {
            printf("s %i and %i and %i",checknum,randomnumber,randomnumber2);
        }
    }
    diff = clock() - start;
    msec = diff * 1000 / CLOCKS_PER_SEC;
    printf("MULTIPLYINTBYSHIFT Time %d milliseconds", msec);
    start = clock();
    for(int i=0;i<1000000;i++)
    {
        randomnumber = rand() % 10000;
        randomnumber2 = rand() % 10000;
        checknum= randomnumber*randomnumber2;
        if (checknum!=randomnumber*randomnumber2)
        {
            printf("s %i and %i and %i",checknum,randomnumber,randomnumber2);
        }
    }
    diff = clock() - start;
    msec = diff * 1000 / CLOCKS_PER_SEC;
    printf("normal * Time %d milliseconds", msec);
    return 0;
}

Passing arrays as parameters in bash

function aecho {
  set "$1[$2]"
  echo "${!1}"
}

Example

$ foo=(dog cat bird)

$ aecho foo 1
cat

Create URL from a String

URL url = new URL(yourUrl, "/api/v1/status.xml");

According to the javadocs this constructor just appends whatever resource to the end of your domain, so you would want to create 2 urls:

URL domain = new URL("http://example.com");
URL url = new URL(domain + "/files/resource.xml");

Sources: http://docs.oracle.com/javase/6/docs/api/java/net/URL.html

Python - Dimension of Data Frame

Summary of all ways to get info on dimensions of DataFrame or Series

There are a number of ways to get information on the attributes of your DataFrame or Series.

Create Sample DataFrame and Series

df = pd.DataFrame({'a':[5, 2, np.nan], 'b':[ 9, 2, 4]})
df

     a  b
0  5.0  9
1  2.0  2
2  NaN  4

s = df['a']
s

0    5.0
1    2.0
2    NaN
Name: a, dtype: float64

shape Attribute

The shape attribute returns a two-item tuple of the number of rows and the number of columns in the DataFrame. For a Series, it returns a one-item tuple.

df.shape
(3, 2)

s.shape
(3,)

len function

To get the number of rows of a DataFrame or get the length of a Series, use the len function. An integer will be returned.

len(df)
3

len(s)
3

size attribute

To get the total number of elements in the DataFrame or Series, use the size attribute. For DataFrames, this is the product of the number of rows and the number of columns. For a Series, this will be equivalent to the len function:

df.size
6

s.size
3

ndim attribute

The ndim attribute returns the number of dimensions of your DataFrame or Series. It will always be 2 for DataFrames and 1 for Series:

df.ndim
2

s.ndim
1

The tricky count method

The count method can be used to return the number of non-missing values for each column/row of the DataFrame. This can be very confusing, because most people normally think of count as just the length of each row, which it is not. When called on a DataFrame, a Series is returned with the column names in the index and the number of non-missing values as the values.

df.count() # by default, get the count of each column

a    2
b    3
dtype: int64


df.count(axis='columns') # change direction to get count of each row

0    2
1    2
2    1
dtype: int64

For a Series, there is only one axis for computation and so it just returns a scalar:

s.count()
2

Use the info method for retrieving metadata

The info method returns the number of non-missing values and data types of each column

df.info()

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 2 columns):
a    2 non-null float64
b    3 non-null int64
dtypes: float64(1), int64(1)
memory usage: 128.0 bytes

Get index of a key/value pair in a C# dictionary based on the value

In your comment to max's answer, you say that what you really wanted to get is the key in, and not the index of, the KeyValuePair that contains a certain value. You could edit your question to make it more clear.

It is worth pointing out (EricM has touched upon this in his answer) that a value might appear more than once in the dictionary, in which case one would have to think which key he would like to get: e.g. the first that comes up, the last, all of them?

If you are sure that each key has a unique value, you could have another dictionary, with the values from the first acting as keys and the previous keys acting as values. Otherwise, this second dictionary idea (suggested by Jon Skeet) will not work, as you would again have to think which of all the possible keys to use as value in the new dictionary.

If you were asking about the index, though, EricM's answer would be OK. Then you could get the KeyValuePair in question by using:

yourDictionary.ElementAt(theIndexYouFound);

provided that you do not add/remove things in yourDictionary.

PS: I know it's been almost 7 years now, but what the heck. I thought it best to formulate my answer as addressing the OP, but of course by now one can say it is an answer for just about anyone else but the OP. Fully aware of that, thank you.

How to center links in HTML

Try doing a nav element with a ul element. Mine has a main above but I don't think you need it.

<main>
<nav>
<ul><li><a href="http//www.google.com">search</a>
<li><a href="http//www.google.com">search</a>
<li><a href="http//www.google.com">search</a>

The code is something like this.
When ever I put in the code it wouldn't work right so you need to fill in the blank,
then center it.

main
nav
ul> li> a>: href="link of choice":name of link:/a>

MySql with JAVA error. The last packet sent successfully to the server was 0 milliseconds ago

It seems that your Java code is using IPv6 instead of IPv4. Please try to use 127.0.0.1 instead of localhost. Ex.: Your connection string should be

jdbc:mysql://127.0.0.1:3306/expeditor?zeroDateTimeBehavior=convertToNull&user=root&password=onelife

P.S.: Please update the URL connection string.

How do I format axis number format to thousands with a comma in matplotlib?

I always find myself on this same page everytime I try to do this. Sure, the other answers get the job done, but aren't easy to remember for next time! ex: import ticker and use lambda, custom def, etc.

Here's a simple solution if you have an axes named ax:

ax.set_yticklabels(['{:,}'.format(int(x)) for x in ax.get_yticks().tolist()])

Update data on a page without refreshing

In general, if you don't know how something works, look for an example which you can learn from.

For this problem, consider this DEMO

You can see loading content with AJAX is very easily accomplished with jQuery:

$(function(){
    // don't cache ajax or content won't be fresh
    $.ajaxSetup ({
        cache: false
    });
    var ajax_load = "<img src='http://automobiles.honda.com/images/current-offers/small-loading.gif' alt='loading...' />";

    // load() functions
    var loadUrl = "http://fiddle.jshell.net/deborah/pkmvD/show/";
    $("#loadbasic").click(function(){
        $("#result").html(ajax_load).load(loadUrl);
    });

// end  
});

Try to understand how this works and then try replicating it. Good luck.

You can find the corresponding tutorial HERE

Update

Right now the following event starts the ajax load function:

$("#loadbasic").click(function(){
        $("#result").html(ajax_load).load(loadUrl);
    });

You can also do this periodically: How to fire AJAX request Periodically?

(function worker() {
  $.ajax({
    url: 'ajax/test.html', 
    success: function(data) {
      $('.result').html(data);
    },
    complete: function() {
      // Schedule the next request when the current one's complete
      setTimeout(worker, 5000);
    }
  });
})();

I made a demo of this implementation for you HERE. In this demo, every 2 seconds (setTimeout(worker, 2000);) the content is updated.

You can also just load the data immediately:

$("#result").html(ajax_load).load(loadUrl);

Which has THIS corresponding demo.

Error:Execution failed for task ':app:transformClassesWithDexForDebug'

Make sure you aren't using two versions of google service.

For example having:

compile 'com.google.firebase:firebase-messaging:9.8.0'

and

compile 'com.google.firebase:firebase-ads:10.0.0'

Create a new file in git bash

This is a very simple to create file in git bash at first write touch then file name with extension

for example

touch filename.extension

How to make a HTTP PUT request?

My Final Approach:

    public void PutObject(string postUrl, object payload)
        {
            var request = (HttpWebRequest)WebRequest.Create(postUrl);
            request.Method = "PUT";
            request.ContentType = "application/xml";
            if (payload !=null)
            {
                request.ContentLength = Size(payload);
                Stream dataStream = request.GetRequestStream();
                Serialize(dataStream,payload);
                dataStream.Close();
            }

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            string returnString = response.StatusCode.ToString();
        }

public void Serialize(Stream output, object input)
            {
                var ser = new DataContractSerializer(input.GetType());
                ser.WriteObject(output, input);
            }

Remove pattern from string with gsub

Just to point out that there is an approach using functions from the tidyverse, which I find more readable than gsub:

a %>% stringr::str_remove(pattern = ".*_")

Passing multiple variables to another page in url

<a href="deleteshare.php?did=<?php echo "$rowc[id]"; ?>&uid=<?php echo "$id";?>">DELETE</a>

Pass multiple Variable one page to another page

How can I kill whatever process is using port 8080 so that I can vagrant up?

You can also use the Activity Monitor to identify and quit the process using the port.

Assign output to variable in Bash

Same with something more complex...getting the ec2 instance region from within the instance.

INSTANCE_REGION=$(curl -s 'http://169.254.169.254/latest/dynamic/instance-identity/document' | python -c "import sys, json; print json.load(sys.stdin)['region']")

echo $INSTANCE_REGION

Where IN clause in LINQ

This little bit different idea. But it will useful to you. I have used sub query to inside the linq main query.

Problem:

Let say we have document table. Schema as follows schema : document(name,version,auther,modifieddate) composite Keys : name,version

So we need to get latest versions of all documents.

soloution

 var result = (from t in Context.document
                          where ((from tt in Context.document where t.Name == tt.Name
                                orderby tt.Version descending select new {Vesion=tt.Version}).FirstOrDefault()).Vesion.Contains(t.Version)
                          select t).ToList();

Convert string into integer in bash script - "Leading Zero" number error

In Short: In order to deal with "Leading Zero" numbers (any 0 digit that comes before the first non-zero) in bash - Use bc An arbitrary precision calculator language

Example:

a="000001"
b=$(echo $a | bc)
echo $b

Output: 1

From Bash manual:

"bc is a language that supports arbitrary precision numbers with interactive execution of statements. There are some similarities in the syntax to the C programming lan- guage. A standard math library is available by command line option. If requested, the math library is defined before processing any files. bc starts by processing code from all the files listed on the command line in the order listed. After all files have been processed, bc reads from the standard input. All code is executed as it is read. (If a file contains a command to halt the processor, bc will never read from the standard input.)"

A formula to copy the values from a formula to another column

You can use =A4, in case A4 is having long formula

Visual Studio Code - Convert spaces to tabs

There are 3 options in .vscode/settings.json:

// The number of spaces a tab is equal to.
"editor.tabSize": 4,

// Insert spaces when pressing Tab.
"editor.insertSpaces": true,

// When opening a file, `editor.tabSize` and `editor.insertSpaces` will be detected based on the file contents.
"editor.detectIndentation": true

editor.detectIndentation detects it from your file, you have to disable it. If it didn't help, check that you have no settings with higher priority. For example when you save it to User settings it could be overwritten by Workspace settings which are in your project folder.

Update:

You may just open File » Preferences » Settings or use shortcut:

CTRL+, (Windows, Linux)

?+, (Mac)

Update:

Now you have alternative to editing those options manually.
Click on selector Spaces:4 at the bottom-right of the editor:
 Ln44, Col .  [Spaces:4] . UTF-8 with BOM . CTRLF . HTML . :)

When you want to convert existing ws to tab, install extension from Marketplace
EDIT:
To convert existing indentation from spaces to tabs hit Ctrl+Shift+P and type:

>Convert indentation to Tabs

This will change the indentation for your document based on the defined settings to Tabs.

Named capturing groups in JavaScript regex?

ECMAScript 2018 introduces named capturing groups into JavaScript regexes.

Example:

  const auth = 'Bearer AUTHORIZATION_TOKEN'
  const { groups: { token } } = /Bearer (?<token>[^ $]*)/.exec(auth)
  console.log(token) // "Prints AUTHORIZATION_TOKEN"

If you need to support older browsers, you can do everything with normal (numbered) capturing groups that you can do with named capturing groups, you just need to keep track of the numbers - which may be cumbersome if the order of capturing group in your regex changes.

There are only two "structural" advantages of named capturing groups I can think of:

  1. In some regex flavors (.NET and JGSoft, as far as I know), you can use the same name for different groups in your regex (see here for an example where this matters). But most regex flavors do not support this functionality anyway.

  2. If you need to refer to numbered capturing groups in a situation where they are surrounded by digits, you can get a problem. Let's say you want to add a zero to a digit and therefore want to replace (\d) with $10. In JavaScript, this will work (as long as you have fewer than 10 capturing group in your regex), but Perl will think you're looking for backreference number 10 instead of number 1, followed by a 0. In Perl, you can use ${1}0 in this case.

Other than that, named capturing groups are just "syntactic sugar". It helps to use capturing groups only when you really need them and to use non-capturing groups (?:...) in all other circumstances.

The bigger problem (in my opinion) with JavaScript is that it does not support verbose regexes which would make the creation of readable, complex regular expressions a lot easier.

Steve Levithan's XRegExp library solves these problems.

This action could not be completed. Try Again (-22421)

It is probably everything all right with your code/provisioning profiles/Xcode.

I did try once more, and it worked like a charm. I did not change anything.

Please take note that some actions of people replying earlier did take, could not have any effect on this problem but still, it might look like that actions did help. It would work with or without it anyway.

Multiple files upload (Array) with CodeIgniter 2.0

<form method="post" action="<?php echo base_url('submit'); ?>" enctype="multipart/form-data">
    <input type="file" name="userfile[]" id="userfile"  multiple="" accept="image/*">
</form>

MODEL : FilesUpload

class FilesUpload extends CI_Model {

    public function setFiles()
    {
        $name_array = array();
        $count = count($_FILES['userfile']['size']);
        foreach ($_FILES as $key => $value)
            for ($s = 0; $s <= $count - 1; $s++) {
                $_FILES['userfile']['name'] = $value['name'][$s];
                $_FILES['userfile']['type'] = $value['type'][$s];
                $_FILES['userfile']['tmp_name'] = $value['tmp_name'][$s];
                $_FILES['userfile']['error'] = $value['error'][$s];
                $_FILES['userfile']['size'] = $value['size'][$s];

                $config['upload_path'] = 'assets/product/';
                $config['allowed_types'] = 'gif|jpg|png';
                $config['max_size'] = '10000000';
                $config['max_width'] = '51024';
                $config['max_height'] = '5768';

                $this->load->library('upload', $config);
                if (!$this->upload->do_upload()) {
                    $data_error = array('msg' => $this->upload->display_errors());
                    var_dump($data_error);
                } else {
                    $data = $this->upload->data();
                }
                $name_array[] = $data['file_name'];
            }

        $names = implode(',', $name_array);

        return $names;
    }
}

CONTROLER submit

class Submit extends CI_Controller {
    function __construct()
        {
        parent::__construct();
        $this->load->helper(array('html', 'url'));
        }

        public function index()
        {
        $this->load->model('FilesUpload');

        $data = $this->FilesUpload->setFiles();

        echo '<pre>';
        print_r($data);

    }
}

Create a user with all privileges in Oracle

There are 2 differences:

2 methods creating a user and granting some privileges to him

create user userName identified by password;
grant connect to userName;

and

grant connect to userName identified by password;

do exactly the same. It creates a user and grants him the connect role.

different outcome

resource is a role in oracle, which gives you the right to create objects (tables, procedures, some more but no views!). ALL PRIVILEGES grants a lot more of system privileges.

To grant a user all privileges run you first snippet or

grant all privileges to userName identified by password;

Find and kill a process in one line using bash and regex

you can do it with awk and backtics

ps auxf |grep 'python csp_build.py'|`awk '{ print "kill " $2 }'`

$2 in awk prints column 2, and the backtics runs the statement that's printed.

But a much cleaner solution would be for the python process to store it's process id in /var/run and then you can simply read that file and kill it.

Run Jquery function on window events: load, resize, and scroll?

You can use the following. They all wrap the window object into a jQuery object.

Load:

$(window).load(function () {
    topInViewport($("#mydivname"))
});

Resize:

$(window).resize(function () {
   topInViewport($("#mydivname"))
});

Scroll

$(window).scroll(function () {
    topInViewport($("#mydivname"))
});

Or bind to them all using on:

$(window).on("load resize scroll",function(e){
    topInViewport($("#mydivname"))
});

How to apply font anti-alias effects in CSS?

Short answer: You can't.

CSS does not have techniques which affect the rendering of fonts in the browser; only the system can do that.

Obviously, text sharpness can easily be achieved with pixel-dense screens, but if you're using a normal PC that's gonna be hard to achieve.

There are some newer fonts that are smooth but at the sacrifice of it appearing somewhat blurry (look at most of Adobe's fonts, for example). You can also find some smooth-but-blurry-by-design fonts at Google Fonts, however.

There are some new CSS3 techniques for font rendering and text effects though the consistency, performance, and reliability of these techniques vary so largely to the point where you generally shouldn't rely on them too much.

How to convert String to long in Java?

In case you are using the Map with out generic, then you need to convert the value into String and then try to convert to Long. Below is sample code

    Map map = new HashMap();

    map.put("name", "John");
    map.put("time", "9648512236521");
    map.put("age", "25");

    long time = Long.valueOf((String)map.get("time")).longValue() ;
    int age = Integer.valueOf((String)  map.get("aget")).intValue();
    System.out.println(time);
    System.out.println(age);

Write to custom log file from a Bash script

@chepner make a good point that logger is dedicated to logging messages.

I do need to mention that @Thomas Haratyk simply inquired why I didn't simply use echo.

At the time, I didn't know about echo, as I'm learning shell-scripting, but he was right.

My simple solution is now this:

#!/bin/bash
echo "This logs to where I want, but using echo" > /var/log/mycustomlog

The example above will overwrite the file after the >

So, I can append to that file with this:

#!/bin/bash
echo "I will just append to my custom log file" >> /var/log/customlog

Thanks guys!

  • on a side note, it's simply my personal preference to keep my personal logs in /var/log/, but I'm sure there are other good ideas out there. And since I didn't create a daemon, /var/log/ probably isn't the best place for my custom log file. (just saying)

Ruby on Rails: Clear a cached page

rake tmp:cache:clear might be what you're looking for.

Confirm deletion in modal / dialog using Twitter Bootstrap?

I'd realise its a very old question, but since i wondered today for a more efficient method of handling the bootstrap modals. I did some research and found something better then the solutions which are shown above, that can be found at this link:

http://www.petefreitag.com/item/809.cfm

First load the jquery

$(document).ready(function() {
    $('a[data-confirm]').click(function(ev) {
        var href = $(this).attr('href');

        if (!$('#dataConfirmModal').length) {
            $('body').append('<div id="dataConfirmModal" class="modal" role="dialog" aria-labelledby="dataConfirmLabel" aria-hidden="true"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button><h3 id="dataConfirmLabel">Please Confirm</h3></div><div class="modal-body"></div><div class="modal-footer"><button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button><a class="btn btn-primary" id="dataConfirmOK">OK</a></div></div>');
        } 
        $('#dataConfirmModal').find('.modal-body').text($(this).attr('data-confirm'));
        $('#dataConfirmOK').attr('href', href);
        $('#dataConfirmModal').modal({show:true});
        return false;
    });
});

Then just ask any question/confirmation to href:

<a href="/any/url/delete.php?ref=ID" data-confirm="Are you sure you want to delete?">Delete</a>

This way the confirmation modal is a lot more universal and so it can easily be re-used on other parts of your website.

When is it appropriate to use C# partial classes?

Here is a list of some of the advantages of partial classes.

You can separate UI design code and business logic code so that it is easy to read and understand. For example you are developing an web application using Visual Studio and add a new web form then there are two source files, "aspx.cs" and "aspx.designer.cs" . These two files have the same class with the partial keyword. The ".aspx.cs" class has the business logic code while "aspx.designer.cs" has user interface control definition.

When working with automatically generated source, the code can be added to the class without having to recreate the source file. For example you are working with LINQ to SQL and create a DBML file. Now when you drag and drop a table it creates a partial class in designer.cs and all table columns have properties in the class. You need more columns in this table to bind on the UI grid but you don't want to add a new column to the database table so you can create a separate source file for this class that has a new property for that column and it will be a partial class. So that does affect the mapping between database table and DBML entity but you can easily get an extra field. It means you can write the code on your own without messing with the system generated code.

More than one developer can simultaneously write the code for the class.

You can maintain your application better by compacting large classes. Suppose you have a class that has multiple interfaces so you can create multiple source files depending on interface implements. It is easy to understand and maintain an interface implemented on which the source file has a partial class.

Sorting int array in descending order

For primitive array types, you would have to write a reverse sort algorithm:

Alternatively, you can convert your int[] to Integer[] and write a comparator:

public class IntegerComparator implements Comparator<Integer> {

    @Override
    public int compare(Integer o1, Integer o2) {
        return o2.compareTo(o1);
    }
}

or use Collections.reverseOrder() since it only works on non-primitive array types.

and finally,

Integer[] a2 = convertPrimitiveArrayToBoxableTypeArray(a1);
Arrays.sort(a2, new IntegerComparator()); // OR
// Arrays.sort(a2, Collections.reverseOrder());

//Unbox the array to primitive type
a1 = convertBoxableTypeArrayToPrimitiveTypeArray(a2);

Jmeter - get current date and time

it seems to be the java SimpleDateFormat : http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

here are some tests i did around 11:30pm on the 20th of May 2015

${__time(dd-mmm-yyyy HHmmss)} 20-032-2015 233224
${__time(d-MMM-yyyy hhmmss)}  20-May-2015 113224
${__time(dd-m-yyyy hhmmss)}   20-32-2015 113224
${__time(D-M-yyyy hhmmss)}    140-5-2015 113224
${__time(DD-MM-yyyy)}         140-05-2015

Android Error Building Signed APK: keystore.jks not found for signing config 'externalOverride'

This is a problem that can arise from writing down a "filename" instead of a path, while generating the .jks file. Generate a new one, put it on the Desktop (or any other real path) and re-generate APK.

When is it acceptable to call GC.Collect?

I use GC.Collect only when writing crude performance/profiler test rigs; i.e. I have two (or more) blocks of code to test - something like:

GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
TestA(); // may allocate lots of transient objects
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
TestB(); // may allocate lots of transient objects
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
...

So that TestA() and TestB() run with as similar state as possible - i.e. TestB() doesn't get hammered just because TestA left it very close to the tipping point.

A classic example would be a simple console exe (a Main method sort-enough to be posted here for example), that shows the difference between looped string concatenation and StringBuilder.

If I need something precise, then this would be two completely independent tests - but often this is enough if we just want to minimize (or normalize) the GC during the tests to get a rough feel for the behaviour.

During production code? I have yet to use it ;-p

How to specify in crontab by what user to run script?

EDIT: Note that this method won't work with crontab -e, but only works if you edit /etc/crontab directly. Otherwise, you may get an error like /bin/sh: www-data: command not found

Just before the program name:

*/1 * * * * www-data php5 /var/www/web/includes/crontab/queue_process.php >> /var/www/web/includes/crontab/queue.log 2>&1

counting number of directories in a specific directory

find is also printing the directory itself:

$ find .vim/ -maxdepth 1 -type d
.vim/
.vim/indent
.vim/colors
.vim/doc
.vim/after
.vim/autoload
.vim/compiler
.vim/plugin
.vim/syntax
.vim/ftplugin
.vim/bundle
.vim/ftdetect

You can instead test the directory's children and do not descend into them at all:

$ find .vim/* -maxdepth 0 -type d
.vim/after
.vim/autoload
.vim/bundle
.vim/colors
.vim/compiler
.vim/doc
.vim/ftdetect
.vim/ftplugin
.vim/indent
.vim/plugin
.vim/syntax

$ find .vim/* -maxdepth 0 -type d | wc -l
11
$ find .vim/ -maxdepth 1 -type d | wc -l
12

You can also use ls:

$ ls -l .vim | grep -c ^d
11


$ ls -l .vim
total 52
drwxrwxr-x  3 anossovp anossovp 4096 Aug 29  2012 after
drwxrwxr-x  2 anossovp anossovp 4096 Aug 29  2012 autoload
drwxrwxr-x 13 anossovp anossovp 4096 Aug 29  2012 bundle
drwxrwxr-x  2 anossovp anossovp 4096 Aug 29  2012 colors
drwxrwxr-x  2 anossovp anossovp 4096 Aug 29  2012 compiler
drwxrwxr-x  2 anossovp anossovp 4096 Aug 29  2012 doc
-rw-rw-r--  1 anossovp anossovp   48 Aug 29  2012 filetype.vim
drwxrwxr-x  2 anossovp anossovp 4096 Aug 29  2012 ftdetect
drwxrwxr-x  2 anossovp anossovp 4096 Aug 29  2012 ftplugin
drwxrwxr-x  2 anossovp anossovp 4096 Aug 29  2012 indent
drwxrwxr-x  2 anossovp anossovp 4096 Aug 29  2012 plugin
-rw-rw-r--  1 anossovp anossovp 2505 Aug 29  2012 README.rst
drwxrwxr-x  2 anossovp anossovp 4096 Aug 29  2012 syntax

$ ls -l .vim | grep ^d
drwxrwxr-x  3 anossovp anossovp 4096 Aug 29  2012 after
drwxrwxr-x  2 anossovp anossovp 4096 Aug 29  2012 autoload
drwxrwxr-x 13 anossovp anossovp 4096 Aug 29  2012 bundle
drwxrwxr-x  2 anossovp anossovp 4096 Aug 29  2012 colors
drwxrwxr-x  2 anossovp anossovp 4096 Aug 29  2012 compiler
drwxrwxr-x  2 anossovp anossovp 4096 Aug 29  2012 doc
drwxrwxr-x  2 anossovp anossovp 4096 Aug 29  2012 ftdetect
drwxrwxr-x  2 anossovp anossovp 4096 Aug 29  2012 ftplugin
drwxrwxr-x  2 anossovp anossovp 4096 Aug 29  2012 indent
drwxrwxr-x  2 anossovp anossovp 4096 Aug 29  2012 plugin
drwxrwxr-x  2 anossovp anossovp 4096 Aug 29  2012 syntax

Cannot add or update a child row: a foreign key constraint fails

You're getting this error because you're trying to add/update a row to table2 that does not have a valid value for the UserID field based on the values currently stored in table1. If you post some more code I can help you diagnose the specific cause.

Call async/await functions in parallel

I create a helper function waitAll, may be it can make it sweeter. It only works in nodejs for now, not in browser chrome.

    //const parallel = async (...items) => {
    const waitAll = async (...items) => {
        //this function does start execution the functions
        //the execution has been started before running this code here
        //instead it collects of the result of execution of the functions

        const temp = [];
        for (const item of items) {
            //this is not
            //temp.push(await item())
            //it does wait for the result in series (not in parallel), but
            //it doesn't affect the parallel execution of those functions
            //because they haven started earlier
            temp.push(await item);
        }
        return temp;
    };

    //the async functions are executed in parallel before passed
    //in the waitAll function

    //const finalResult = await waitAll(someResult(), anotherResult());
    //const finalResult = await parallel(someResult(), anotherResult());
    //or
    const [result1, result2] = await waitAll(someResult(), anotherResult());
    //const [result1, result2] = await parallel(someResult(), anotherResult());

How to make a div with a circular shape?

.circle {
    border-radius: 50%;
    width: 500px;
    height: 500px;
    background: red;
}

<div class="circle"></div>

see this FIDDLE

Delete rows containing specific strings in R

This should do the trick:

df[- grep("REVERSE", df$Name),]

Or a safer version would be:

df[!grepl("REVERSE", df$Name),]

Split code over multiple lines in an R script

Dirk's method above will absolutely work, but if you're looking for a way to bring in a long string where whitespace/structure is important to preserve (example: a SQL query using RODBC) there is a two step solution.

1) Bring the text string in across multiple lines

long_string <- "this
is 
a 
long
string
with
whitespace"

2) R will introduce a bunch of \n characters. Strip those out with strwrap(), which destroys whitespace, per the documentation:

strwrap(long_string, width=10000, simplify=TRUE)

By telling strwrap to wrap your text to a very, very long row, you get a single character vector with no whitespace/newline characters.

Verifying that a string contains only letters in C#

I think is a good case to use Regular Expressions:

public bool IsAlpha(string input)
{
    return Regex.IsMatch(input, "^[a-zA-Z]+$");
}

public bool IsAlphaNumeric(string input)
{
    return Regex.IsMatch(input, "^[a-zA-Z0-9]+$");
}

public bool IsAlphaNumericWithUnderscore(string input)
{
    return Regex.IsMatch(input, "^[a-zA-Z0-9_]+$");
}

How to "pull" from a local branch into another one?

If you are looking for a brand new pull from another branch like from local to master you can follow this.

git commit -m "Initial Commit"
git add .
git pull --rebase git_url
git push origin master

Bootstrap alert in a fixed floating div at the top of page

Others are suggesting a wrapping div but you should be able to do this without adding complexity to your html...

check this out:

#message {
  box-sizing: border-box;
  padding: 8px;
}

Save plot to image file instead of displaying it using Matplotlib

You can save your image with any extension(png, jpg,etc.) and with the resolution you want. Here's a function to save your figure.

import os

def save_fig(fig_id, tight_layout=True, fig_extension="png", resolution=300):
    path = os.path.join(IMAGES_PATH, fig_id + "." + fig_extension)
    print("Saving figure", fig_id)
    if tight_layout:
        plt.tight_layout()
    plt.savefig(path, format=fig_extension, dpi=resolution)

'fig_id' is the name by which you want to save your figure. Hope it helps:)

Can't clone a github repo on Linux via HTTPS

As JERC said, make sure you have an updated version of git. If you are only using the default settings, when you try to install git you will get version 1.7.1. Other than manually downloading and installing the latest version of get, you can also accomplish this by adding a new repository to yum.

From tecadmin.net:

Download and install the rpmforge repository:

# use this for 64-bit
rpm -i 'http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.3-1.el6.rf.x86_64.rpm'
# use this for 32-bit
rpm -i 'http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.3-1.el6.rf.i686.rpm'

# then run this in either case
rpm --import http://apt.sw.be/RPM-GPG-KEY.dag.txt

Then you need to enable the rpmforge-extras. Edit /etc/yum.repos.d/rpmforge.repo and change enabled = 0 to enabled = 1 under [rpmforge-extras]. The file looks like this:

### Name: RPMforge RPM Repository for RHEL 6 - dag
### URL: http://rpmforge.net/
[rpmforge]
name = RHEL $releasever - RPMforge.net - dag
baseurl = http://apt.sw.be/redhat/el6/en/$basearch/rpmforge
mirrorlist = http://mirrorlist.repoforge.org/el6/mirrors-rpmforge
#mirrorlist = file:///etc/yum.repos.d/mirrors-rpmforge
enabled = 1
protect = 0
gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY-rpmforge-dag
gpgcheck = 1

[rpmforge-extras]
name = RHEL $releasever - RPMforge.net - extras
baseurl = http://apt.sw.be/redhat/el6/en/$basearch/extras
mirrorlist = http://mirrorlist.repoforge.org/el6/mirrors-rpmforge-extras
#mirrorlist = file:///etc/yum.repos.d/mirrors-rpmforge-extras
enabled = 0 ####### CHANGE THIS LINE TO "enabled = 1" #############
protect = 0
gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY-rpmforge-dag
gpgcheck = 1

[rpmforge-testing]
name = RHEL $releasever - RPMforge.net - testing
baseurl = http://apt.sw.be/redhat/el6/en/$basearch/testing
mirrorlist = http://mirrorlist.repoforge.org/el6/mirrors-rpmforge-testing
#mirrorlist = file:///etc/yum.repos.d/mirrors-rpmforge-testing
enabled = 0
protect = 0
gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY-rpmforge-dag
gpgcheck = 1

Once you've done this, then you can update git with

yum update git

I'm not sure why, but they then suggest disabling rpmforge-extras (change back to enabled = 0) and then running yum clean all.

Most likely you'll need to use sudo for these commands.

How to get domain root url in Laravel 4?

In Laravel 5.1 and later you can use

request()->getHost();

or

request()->getHttpHost();

(the second one will add port if it's not standard one)

How do I change tab size in Vim?

As a one-liner into vim:

:set tabstop=4 shiftwidth=4

For permanent setup, add these lines to ~/.vimrc:

set tabstop=4
set shiftwidth=4

NOTE: Add set expandtab if you prefer 4-spaces indentation, instead of a tab indentation.

How can I determine if a variable is 'undefined' or 'null'?

I run this test in the Chrome console. Using (void 0) you can check undefined:

var c;
undefined
if (c === void 0) alert();
// output =  undefined
var c = 1;
// output =  undefined
if (c === void 0) alert();
// output =   undefined
// check c value  c
// output =  1
if (c === void 0) alert();
// output =  undefined
c = undefined;
// output =  undefined
if (c === void 0) alert();
// output =   undefined

HTML/CSS font color vs span style

You should use <span>, because as specified by the spec, <font> has been deprecated and probably won't display as you intend.

What is the purpose for using OPTION(MAXDOP 1) in SQL Server?

As something of an aside, MAXDOP can apparently be used as a workaround to a potentially nasty bug:

Returned identity values not always correct

Why is it bad style to `rescue Exception => e` in Ruby?

That's a specific case of the rule that you shouldn't catch any exception you don't know how to handle. If you don't know how to handle it, it's always better to let some other part of the system catch and handle it.

Get file path of image on Android

use this function to get the capture image path

protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
        if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {  
            Uri mImageCaptureUri = intent.getData();
            Bitmap photo = (Bitmap) data.getExtras().get("data"); 
            imageView.setImageBitmap(photo);
            knop.setVisibility(Button.VISIBLE);
            System.out.println(mImageCaptureUri);
           //getImgPath(mImageCaptureUri);// it will return the Capture image path
        }  
    }

public String getImgPath(Uri uri) {
        String[] largeFileProjection = { MediaStore.Images.ImageColumns._ID,
                MediaStore.Images.ImageColumns.DATA };
        String largeFileSort = MediaStore.Images.ImageColumns._ID + " DESC";
        Cursor myCursor = this.managedQuery(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                largeFileProjection, null, null, largeFileSort);
        String largeImagePath = "";
        try {
            myCursor.moveToFirst();
            largeImagePath = myCursor
                    .getString(myCursor
                            .getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA));
        } finally {
            myCursor.close();
        }
        return largeImagePath;
    }

How do I create a custom Error in JavaScript?

This is my implementation:

class HttpError extends Error {
  constructor(message, code = null, status = null, stack = null, name = null) {
    super();
    this.message = message;
    this.status = 500;

    this.name = name || this.constructor.name;
    this.code = code || `E_${this.name.toUpperCase()}`;
    this.stack = stack || null;
  }

  static fromObject(error) {
    if (error instanceof HttpError) {
      return error;
    }
    else {
      const { message, code, status, stack } = error;
      return new ServerError(message, code, status, stack, error.constructor.name);
    }
  }

  expose() {
    if (this instanceof ClientError) {
      return { ...this };
    }
    else {
      return {
        name: this.name,
        code: this.code,
        status: this.status,
      }
    }
  }
}

class ServerError extends HttpError {}

class ClientError extends HttpError { }

class IncorrectCredentials extends ClientError {
  constructor(...args) {
    super(...args);
    this.status = 400;
  }
}

class ResourceNotFound extends ClientError {
  constructor(...args) {
    super(...args);
    this.status = 404;
  }
}

Example usage #1:

app.use((req, res, next) => {
  try {
    invalidFunction();
  }
  catch (err) {
    const error = HttpError.fromObject(err);
    return res.status(error.status).send(error.expose());
  }
});

Example usage #2:

router.post('/api/auth', async (req, res) => {
  try {
    const isLogged = await User.logIn(req.body.username, req.body.password);

    if (!isLogged) {
      throw new IncorrectCredentials('Incorrect username or password');
    }
    else {
      return res.status(200).send({
        token,
      });
    }
  }
  catch (err) {
    const error = HttpError.fromObject(err);
    return res.status(error.status).send(error.expose());
  }
});

iPhone and WireShark

I recommend Charles Web Proxy

Charles is an HTTP proxy / HTTP monitor / Reverse Proxy that enables a developer to view all of the HTTP and SSL / HTTPS traffic between their machine and the Internet. This includes requests, responses and the HTTP headers (which contain the cookies and caching information).

  • SSL Proxying – view SSL requests and responses in plain text
  • Bandwidth Throttling to simulate slower Internet connections including latency
  • AJAX debugging – view XML and JSON requests and responses as a tree or as text
  • AMF – view the contents of Flash Remoting / Flex Remoting messages as a tree
  • Repeat requests to test back-end changes, Edit requests to test different inputs
  • Breakpoints to intercept and edit requests or responses
  • Validate recorded HTML, CSS and RSS/atom responses using the W3C validator

It's cross-platform, written in JAVA, and pretty good. Not nearly as overwhelming as Wireshark, and does a lot of the annoying stuff like setting up the proxies, etc. for you. The only bad part is that it costs money, $50 at that. Not cheap, but a useful tool.

Read more about Charles's features.

Duplicate AssemblyVersion Attribute

I came across the same when tried add GitVersion tool to update my version in AssemblyInfo.cs. Use VS2017 and .NET Core project. So I just mixed both worlds. My AssemblyInfo.cs contains only version info that was generated by GitVersion tool, my csproj contains remaingin things. Please note I don't use <GenerateAssemblyInfo>false</GenerateAssemblyInfo> I use attributes related to version only (see below). More details here AssemblyInfo properties.

AssemblyInfo.cs

[assembly: AssemblyVersion("0.2.1.0")]
[assembly: AssemblyFileVersion("0.2.1.0")]
[assembly: AssemblyInformationalVersion("0.2.1+13.Branch.master.Sha.119c35af0f529e92e0f75a5e6d8373912d457818")]

my.csproj contains all related to other assemblyu attributes:

<PropertyGroup>
...
<Company>SOME Company </Company>
<Authors>Some Authors</Authors>
<Product>SOME Product</Product>
...
<GenerateAssemblyVersionAttribute>false</GenerateAssemblyVersionAttribute>
<GenerateAssemblyFileVersionAttribute>false</GenerateAssemblyFileVersionAttribute><GenerateAssemblyInformationalVersionAttribute>false</GenerateAssemblyInformationalVersionAttribute>

csproj maps to package tab at project properties

Why is sed not recognizing \t as a tab?

Use $(echo '\t'). You'll need quotes around the pattern.

Eg. To remove a tab:

sed "s/$(echo '\t')//"