Programs & Examples On #Singlepage

Single Page Applications are web applications that simulate the interaction behavior of desktop applications.

AngularJs ReferenceError: angular is not defined

If you've downloaded the angular.js file from Google, you need to make sure that Everyone has Read access to it, or it will not be loaded by your HTML file. By default, it seems to download with No access permissions, so you'll also be getting a message such as:

GET http://localhost/myApp/js/angular.js

This maddened me for about half an hour!

Hex-encoded String to Byte Array

Java SE 6 or Java EE 5 provides a method to do this now so there is no need for extra libraries.

The method is DatatypeConverter.parseHexBinary

In this case it can be used as follows:

String str = "9B7D2C34A366BF890C730641E6CECF6F";
byte[] bytes = DatatypeConverter.parseHexBinary(str);

The class also provides type conversions for many other formats that are generally used in XML.

no default constructor exists for class

If you define a class without any constructor, the compiler will synthesize a constructor for you (and that will be a default constructor -- i.e., one that doesn't require any arguments). If, however, you do define a constructor, (even if it does take one or more arguments) the compiler will not synthesize a constructor for you -- at that point, you've taken responsibility for constructing objects of that class, so the compiler "steps back", so to speak, and leaves that job to you.

You have two choices. You need to either provide a default constructor, or you need to supply the correct parameter when you define an object. For example, you could change your constructor to look something like:

Blowfish(BlowfishAlgorithm algorithm = CBC);

...so the ctor could be invoked without (explicitly) specifying an algorithm (in which case it would use CBC as the algorithm).

The other alternative would be to explicitly specify the algorithm when you define a Blowfish object:

class GameCryptography { 
    Blowfish blowfish_;
public:
    GameCryptography() : blowfish_(ECB) {}
    // ...
};

In C++ 11 (or later) you have one more option available. You can define your constructor that takes an argument, but then tell the compiler to generate the constructor it would have if you didn't define one:

class GameCryptography { 
public:

    // define our ctor that takes an argument
    GameCryptography(BlofishAlgorithm); 

    // Tell the compiler to do what it would have if we didn't define a ctor:
    GameCryptography() = default;
};

As a final note, I think it's worth mentioning that ECB, CBC, CFB, etc., are modes of operation, not really encryption algorithms themselves. Calling them algorithms won't bother the compiler, but is unreasonably likely to cause a problem for others reading the code.

Converting string to double in C#

There are 3 problems.

1) Incorrect decimal separator

Different cultures use different decimal separators (namely , and .).

If you replace . with , it should work as expected:

Console.WriteLine(Convert.ToDouble("52,8725945"));

You can parse your doubles using overloaded method which takes culture as a second parameter. In this case you can use InvariantCulture (What is the invariant culture) e.g. using double.Parse:

double.Parse("52.8725945", System.Globalization.CultureInfo.InvariantCulture);

You should also take a look at double.TryParse, you can use it with many options and it is especially useful to check wheter or not your string is a valid double.

2) You have an incorrect double

One of your values is incorrect, because it contains two dots:

15.5859949000000662452.23862099999999

3) Your array has an empty value at the end, which is an incorrect double

You can use overloaded Split which removes empty values:

string[] someArray = a.Split(new char[] { '#' }, StringSplitOptions.RemoveEmptyEntries);

Postgresql 9.2 pg_dump version mismatch

For macs, use find / -name pg_dump -type f 2>/dev/null find the location of pg_dump

For me, I have following results:

Applications/Postgres.app/Contents/Versions/9.5/bin/pg_dump
/usr/local/Cellar/postgresql/9.4.5_2/bin/pg_dump

If you don't want to use sudo ln -s new_pg_dump old_pg_dump --force, just use:

Applications/Postgres.app/Contents/Versions/9.5/bin/pg_dump to replace with pg_dump in your terminal

For example:

Applications/Postgres.app/Contents/Versions/9.5/bin/pg_dump books > books.out

It works for me!

What is the `zero` value for time.Time in Go?

You should use the Time.IsZero() function instead:

func (Time) IsZero

func (t Time) IsZero() bool
IsZero reports whether t represents the zero time instant, January 1, year 1, 00:00:00 UTC.

What's the difference between %s and %d in Python string formatting?

speaking of which ...
python3.6 comes with f-strings which makes things much easier in formatting!
now if your python version is greater than 3.6 you can format your strings with these available methods:

name = "python"

print ("i code with %s" %name)          # with help of older method
print ("i code with {0}".format(name))  # with help of format
print (f"i code with {name}")           # with help of f-strings

What is newline character -- '\n'

NewLine (\n) is 10 (0xA) and CarriageReturn (\r) is 13 (0xD).

Different operating systems picked different end of line representations for files. Windows uses CRLF (\r\n). Unix uses LF (\n). Older Mac OS versions use CR (\r), but OS X switched to the Unix character.

Here is a relatively useful FAQ.

How to hide 'Back' button on navigation bar on iPhone?

hide back button with bellow code...

[self.navigationItem setHidesBackButton:YES animated:YES];

or

[self.navigationItem setHidesBackButton:YES];

Also if you have custom UINavigationBar then try bellow code

self.navigationItem.leftBarButtonItem = nil;

What does "-ne" mean in bash?

"not equal" So in this case, $RESULT is tested to not be equal to zero.

However, the test is done numerically, not alphabetically:

n1 -ne n2     True if the integers n1 and n2 are not algebraically equal.

compared to:

s1 != s2      True if the strings s1 and s2 are not identical.

C# ASP.NET Send Email via TLS

On SmtpClient there is an EnableSsl property that you would set.

i.e.

SmtpClient client = new SmtpClient(exchangeServer);
client.EnableSsl = true;
client.Send(msg);

Generate Java class from JSON?

I created a github project Json2Java that does this. https://github.com/inder123/json2java

Json2Java provides customizations such as renaming fields, and creating inheritance hierarchies.

I have used the tool to create some relatively complex APIs:

Gracenote's TMS API: https://github.com/inder123/gracenote-java-api

Google Maps Geocoding API: https://github.com/inder123/geocoding

Inline CSS styles in React: how to implement a:hover?

I think onMouseEnter and onMouseLeave are the ways to go, but I don't see the need for an additional wrapper component. Here is how I implemented it:

var Link = React.createClass({
  getInitialState: function(){
    return {hover: false}
  },
  toggleHover: function(){
    this.setState({hover: !this.state.hover})
  },
  render: function() {
    var linkStyle;
    if (this.state.hover) {
      linkStyle = {backgroundColor: 'red'}
    } else {
      linkStyle = {backgroundColor: 'blue'}
    }
    return(
      <div>
        <a style={linkStyle} onMouseEnter={this.toggleHover} onMouseLeave={this.toggleHover}>Link</a>
      </div>
    )
}

You can then use the state of hover (true/false) to change the style of the link.

How do I run a bat file in the background from another bat file?

Create a new C# Windows application and call this method from main:

public static void RunBatchFile(string filename)
{
    Process process = new Process();

    process.StartInfo.FileName = filename;

    // suppress output (command window still gets created)
    process.StartInfo.Arguments = "> NULL";

    process.Start();
    process.WaitForExit();
}

Automatically creating directories with file output

The os.makedirs function does this. Try the following:

import os
import errno

filename = "/foo/bar/baz.txt"
if not os.path.exists(os.path.dirname(filename)):
    try:
        os.makedirs(os.path.dirname(filename))
    except OSError as exc: # Guard against race condition
        if exc.errno != errno.EEXIST:
            raise

with open(filename, "w") as f:
    f.write("FOOBAR")

The reason to add the try-except block is to handle the case when the directory was created between the os.path.exists and the os.makedirs calls, so that to protect us from race conditions.


In Python 3.2+, there is a more elegant way that avoids the race condition above:

import os

filename = "/foo/bar/baz.txt"
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, "w") as f:
    f.write("FOOBAR")

RelativeLayout center vertical

       <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentStart="true"
                android:layout_centerInParent="true"
                android:layout_gravity="center_vertical"
                android:layout_marginTop="@dimen/main_spacing_extra_big"
                android:orientation="horizontal">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"

                    android:fontFamily="@font/noto_kufi_regular"
                    android:text="@string/renew_license_municipality"
                    android:textColor="@color/sixth_text"
                    android:textSize="@dimen/main_text" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:fontFamily="@font/noto_kufi_regular"
                    android:text="@{RenewLicenseBasicInfoFragmentVM.tvMunicipality}"
                    android:textColor="@color/sixth_text"
                    android:textSize="@dimen/main_text" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentEnd="true"
                android:layout_centerInParent="true"
                android:layout_gravity="center_vertical"
                android:layout_marginTop="@dimen/main_spacing_extra_big"
                android:orientation="horizontal">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="end"
                    android:fontFamily="@font/noto_kufi_regular"
                    android:text="@string/renew_license_license_number"
                    android:textColor="@color/sixth_text"
                    android:textSize="@dimen/main_text" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="end"
                    android:fontFamily="@font/noto_kufi_regular"
                    android:text="@{RenewLicenseBasicInfoFragmentVM.tvLicenseNum}"
                    android:textColor="@color/sixth_text"
                    android:textSize="@dimen/main_text" />
            </LinearLayout>`enter code here`

        </RelativeLayout>

Video 100% width and height

I am new into all of this. Maybe you can just add/change this HTML code. Without need for CSS. It worked for me :)

width="100%" height="height"

How to enable Ad Hoc Distributed Queries

sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
GO
RECONFIGURE;
GO

Get week day name from a given month, day and year individually in SQL Server

I used

select
case
when (extract (weekday from DATE)=0) then 'Sunday'

and so on...

0 Sunday, 1 Monday...

Python - converting a string of numbers into a list of int

it should work

example_string = '0, 0, 0, 11, 0, 0, 0, 0, 0, 19, 0, 9, 0, 0, 0, 0, 0, 0, 11'
example_list = [int(k) for k in example_string.split(',')]

How to open .mov format video in HTML video Tag?

You can use Controls attribute

<video id="sampleMovie" src="HTML5Sample.mov" controls></video>

In Typescript, what is the ! (exclamation mark / bang) operator when dereferencing a member?

non-null assertion operator

With the non-null assertion operator we can tell the compiler explicitly that an expression has value other than null or undefined. This is can be useful when the compiler cannot infer the type with certainty but we more information than the compiler.

Example

TS code

function simpleExample(nullableArg: number | undefined | null) {
   const normal: number = nullableArg; 
    //   Compile err: 
    //   Type 'number | null | undefined' is not assignable to type 'number'.
    //   Type 'undefined' is not assignable to type 'number'.(2322)

   const operatorApplied: number = nullableArg!; 
    // compiles fine because we tell compiler that null | undefined are excluded 
}

Compiled JS code

Note that the JS does not know the concept of the Non-null assertion operator since this is a TS feature

_x000D_
_x000D_
"use strict";
function simpleExample(nullableArg) {
    const normal = nullableArg;
    const operatorApplied = nullableArg;
 }
_x000D_
_x000D_
_x000D_

How can I create a text box for a note in markdown?

Similar to Etienne's solution, a simple table formats nicely:

| | |
|-|-|
|`NOTE` | This is something I want you to notice. It has a lot of text, and I want that text to wrap within a cell to the right of the `NOTE`, instead of under it.|

Another alternative (which comes with more emphasis), is to make the content the header of a body-less table:

|`NOTE` | This is something I want you to notice. It has a lot of text, and I want that text to wrap within a cell to the right of the `NOTE`, instead of under it.|
|-|-|

Finally, you can include a horizontal line (thematic break) to create a closed box (although the line style is a little different than the header line in the table):

| | |
|-|-|
|`NOTE` | This is something I want you to notice. It has a lot of text, and I want that text to wrap within a cell to the right of the `NOTE`, instead of under it.|

---

Note the empty line after the text.

Downloading video from YouTube

I've written a library that is up-to-date, since all the other answers are outdated:

https://github.com/flagbug/YoutubeExtractor

Cannot find firefox binary in PATH. Make sure firefox is installed. OS appears to be: VISTA

I got this error message while running tests in Visual Studio: Firefox simply wouldn't load and I got OP's error message.

I manually opened Firefox and found out that it needed to update itself (it did so before loading). Once finished I reran the test suite and Firefox showed up nicely, the tests were properly ran. If you get this error all of a sudden please try this answer before updating anything on your machine.

How to set a default value for an existing column

You can use following syntax, For more information see this question and answers : Add a column with a default value to an existing table in SQL Server

Syntax :

ALTER TABLE {TABLENAME} 
ADD {COLUMNNAME} {TYPE} {NULL|NOT NULL} 
CONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE}
WITH VALUES

Example :

ALTER TABLE SomeTable
ADD SomeCol Bit NULL --Or NOT NULL.
CONSTRAINT D_SomeTable_SomeCol --When Omitted a Default-Constraint Name is 
autogenerated.
DEFAULT (0)--Optional Default-Constraint.
WITH VALUES --Add if Column is Nullable and you want the Default Value for Existing Records.

Another way :

Right click on the table and click on Design,then click on column that you want to set default value.

Then in bottom of page add a default value or binding : something like '1' for string or 1 for int.

MySQL SELECT statement for the "length" of the field is greater than 1

Try:

SELECT
    *
FROM
    YourTable
WHERE
    CHAR_LENGTH(Link) > x

How do I get JSON data from RESTful service using Python?

If you desire to use Python 3, you can use the following:

import json
import urllib.request
req = urllib.request.Request('url')
with urllib.request.urlopen(req) as response:
    result = json.loads(response.readall().decode('utf-8'))

How do you change the size of figures drawn with matplotlib?

Another option, to use the rc() function in matplotlib (the unit is inch)

import matplotlib
matplotlib.rc('figure', figsize=[10,5])

Drawing a line/path on Google Maps

You can get the projection from the MapView object which is passed into the draw() method: mapv.getProjection().toPixels(gP1, p1);

How to create a XML object from String in Java?

try something like

public static Document loadXML(String xml) throws Exception
{
   DocumentBuilderFactory fctr = DocumentBuilderFactory.newInstance();
   DocumentBuilder bldr = fctr.newDocumentBuilder();
   InputSource insrc = new InputSource(new StringReader(xml));
   return bldr.parse(insrc);
}

Run javascript script (.js file) in mongodb including another file inside js

Yes you can. The default location for script files is data/db

If you put any script there you can call it as

load("myjstest.js")      // or 
load("/data/db/myjstest.js")

How to load a resource bundle from a file resource in Java?

As long as you name your resource bundle files correctly (with a .properties extension), then this works:

File file = new File("C:\\temp");
URL[] urls = {file.toURI().toURL()};
ClassLoader loader = new URLClassLoader(urls);
ResourceBundle rb = ResourceBundle.getBundle("myResource", Locale.getDefault(), loader);

where "c:\temp" is the external folder (NOT on the classpath) holding the property files, and "myResource" relates to myResource.properties, myResource_fr_FR.properties, etc.

Credit to http://www.coderanch.com/t/432762/java/java/absolute-path-bundle-file

Git error on git pull (unable to update local ref)

What happened over here? The local references to your remote branches were changed and hence when you run git pull, git doesn't find any corresponding remote branches and hence it fails.

git remote prune origin

actually cleans this local references and then run git pull again.

Suggestion - Please run with --dry-run option for safety

How to POST raw whole JSON in the body of a Retrofit request?

I tried this: When you are creating your Retrofit instance, add this converter factory to the retrofit builder:

gsonBuilder = new GsonBuilder().serializeNulls()     
your_retrofit_instance = Retrofit.Builder().addConverterFactory( GsonConverterFactory.create( gsonBuilder.create() ) )

What is the best way to return different types of ResponseEntity in Spring MVC or Spring-Boot

You can use a map with your object or string like bellow :

@RequestMapping(value = "/path", 
        method = RequestMethod.GET, 
        produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public ResponseEntity<Map<String,String>> getData(){

    Map<String,String> response = new HashMap<String, String>();

    boolean isValid = // some logic
    if (isValid){
        response.put("ok", "success saving data");
        return ResponseEntity.accepted().body(response);
    }
    else{
        response.put("error", "an error expected on processing file");
        return ResponseEntity.badRequest().body(response);
    }

}

how to make a jquery "$.post" request synchronous

If you want an synchronous request set the async property to false for the request. Check out the jQuery AJAX Doc

Simple int to char[] conversion

If you want to convert an int which is in the range 0-9 to a char, you may usually write something like this:

int x;
char c = '0' + x;

Now, if you want a character string, just add a terminating '\0' char:

char s[] = {'0' + x, '\0'};

Note that:

  1. You must be sure that the int is in the 0-9 range, otherwise it will fail,
  2. It works only if character codes for digits are consecutive. This is true in the vast majority of systems, that are ASCII-based, but this is not guaranteed to be true in all cases.

how to create a login page when username and password is equal in html

<html>
    <head>
        <title>Login page</title>
    </head>
    <body>
        <h1>Simple Login Page</h1>
        <form name="login">
            Username<input type="text" name="userid"/>
            Password<input type="password" name="pswrd"/>
            <input type="button" onclick="check(this.form)" value="Login"/>
            <input type="reset" value="Cancel"/>
        </form>
        <script language="javascript">
            function check(form) { /*function to check userid & password*/
                /*the following code checkes whether the entered userid and password are matching*/
                if(form.userid.value == "myuserid" && form.pswrd.value == "mypswrd") {
                    window.open('target.html')/*opens the target page while Id & password matches*/
                }
                else {
                    alert("Error Password or Username")/*displays error message*/
                }
            }
        </script>
    </body>
</html>

Add JsonArray to JsonObject

Just try below a simple solution:

JsonObject body=new JsonObject();
body.add("orders", (JsonElement) orders);

whenever my JSON request is like:

{
      "role": "RT",
      "orders": [
        {
          "order_id": "ORDER201908aPq9Gs",
          "cart_id": 164444,
          "affiliate_id": 0,
          "orm_order_status": 9,
          "status_comments": "IC DUE - Auto moved to Instruction Call Due after 48hrs",
          "status_date": "2020-04-15",
        }
      ]
    }

How to create a CPU spike with a bash command

One core (doesn't invoke external process):

while true; do true; done

Two cores:

while true; do /bin/true; done

The latter only makes both of mine go to ~50% though...

This one will make both go to 100%:

while true; do echo; done

Number to String in a formula field

I believe this is what you're looking for:

Convert Decimal Numbers to Text showing only the non-zero decimals

Especially this line might be helpful:

StringVar text     :=  Totext ( {Your.NumberField} , 6 , ""  )  ;

The first parameter is the decimal to be converted, the second parameter is the number of decimal places and the third parameter is the separator for thousands/millions etc.

How to read all files in a folder from Java?

package com.commandline.folder;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class FolderReadingDemo {
    public static void main(String[] args) {
        String str = args[0];
        final File folder = new File(str);
//      listFilesForFolder(folder);
        listFilesForFolder(str);
    }

    public static void listFilesForFolder(String str) {
        try (Stream<Path> paths = Files.walk(Paths.get(str))) {
            paths.filter(Files::isRegularFile).forEach(System.out::println);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void listFilesForFolder(final File folder) {
        for (final File fileEntry : folder.listFiles()) {
            if (fileEntry.isDirectory()) {
                listFilesForFolder(fileEntry);
            } else {
                System.out.println(fileEntry.getName());
            }
        }
    }

}

What does axis in pandas mean?

Let's visualize (you gonna remember always), enter image description here

In Pandas:

  1. axis=0 means along "indexes". It's a row-wise operation.

Suppose, to perform concat() operation on dataframe1 & dataframe2, we will take dataframe1 & take out 1st row from dataframe1 and place into the new DF, then we take out another row from dataframe1 and put into new DF, we repeat this process until we reach to the bottom of dataframe1. Then, we do the same process for dataframe2.

Basically, stacking dataframe2 on top of dataframe1 or vice a versa.

E.g making a pile of books on a table or floor

  1. axis=1 means along "columns". It's a column-wise operation.

Suppose, to perform concat() operation on dataframe1 & dataframe2, we will take out the 1st complete column(a.k.a 1st series) of dataframe1 and place into new DF, then we take out the second column of dataframe1 and keep adjacent to it (sideways), we have to repeat this operation until all columns are finished. Then, we repeat the same process on dataframe2. Basically, stacking dataframe2 sideways.

E.g arranging books on a bookshelf.

More to it, since arrays are better representations to represent a nested n-dimensional structure compared to matrices! so below can help you more to visualize how axis plays an important role when you generalize to more than one dimension. Also, you can actually print/write/draw/visualize any n-dim array but, writing or visualizing the same in a matrix representation(3-dim) is impossible on a paper more than 3-dimensions.

enter image description here

Side-by-side plots with ggplot2

In my experience gridExtra:grid.arrange works perfectly, if you are trying to generate plots in a loop.

Short Code Snippet:

gridExtra::grid.arrange(plot1, plot2, ncol = 2)

** Updating this comment to show how to use grid.arrange() within a for loop to generate plots for different factors of a categorical variable.

for (bin_i in levels(athlete_clean$BMI_cat)) {

plot_BMI <- athlete_clean %>% filter(BMI_cat == bin_i) %>% group_by(BMI_cat,Team) %>% summarize(count_BMI_team = n()) %>% 
          mutate(percentage_cbmiT = round(count_BMI_team/sum(count_BMI_team) * 100,2)) %>% 
          arrange(-count_BMI_team) %>% top_n(10,count_BMI_team) %>% 
          ggplot(aes(x = reorder(Team,count_BMI_team), y = count_BMI_team, fill = Team)) +
            geom_bar(stat = "identity") +
            theme_bw() +
            # facet_wrap(~Medal) +
            labs(title = paste("Top 10 Participating Teams with \n",bin_i," BMI",sep=""), y = "Number of Athletes", 
                 x = paste("Teams - ",bin_i," BMI Category", sep="")) +
            geom_text(aes(label = paste(percentage_cbmiT,"%",sep = "")), 
                      size = 3, check_overlap = T,  position = position_stack(vjust = 0.7) ) +
            theme(axis.text.x = element_text(angle = 00, vjust = 0.5), plot.title = element_text(hjust = 0.5), legend.position = "none") +
            coord_flip()

plot_BMI_Medal <- athlete_clean %>% 
          filter(!is.na(Medal), BMI_cat == bin_i) %>% 
          group_by(BMI_cat,Team) %>% 
          summarize(count_BMI_team = n()) %>% 
          mutate(percentage_cbmiT = round(count_BMI_team/sum(count_BMI_team) * 100,2)) %>% 
          arrange(-count_BMI_team) %>% top_n(10,count_BMI_team) %>% 
          ggplot(aes(x = reorder(Team,count_BMI_team), y = count_BMI_team, fill = Team)) +
            geom_bar(stat = "identity") +
            theme_bw() +
            # facet_wrap(~Medal) +
            labs(title = paste("Top 10 Winning Teams with \n",bin_i," BMI",sep=""), y = "Number of Athletes", 
                 x = paste("Teams - ",bin_i," BMI Category", sep="")) +
            geom_text(aes(label = paste(percentage_cbmiT,"%",sep = "")), 
                      size = 3, check_overlap = T,  position = position_stack(vjust = 0.7) ) +
            theme(axis.text.x = element_text(angle = 00, vjust = 0.5), plot.title = element_text(hjust = 0.5), legend.position = "none") +
            coord_flip()

gridExtra::grid.arrange(plot_BMI, plot_BMI_Medal, ncol = 2)

}

One of the Sample Plots from the above for loop is included below. The above loop will produce multiple plots for all levels of BMI category.

Sample Image

If you wish to see a more comprehensive use of grid.arrange() within for loops, check out https://rpubs.com/Mayank7j_2020/olympic_data_2000_2016

How can I increase the cursor speed in terminal?

If by "cursor speed", you mean the repeat rate when holding down a key - then have a look here: http://hints.macworld.com/article.php?story=20090823193018149

To summarize, open up a Terminal window and type the following command:

defaults write NSGlobalDomain KeyRepeat -int 0

More detail from the article:

Everybody knows that you can get a pretty fast keyboard repeat rate by changing a slider on the Keyboard tab of the Keyboard & Mouse System Preferences panel. But you can make it even faster! In Terminal, run this command:

defaults write NSGlobalDomain KeyRepeat -int 0

Then log out and log in again. The fastest setting obtainable via System Preferences is 2 (lower numbers are faster), so you may also want to try a value of 1 if 0 seems too fast. You can always visit the Keyboard & Mouse System Preferences panel to undo your changes.

You may find that a few applications don't handle extremely fast keyboard input very well, but most will do just fine with it.

How, in general, does Node.js handle 10,000 concurrent requests?

What you seem to be thinking is that most of the processing is handled in the node event loop. Node actually farms off the I/O work to threads. I/O operations typically take orders of magnitude longer than CPU operations so why have the CPU wait for that? Besides, the OS can handle I/O tasks very well already. In fact, because Node does not wait around it achieves much higher CPU utilisation.

By way of analogy, think of NodeJS as a waiter taking the customer orders while the I/O chefs prepare them in the kitchen. Other systems have multiple chefs, who take a customers order, prepare the meal, clear the table and only then attend to the next customer.

Convert an image (selected by path) to base64 string

Something like that

 Function imgTo64(ByVal thePath As String) As String
    Dim img As System.Drawing.Image = System.Drawing.Image.FromFile(thePath)
    Dim m As IO.MemoryStream = New IO.MemoryStream()

    img.Save(m, img.RawFormat)
    Dim imageBytes As Byte() = m.ToArray
    img.Dispose()

    Dim str64 = Convert.ToBase64String(imageBytes)
    Return str64
End Function

How do I find the parent directory in C#?

Like this:

System.IO.DirectoryInfo myDirectory = new DirectoryInfo(Environment.CurrentDirectory);
string parentDirectory = myDirectory.Parent.FullName;

Good luck!

Using If else in SQL Select statement

Here is some example using CASE WHEN

SELECT 
    CASE WHEN A > 1 THEN
            'Greater than 1'
    END  
FROM TRIANGLES

.

SELECT 
    CASE WHEN A > 1 THEN
            A
    END  
FROM TRIANGLES

.

SELECT 
    CASE WHEN A > 1 and B > 1 THEN
            'Greater than 1'
    END  
FROM TRIANGLES

.

SELECT 
    CASE WHEN A > 1 THEN
            'greater than 1'
         ELSE
            'less than 1'
    END  
FROM TRIANGLES

.

SELECT 
    CASE WHEN A > 1 THEN
            'greater than 1'
         ELSE CASE WHEN A >= 0 THEN
                      'greater than or equal 0'
                   ELSE
                      'less than 0'
              END        
    END  
FROM TRIANGLES;

Hope this helps

How to stop/shut down an elasticsearch node?

For Mac users using Homebrew (Brew) to install and manage services:

List your Brew services:

brew services

Do something with a service:

brew services start elasticsearch-full
brew services restart elasticsearch-full
brew services stop elasticsearch-full

Benefits of inline functions in C++?

Why not make all functions inline by default? Because it's an engineering trade off. There are at least two types of "optimization": speeding up the program and reducing the size (memory footprint) of the program. Inlining generally speeds things up. It gets rid of the function call overhead, avoiding pushing then pulling parameters from the stack. However, it also makes the memory footprint of the program bigger, because every function call must now be replaced with the full code of the function. To make things even more complicated, remember that the CPU stores frequently used chunks of memory in a cache on the CPU for ultra-rapid access. If you make the program's memory image big enough, your program won't be able to use the cache efficiently, and in the worst case inlining could actually slow your program down. To some extent the compiler can calculate what the trade offs are, and may be able to make better decisions than you can, just looking at the source code.

jQuery if Element has an ID?

Like this:

var $aWithId = $('.parent a[id]');

Following OP's comment, test it like this:

if($aWithId.length) //or without using variable: if ($('.parent a[id]').length)

Will return all anchor tags inside elements with class parent which have an attribute ID specified

How do I get the selected element by name and then get the selected value from a dropdown using jQuery?

Remove the onchange event from the HTML Markup and bind it in your document ready event

<select  name="a[b]" >
     <option value='Choice 1'>Choice 1</option>
     <option value='Choice 2'>Choice 2</option>
</select>?

and Script

$(function(){    
    $("select[name='a[b]']").change(function(){
       alert($(this).val());        
    }); 
});

Working sample : http://jsfiddle.net/gLaR8/3/

Getting unique values in Excel by using formulas only

Ok, I have two ideas for you. Hopefully one of them will get you where you need to go. Note that the first one ignores the request to do this as a formula since that solution is not pretty. I figured I make sure the easy way really wouldn't work for you ;^).

Use the Advanced Filter command

  1. Select the list (or put your selection anywhere inside the list and click ok if the dialog comes up complaining that Excel does not know if your list contains headers or not)
  2. Choose Data/Advanced Filter
  3. Choose either "Filter the list, in-place" or "Copy to another location"
  4. Click "Unique records only"
  5. Click ok
  6. You are done. A unique list is created either in place or at a new location. Note that you can record this action to create a one line VBA script to do this which could then possible be generalized to work in other situations for you (e.g. without the manual steps listed above).

Using Formulas (note that I'm building on Locksfree solution to end up with a list with no holes)

This solution will work with the following caveats:

  • The list must be sorted (ascending or descending does not matter). Actually that's quite accurate as the requirement is really that all like items must be contiguous but sorting is the easiest way to reach that state.
  • Three new columns are required (two new columns for calculations and one new column for the new list). The second and third columns could be combined but I'll leave that as an exercise to the reader.

    Here is the summary of the solution:

    1. For each item in the list, calculate the number of duplicates above it.
    2. For each place in the unique list, calculate the index of the next unique item.
    3. Finally, use the indexes to create a new list with only unique items.

    And here is a step by step example:

    1. Open a new spreadsheet
    2. In a1:a6 enter the example given in the original question ("red", "blue", "red", "green", "blue", "black")
    3. Sort the list: put the selection in the list and choose the sort command.
    4. In column B, calculate the duplicates:
      1. In B1, enter "=IF(COUNTIF($A$1:A1,A1) = 1,0,COUNTIF(A1:$A$6,A1))". Note that the "$" in the cell references are very important as it will make the next step (populating the rest of the column) much easier. The "$" indicates an absolute reference so that when the cell content is copy/pasted the reference will not update (as opposed to a relative reference which will update).
      2. Use smart copy to populate the rest of column B: Select B1. Move your mouse over the black square in the lower right hand corner of the selection. Click and drag down to the bottom of the list (B6). When you release, the formula will be copied into B2:B6 with the relative references updated.
      3. The value of B1:B6 should now be "0,0,1,0,0,1". Notice that the "1" entries indicate duplicates.
    5. In Column C, create an index of unique items:
      1. In C1, enter "=Row()". You really just want C1 = 1 but using Row() means this solution will work even if the list does not start in row 1.
      2. In C2, enter "=IF(C1+1<=ROW($B$6), C1+1+INDEX($B$1:$B$6,C1+1),C1+1)". The "if" is being used to stop a #REF from being produced when the index reaches the end of the list.
      3. Use smart copy to populate C3:C6.
      4. The value of C1:C6 should be "1,2,4,5,7,8"
    6. In column D, create the new unique list:
      1. In D1, enter "=IF(C1<=ROW($A$6), INDEX($A$1:$A$6,C1), "")". And, the "if" is being used to stop the #REF case when the index goes beyond the end of the list.
      2. Use smart copy to populate D2:D6.
      3. The values of D1:D6 should now be "black","blue","green","red","","".

    Hope this helps....

  • Fetching data from MySQL database to html dropdown list

    # here database details      
    mysql_connect('hostname', 'username', 'password');
    mysql_select_db('database-name');
    
    $sql = "SELECT username FROM userregistraton";
    $result = mysql_query($sql);
    
    echo "<select name='username'>";
    while ($row = mysql_fetch_array($result)) {
        echo "<option value='" . $row['username'] ."'>" . $row['username'] ."</option>";
    }
    echo "</select>";
    
    # here username is the column of my table(userregistration)
    # it works perfectly
    

    Adding Only Untracked Files

    git ls-files -o --exclude-standard gives untracked files, so you can do something like below ( or add an alias to it):

    git add $(git ls-files -o --exclude-standard)
    

    change cursor from block or rectangle to line?

    please Press fn +ins key together

    Tomcat - maxThreads vs maxConnections

    Tomcat can work in 2 modes:

    • BIO – blocking I/O (one thread per connection)
    • NIOnon-blocking I/O (many more connections than threads)

    Tomcat 7 is BIO by default, although consensus seems to be "don't use Bio because Nio is better in every way". You set this using the protocol parameter in the server.xml file.

    • BIO will be HTTP/1.1 or org.apache.coyote.http11.Http11Protocol
    • NIO will be org.apache.coyote.http11.Http11NioProtocol

    If you're using BIO then I believe they should be more or less the same.

    If you're using NIO then actually "maxConnections=1000" and "maxThreads=10" might even be reasonable. The defaults are maxConnections=10,000 and maxThreads=200. With NIO, each thread can serve any number of connections, switching back and forth but retaining the connection so you don't need to do all the usual handshaking which is especially time-consuming with HTTPS but even an issue with HTTP. You can adjust the "keepAlive" parameter to keep connections around for longer and this should speed everything up.

    What version of MongoDB is installed on Ubuntu

    In the terminal just enter the traditional command:

    mongod --version
    

    Converting list to numpy array

    If you have a list of lists, you only needed to use ...

    import numpy as np
    ...
    npa = np.asarray(someListOfLists, dtype=np.float32)
    

    per this LINK in the scipy / numpy documentation. You just needed to define dtype inside the call to asarray.

    How to list the files inside a JAR file?

    Given an actual JAR file, you can list the contents using JarFile.entries(). You will need to know the location of the JAR file though - you can't just ask the classloader to list everything it could get at.

    You should be able to work out the location of the JAR file based on the URL returned from ThisClassName.class.getResource("ThisClassName.class"), but it may be a tiny bit fiddly.

    File Not Found when running PHP with Nginx

    I had this error as well. In my case it was because there was another virtual host that was pointing to the same root directory.

    How to prevent a double-click using jQuery?

    You can do something like this to disable submit button when loading a new page with the same form:

    $("#btnConfirm").bind("click", function (e) {
      $("#btnConfirm ").css("pointer-events", "none");
    });
    

    The submit button could look like this:

    <input
        type="submit"
        name="ACMS_POST_Form_Confirm"
        value="confirm"
        id="btnConfirm"
    />
    

    Specifying and saving a figure with exact size in pixels

    This worked for me, based on your code, generating a 93Mb png image with color noise and the desired dimensions:

    import matplotlib.pyplot as plt
    import numpy
    
    w = 7195
    h = 3841
    
    im_np = numpy.random.rand(h, w)
    
    fig = plt.figure(frameon=False)
    fig.set_size_inches(w,h)
    ax = plt.Axes(fig, [0., 0., 1., 1.])
    ax.set_axis_off()
    fig.add_axes(ax)
    ax.imshow(im_np, aspect='normal')
    fig.savefig('figure.png', dpi=1)
    

    I am using the last PIP versions of the Python 2.7 libraries in Linux Mint 13.

    Hope that helps!

    PHP Session Destroy on Log Out Button

    // logout

    if(isset($_GET['logout'])) {
        session_destroy();
        unset($_SESSION['username']);
        header('location:login.php');
    }
    

    ?>

    Making a PowerShell POST request if a body param starts with '@'

    @Frode F. gave the right answer.

    By the Way Invoke-WebRequest also prints you the 200 OK and a lot of bla, bla, bla... which might be useful but I still prefer the Invoke-RestMethod which is lighter.

    Also, keep in mind that you need to use | ConvertTo-Json for the body only, not the header:

    $body = @{
     "UserSessionId"="12345678"
     "OptionalEmail"="[email protected]"
    } | ConvertTo-Json
    
    $header = @{
     "Accept"="application/json"
     "connectapitoken"="97fe6ab5b1a640909551e36a071ce9ed"
     "Content-Type"="application/json"
    } 
    
    Invoke-RestMethod -Uri "http://MyServer/WSVistaWebClient/RESTService.svc/member/search" -Method 'Post' -Body $body -Headers $header | ConvertTo-HTML
    

    and you can then append a | ConvertTo-HTML at the end of the request for better readability

    Retrieve a Fragment from a ViewPager

    Best solution is to use the extension we created at CodePath called SmartFragmentStatePagerAdapter. Following that guide, this makes retrieving fragments and the currently selected fragment from a ViewPager significantly easier. It also does a better job of managing the memory of the fragments embedded within the adapter.

    Initializing select with AngularJS and ng-repeat

    As suggested you need to use ng-options and unfortunately I believe you need to reference the array element for a default (unless the array is an array of strings).

    http://jsfiddle.net/FxM3B/3/

    The JavaScript:

    function AppCtrl($scope) {
    
    
        $scope.operators = [
            {value: 'eq', displayName: 'equals'},
            {value: 'neq', displayName: 'not equal'}
         ]
    
        $scope.filterCondition={
            operator: $scope.operators[0]
        }
    }
    

    The HTML:

    <body ng-app ng-controller="AppCtrl">
    <div>Operator is: {{filterCondition.operator.value}}</div>
    <select ng-model="filterCondition.operator" ng-options="operator.displayName for operator in operators">
    </select>
    </body>
    

    Add characters to a string in Javascript

    You can also keep adding strings to an existing string like so:

    var myString = "Hello ";
    myString += "World";
    myString += "!";
    

    the result would be -> Hello World!

    Java/ JUnit - AssertTrue vs AssertFalse

    I think it's just for your convenience (and the readers of your code)

    Your code, and your unit tests should be ideally self documenting which this API helps with,

    Think abt what is more clear to read:

    AssertTrue(!(a > 3));
    

    or

    AssertFalse(a > 3);
    

    When you open your tests after xx months when your tests suddenly fail, it would take you much less time to understand what went wrong in the second case (my opinion). If you disagree, you can always stick with AssertTrue for all cases :)

    How to align LinearLayout at the center of its parent?

    @jksschneider explation is almost right. Make sure that you haven't set any gravity to parent layout, and then set layout_gravity="center" to your view or layout.

    JQuery $.each() JSON array object iteration

    Assign the second variable for the $.each function() as well, makes it lot easier as it'll provide you the data (so you won't have to work with the indicies).

    $.each(json, function(arrayID,group) {
                console.log('<a href="'+group.GROUP_ID+'">');
        $.each(group.EVENTS, function(eventID,eventData) {
                console.log('<p>'+eventData.SHORT_DESC+'</p>');
         });
    });
    

    Should print out everything you were trying in your question.

    http://jsfiddle.net/niklasvh/hZsQS/

    edit renamed the variables to make it bit easier to understand what is what.

    TypeError: unhashable type: 'list' when using built-in set function

    Definitely not the ideal solution, but it's easier for me to understand if I convert the list into tuples and then sort it.

    mylist = [[1,2,3,4],[4,5,6,7]]
    mylist2 = []
    for thing in mylist:
        thing = tuple(thing)
        mylist2.append(thing)
    set(mylist2)
    

    How print out the contents of a HashMap<String, String> in ascending order based on its values?

    You can use a list of the entry set rather than the key set and it is a more natural choice given you are sorting based on the value. This avoids a lot of unneeded lookups in the sorting and printing of the entries.

    Map<String, String> map = ...
    List<Map.Entry<String, String>> listOfEntries = new ArrayList<Map.Entry<String, String>>(map.entrySet());
    Collections.sort(listOfEntries, new SortByValueComparator());
    for(Map.Entry<String, String> entry: listOfEntries)
       System.out.println(entry);
    
    static class SortByValueComparator implements Comparator<Map.Entry<String, String>> {
       public int compareTo(Map.Entry<String, String> e1, Map.Entry<String, String> e2) {
           return e1.getValue().compateTo(e2.getValue());
       }
    }
    

    transform object to array with lodash

    Object to Array

    Of all the answers I think this one is the best:

    let arr = Object.entries(obj).map(([key, val]) => ({ key, ...val }))
    

    that transforms:

    {
      a: { p: 1, q: 2},
      b: { p: 3, q: 4}
    }
    

    to:

    [
      { key: 'a', p: 1, q: 2 }, 
      { key: 'b', p: 3, q: 4 }
    ]
    

    Array to Object

    To transform back:

    let obj = arr.reduce((obj, { key, ...val }) => { obj[key] = { ...val }; return obj; }, {})
    

    To transform back keeping the key in the value:

    let obj = arr.reduce((obj, { key, ...val }) => { obj[key] = { key, ...val }; return obj; }, {})
    

    Will give:

    {
      a: { key: 'a', p: 1, q: 2 },
      b: { key: 'b', p: 3, q: 4 }
    }
    

    For the last example you can also use lodash _.keyBy(arr, 'key') or _.keyBy(arr, i => i.key).

    how to check for datatype in node js- specifically for integer

    I think of two ways to test for the type of a value:

    Method 1:

    You can use the isNaN javascript method, which determines if a value is NaN or not. But because in your case you are testing a numerical value converted to string, Javascript is trying to guess the type of the value and converts it to the number 5 which is not NaN. That's why if you console.log out the result, you will be surprised that the code:

    if (isNaN(i)) {
        console.log('This is not number');
    }
    

    will not return anything. For this reason a better alternative would be the method 2.

    Method 2:

    You may use javascript typeof method to test the type of a variable or value

    if (typeof i != "number") {
        console.log('This is not number');
    }
    

    Notice that i'm using double equal operator, because in this case the type of the value is a string but Javascript internally will convert to Number.

    A more robust method to force the value to numerical type is to use Number.isNaN which is part of new Ecmascript 6 (Harmony) proposal, hence not widespread and fully supported by different vendors.

    How to delete rows in tables that contain foreign keys to other tables

    First, as a one-time data-scrubbing exercise, delete the orphaned rows e.g.

    DELETE 
      FROM ReferencingTable 
     WHERE NOT EXISTS (
                       SELECT * 
                         FROM MainTable AS T1
                        WHERE T1.pk_col_1 = ReferencingTable.pk_col_1
                      );
    

    Second, as a one-time schema-alteration exercise, add the ON DELETE CASCADE referential action to the foreign key on the referencing table e.g.

    ALTER TABLE ReferencingTable DROP 
       CONSTRAINT fk__ReferencingTable__MainTable;
    
    ALTER TABLE ReferencingTable ADD 
       CONSTRAINT fk__ReferencingTable__MainTable 
          FOREIGN KEY (pk_col_1)
          REFERENCES MainTable (pk_col_1)
          ON DELETE CASCADE;
    

    Then, forevermore, rows in the referencing tables will automatically be deleted when their referenced row is deleted.

    How to add element in Python to the end of list using list.insert?

    list.insert with any index >= len(of_the_list) places the value at the end of list. It behaves like append

    Python 3.7.4
    >>>lst=[10,20,30]
    >>>lst.insert(len(lst), 101)
    >>>lst
    [10, 20, 30, 101]
    >>>lst.insert(len(lst)+50, 202)
    >>>lst
    [10, 20, 30, 101, 202]
    

    Time complexity, append O(1), insert O(n)

    Embedding JavaScript engine into .NET

    There is an implementation of an ActiveX Scripting Engine Host in C# available here: parse and execute JS by C#

    It allows to use Javascript (or VBScript) directly from C#, in native 32-bit or 64-bit processes. The full source is ~500 lines of C# code. It only has an implicit dependency on the installed JScript (or VBScript) engine DLL.

    For example, the following code:

    Console.WriteLine(ScriptEngine.Eval("jscript", "1+2/3"));
    

    will display 1.66666666666667

    Dynamically set value of a file input

    I am working on an angular js app, andhavecome across a similar issue. What i did was display the image from the db, then created a button to remove or keep the current image. If the user decided to keep the current image, i changed the ng-submit attribute to another function whihc doesnt require image validation, and updated the record in the db without touching the original image path name. The remove image function also changed the ng-submit attribute value back to a function that submits the form and includes image validation and upload. Also a bit of javascript to slide the into view to upload a new image.

    Rails 4 LIKE query - ActiveRecord adds quotes

    .find(:all, where: "value LIKE product_%", params: { limit: 20, page: 1 })
    

    "SyntaxError: Unexpected token < in JSON at position 0"

    Maybe some permission error would be there just try switching the browser and log in from an authorized account.

    How to output a comma delimited list in jinja python template?

    you could also use the builtin "join" filter (http://jinja.pocoo.org/docs/templates/#join like this:

    {{ users|join(', ') }}
    

    case-insensitive matching in xpath?

    One possible PHP solution:

    // load XML to SimpleXML
    $x = simplexml_load_string($xmlstr);
    
    // index it by title once
    $index = array();
    foreach ($x->CD as &$cd) {
      $title = strtolower((string)$cd['title']); 
      if (!array_key_exists($title, $index)) $index[$title] = array();
      $index[$title][] = &$cd;
    }
    
    // query the index 
    $result = $index[strtolower("EMPIRE BURLESQUE")];
    

    How can I show data using a modal when clicking a table row (using bootstrap)?

    The best practice is to ajax load the order information when click tr tag, and render the information html in $('#orderDetails') like this:

      $.get('the_get_order_info_url', { order_id: the_id_var }, function(data){
        $('#orderDetails').html(data);
      }, 'script')
    

    Alternatively, you can add class for each td that contains the order info, and use jQuery method $('.class').html(html_string) to insert specific order info into your #orderDetails BEFORE you show the modal, like:

      <% @restaurant.orders.each do |order| %>
      <!-- you should add more class and id attr to help control the DOM -->
      <tr id="order_<%= order.id %>" onclick="orderModal(<%= order.id  %>);">
        <td class="order_id"><%= order.id %></td>
        <td class="customer_id"><%= order.customer_id %></td>
        <td class="status"><%= order.status %></td>
      </tr>
      <% end %>
    

    js:

    function orderModal(order_id){
      var tr = $('#order_' + order_id);
      // get the current info in html table 
      var customer_id = tr.find('.customer_id');
      var status = tr.find('.status');
    
      // U should work on lines here:
      var info_to_insert = "order: " + order_id + ", customer: " + customer_id + " and status : " + status + ".";
      $('#orderDetails').html(info_to_insert);
    
      $('#orderModal').modal({
        keyboard: true,
        backdrop: "static"
      });
    };
    

    That's it. But I strongly recommend you to learn sth about ajax on Rails. It's pretty cool and efficient.

    How can I make visible an invisible control with jquery? (hide and show not work)

    Here's some code I use to deal with this.

    First we show the element, which will typically set the display type to "block" via .show() function, and then set the CSS rule to "visible":

    jQuery( '.element' ).show().css( 'visibility', 'visible' );
    

    Or, assuming that the class that is hiding the element is called hidden, such as in Twitter Bootstrap, toggleClass() can be useful:

    jQuery( '.element' ).toggleClass( 'hidden' );
    

    Lastly, if you want to chain functions, perhaps with fancy with a fading effect, you can do it like so:

    jQuery( '.element' ).css( 'visibility', 'visible' ).fadeIn( 5000 );
    

    How do I use the JAVA_OPTS environment variable?

    Actually, you can, even though accepted answer saying that you can't.

    There is a _JAVA_OPTIONS environment variable, more about it here

    throwing an exception in objective-c/cocoa

    Use NSError to communicate failures rather than exceptions.

    Quick points about NSError:

    • NSError allows for C style error codes (integers) to clearly identify the root cause and hopefully allow the error handler to overcome the error. You can wrap error codes from C libraries like SQLite in NSError instances very easily.

    • NSError also has the benefit of being an object and offers a way to describe the error in more detail with its userInfo dictionary member.

    • But best of all, NSError CANNOT be thrown so it encourages a more proactive approach to error handling, in contrast to other languages which simply throw the hot potato further and further up the call stack at which point it can only be reported to the user and not handled in any meaningful way (not if you believe in following OOP's biggest tenet of information hiding that is).

    Reference Link: Reference

    Use different Python version with virtualenv

    [November 2019] I needed to install a Python 3.7 environment (env) on my Python 3.8-based Arch Linux system. Python 3.7 was no longer on the system, so I could not downgrade Python, to install a package that I needed.

    Furthermore, I wanted to use that package / Python 3.7 inside a virtual environment (venv). This is how I did it.


    Download Python version source files:

    I downloaded the Python 3.7.4 source files from

    https://www.python.org/downloads/source/

    to

    /mnt/Vancouver/apps/python_versions/src/Python-3.7.4.tgz

    I then extracted that archive (source files) to

    /mnt/Vancouver/apps/python_versions/src/Python-3.7.4/


    Installation:

    [Note: in my system env, not a venv.]

    cd /mnt/Vancouver/apps/python_versions/src/Python-3.7.4/
    time ./configure                 ## 17 sec
    time make                        ## 1 min 51 sec
    time sudo make install           ## 18 sec
    time make clean                  ## 0.3 sec
    

    Examine installed Python versions:

    $ which python
    /usr/bin/python
    
    $ python --version
    Python 3.8.0
    
    $ which python3.7
    /usr/local/bin/python3.7
    
    $ python    ## Python 3.8 [system / env]
    Python 3.8.0 (default, Oct 23 2019, 18:51:26) 
    [GCC 9.2.0] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>>
    
    $ python3.7    ## newly-installed Python 3.7 package
    Python 3.7.4 (default, Nov 20 2019, 11:36:53) 
    [GCC 9.2.0] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import sys
    >>> print(sys.version)
    3.7.4 (default, Nov 20 2019, 11:36:53) 
    [GCC 9.2.0]
    >>>
    
    $ python3.7 --version                                                                                                 
    Python 3.7.4
    

    How to create a venv for a specific Python version:

    https://docs.python.org/3/tutorial/venv.html

    12.2. CREATING VIRTUAL ENVIRONMENTS

    The module used to create and manage virtual environments is called venv. venv will usually install the most recent version of Python that you have available. If you have multiple versions of Python on your system, you can select a specific Python version by running python3 or whichever version you want.

    To create a virtual environment, decide upon a directory where you want to place it, and run the venv module as a script with the directory path:

    python3 -m venv tutorial-env

    This will create the tutorial-env directory if it doesn’t exist, and also create directories inside it containing a copy of the Python interpreter, the standard library, and various supporting files. ...


    Create Python 3.7 venv [on a Python 3.8 operating env / system]:

    python3.7 -m venv ~/venv/py3.7      ## create Python 3.7-based venv
    source ~/venv/py3.7/bin/activate    ## activate that venv
    deactivate                          ## deactivate that venv (when done, there)
    

    Added to ~/.bashrc:

    alias p37='echo "   [Python 3.7 venv (source ~/venv/py3.7/bin/activate)]" && source ~/venv/py3.7/bin/activate'
    

    Test Python 3.7 venv:

    $ p37                                                                                                                 
    [Python 3.7 venv (source ~/venv/py3.7/bin/activate)]
    
    (py3.7)$ python --version
    Python 3.7.4
    
    (py3.7)$ python
    Python 3.7.4 (default, Nov 20 2019, 11:36:53) 
    [GCC 9.2.0] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import sys
    >>> print(sys.version)
    3.7.4 (default, Nov 20 2019, 11:36:53) 
    [GCC 9.2.0] 
    >>>
    

    Convert a bitmap into a byte array

    More simple:

    return (byte[])System.ComponentModel.TypeDescriptor.GetConverter(pImagen).ConvertTo(pImagen, typeof(byte[]))
    

    Undefined symbols for architecture x86_64 on Xcode 6.1

    Apparently, your class "Format" is involved in the problem. Check your declaration of this class, especially if you did it inside another class you probably forgot the @implementation or something similar.

    How to convert string to boolean in typescript Angular 4

    Method 1 :

    var stringValue = "true";
    var boolValue = (/true/i).test(stringValue) //returns true
    

    Method 2 :

    var stringValue = "true";
    var boolValue = (stringValue =="true");   //returns true
    

    Method 3 :

    var stringValue = "true";
    var boolValue = JSON.parse(stringValue);   //returns true
    

    Method 4 :

    var stringValue = "true";
    var boolValue = stringValue.toLowerCase() == 'true'; //returns true
    

    Method 5 :

    var stringValue = "true";
    var boolValue = getBoolean(stringValue); //returns true
    function getBoolean(value){
       switch(value){
            case true:
            case "true":
            case 1:
            case "1":
            case "on":
            case "yes":
                return true;
            default: 
                return false;
        }
    }
    

    source: http://codippa.com/how-to-convert-string-to-boolean-javascript/

    Position Relative vs Absolute?

    Absolute CSS Positioning

    position: absolute;

    Absolute positioning is the easiest to understand. You start with the CSS position property:

    position: absolute;
    

    This tells the browser that whatever is going to be positioned should be removed from the normal flow of the document and will be placed in an exact location on the page. It won't affect how the elements before it or after it in the HTML are positioned on the Web page however it will be subject to it's parents' positioning unless you override it.

    If you want to position an element 10 pixels from the top of the document window, you would use the top offset to position it there with absolute positioning:

    position: absolute;
    top: 10px;
    

    This element will then always display 10px from the top of the page regardless of what content passes through, under or over the element (visually).

    The four positioning properties are:

    1. top
    2. right
    3. bottom
    4. left

    To use them, you need to think of them as offset properties. In other words, an element positioned right: 2px is not moved right 2px. It's right side is offset from the right side of the window (or its position overriding parent) by 2px. The same is true for the other three.

    Relative Positioning

    position: relative;

    Relative positioning uses the same four positioning properties as absolute positioning. But instead of basing the position of the element upon the browser view port, it starts from where the element would be if it were still in the normal flow.

    For example, if you have three paragraphs on your Web page, and the third has a position: relative style placed on it, its position will be offset based on its current location-- not from the original sides of the view port.

    Paragraph 1.

    Paragraph 2.

    Paragraph 3.

    In the above example, the third paragraph will be positioned 3em from the left side of the container element, but will still be below the first two paragraphs. It would remain in the normal flow of the document, and just be offset slightly. If you changed it to position: absolute;, anything following it would display on top of it, because it would no longer be in the normal flow of the document.

    Notes:

    • the default width of an element that is absolutely positioned is the width of the content within it, unlike an element that is relatively positioned where it's default width is 100% of the space it can fill.

    • You can have elements that overlap with absolutely positioned elements, whereas you cannot do this with relatively positioned elements (natively i.e without the use of negative margins/positioning)


    lots pulled from: this resource

    Change jsp on button click

    If you wanna do with a button click and not the other way. You can do it by adding location.href to your button. Here is how I'm using

    <button class="btn btn-lg btn-primary" id="submit" onclick="location.href ='/dashboard'" >Go To Dashboard</button>
    

    The button above uses bootstrap classes for styling. Without styling, the simplest code would be

    <button onclick="location.href ='/dashboard'" >Go To Dashboard</button>
    

    The /dashboard is my JSP page, If you are using extension too then used /dashboard.jsp

    How to check if field is null or empty in MySQL?

    You can create a function to make this easy.

    create function IFEMPTY(s text, defaultValue text)
    returns text deterministic
    return if(s is null or s = '', defaultValue, s);
    

    Using:

    SELECT IFEMPTY(field1, 'empty') as field1 
    from tablename
    

    Console.log(); How to & Debugging javascript

    Essentially console.log() allows you to output variables in your javascript debugger of choice instead of flashing an alert() every time you want to inspect something... additionally, for more complex objects it will give you a tree view to inspect the object further instead of having to convert elements to strings like an alert().

    Delay/Wait in a test case of Xcode UI testing

    Additionally, you can just sleep:

    sleep(10)
    

    Since the UITests run in another process, this works. I don’t know how advisable it is, but it works.

    Aligning text and image on UIButton with imageEdgeInsets and titleEdgeInsets

    Here is a simple example of how to use imageEdgeInsets This will make a 30x30 button with a hittable area 10 pixels bigger all the way around (50x50)

        var expandHittableAreaAmt : CGFloat = 10
        var buttonWidth : CGFloat = 30
        var button = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
        button.frame = CGRectMake(0, 0, buttonWidth+expandHittableAreaAmt, buttonWidth+expandHittableAreaAmt)
        button.imageEdgeInsets = UIEdgeInsetsMake(expandHittableAreaAmt, expandHittableAreaAmt, expandHittableAreaAmt, expandHittableAreaAmt)
        button.setImage(UIImage(named: "buttonImage"), forState: .Normal)
        button.addTarget(self, action: "didTouchButton:", forControlEvents:.TouchUpInside)
    

    Unable to start debugging on the web server. Could not start ASP.NET debugging VS 2010, II7, Win 7 x64

    Visual Studio, when starting up, will (for some reason) attempt to access the URL:

    /debugattach.aspx

    If you have a rewrite rule that redirects (or otherwise catches), say, .aspx files, somewhere else then you will get this error. The solution is to add this section to the beginning of your web.config's <system.webServer>/<rewrite>/<rules> section:

    <rule name="Ignore Default.aspx" enabled="true" stopProcessing="true">
        <match url="^debugattach\.aspx" />
        <conditions logicalGrouping="MatchAll" trackAllCaptures="false" />
        <action type="None" />
    </rule>
    

    This will make sure to catch this one particular request, do nothing, and, most importantly, stop execution so none of your other rules will get run. This is a robust solution, so feel free to keep this in your config file for production.

    cURL equivalent in Node.js?

    You can try using POSTMAN Chrome app for your request and you can generate node js code from there

    Add leading zeroes/0's to existing Excel values to certain length

    The more efficient (less obtrusive) way of doing this is through custom formatting.

    1. Highlight the column/array you want to style.
    2. Click ctrl + 1 or Format -> Format Cells.
    3. In the Number tab, choose Custom.
    4. Set the Custom formatting to 000#. (zero zero zero #)

    Note that this does not actually change the value of the cell. It only displays the leading zeroes in the worksheet.

    Python Script Uploading files via FTP

    To avoid getting the encryption error you can also try out below commands

    ftp = ftplib.FTP_TLS("ftps.dummy.com")
    ftp.login("username", "password")
    ftp.prot_p()
    file = open("filename", "rb")
    ftp.storbinary("STOR filename", file)
    file.close()
    ftp.close()
    

    ftp.prot_p() ensure that your connections are encrypted

    Bootstrap 3.0 Sliding Menu from left

    I believe that although javascript is an option here, you have a smoother animation through forcing hardware accelerate with CSS3. You can achieve this by setting the following CSS3 properties on the moving div:

    div.hardware-accelarate {
         -webkit-transform: translate3d(0,0,0);
            -moz-transform: translate3d(0,0,0);
             -ms-transform: translate3d(0,0,0);
              -o-transform: translate3d(0,0,0);
                 transform: translate3d(0,0,0);
    }
    

    I've made a plunkr setup for ya'll to test and tweak...

    What's the pythonic way to use getters and setters?

    What's the pythonic way to use getters and setters?

    The "Pythonic" way is not to use "getters" and "setters", but to use plain attributes, like the question demonstrates, and del for deleting (but the names are changed to protect the innocent... builtins):

    value = 'something'
    
    obj.attribute = value  
    value = obj.attribute
    del obj.attribute
    

    If later, you want to modify the setting and getting, you can do so without having to alter user code, by using the property decorator:

    class Obj:
        """property demo"""
        #
        @property            # first decorate the getter method
        def attribute(self): # This getter method name is *the* name
            return self._attribute
        #
        @attribute.setter    # the property decorates with `.setter` now
        def attribute(self, value):   # name, e.g. "attribute", is the same
            self._attribute = value   # the "value" name isn't special
        #
        @attribute.deleter     # decorate with `.deleter`
        def attribute(self):   # again, the method name is the same
            del self._attribute
    

    (Each decorator usage copies and updates the prior property object, so note that you should use the same name for each set, get, and delete function/method.

    After defining the above, the original setting, getting, and deleting code is the same:

    obj = Obj()
    obj.attribute = value  
    the_value = obj.attribute
    del obj.attribute
    

    You should avoid this:

    def set_property(property,value):  
    def get_property(property):  
    

    Firstly, the above doesn't work, because you don't provide an argument for the instance that the property would be set to (usually self), which would be:

    class Obj:
    
        def set_property(self, property, value): # don't do this
            ...
        def get_property(self, property):        # don't do this either
            ...
    

    Secondly, this duplicates the purpose of two special methods, __setattr__ and __getattr__.

    Thirdly, we also have the setattr and getattr builtin functions.

    setattr(object, 'property_name', value)
    getattr(object, 'property_name', default_value)  # default is optional
    

    The @property decorator is for creating getters and setters.

    For example, we could modify the setting behavior to place restrictions the value being set:

    class Protective(object):
    
        @property
        def protected_value(self):
            return self._protected_value
    
        @protected_value.setter
        def protected_value(self, value):
            if acceptable(value): # e.g. type or range check
                self._protected_value = value
    

    In general, we want to avoid using property and just use direct attributes.

    This is what is expected by users of Python. Following the rule of least-surprise, you should try to give your users what they expect unless you have a very compelling reason to the contrary.

    Demonstration

    For example, say we needed our object's protected attribute to be an integer between 0 and 100 inclusive, and prevent its deletion, with appropriate messages to inform the user of its proper usage:

    class Protective(object):
        """protected property demo"""
        #
        def __init__(self, start_protected_value=0):
            self.protected_value = start_protected_value
        # 
        @property
        def protected_value(self):
            return self._protected_value
        #
        @protected_value.setter
        def protected_value(self, value):
            if value != int(value):
                raise TypeError("protected_value must be an integer")
            if 0 <= value <= 100:
                self._protected_value = int(value)
            else:
                raise ValueError("protected_value must be " +
                                 "between 0 and 100 inclusive")
        #
        @protected_value.deleter
        def protected_value(self):
            raise AttributeError("do not delete, protected_value can be set to 0")
    

    (Note that __init__ refers to self.protected_value but the property methods refer to self._protected_value. This is so that __init__ uses the property through the public API, ensuring it is "protected".)

    And usage:

    >>> p1 = Protective(3)
    >>> p1.protected_value
    3
    >>> p1 = Protective(5.0)
    >>> p1.protected_value
    5
    >>> p2 = Protective(-5)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 3, in __init__
      File "<stdin>", line 15, in protected_value
    ValueError: protectected_value must be between 0 and 100 inclusive
    >>> p1.protected_value = 7.3
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 17, in protected_value
    TypeError: protected_value must be an integer
    >>> p1.protected_value = 101
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 15, in protected_value
    ValueError: protectected_value must be between 0 and 100 inclusive
    >>> del p1.protected_value
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 18, in protected_value
    AttributeError: do not delete, protected_value can be set to 0
    

    Do the names matter?

    Yes they do. .setter and .deleter make copies of the original property. This allows subclasses to properly modify behavior without altering the behavior in the parent.

    class Obj:
        """property demo"""
        #
        @property
        def get_only(self):
            return self._attribute
        #
        @get_only.setter
        def get_or_set(self, value):
            self._attribute = value
        #
        @get_or_set.deleter
        def get_set_or_delete(self):
            del self._attribute
    

    Now for this to work, you have to use the respective names:

    obj = Obj()
    # obj.get_only = 'value' # would error
    obj.get_or_set = 'value'  
    obj.get_set_or_delete = 'new value'
    the_value = obj.get_only
    del obj.get_set_or_delete
    # del obj.get_or_set # would error
    

    I'm not sure where this would be useful, but the use-case is if you want a get, set, and/or delete-only property. Probably best to stick to semantically same property having the same name.

    Conclusion

    Start with simple attributes.

    If you later need functionality around the setting, getting, and deleting, you can add it with the property decorator.

    Avoid functions named set_... and get_... - that's what properties are for.

    What is the difference between window, screen, and document in Javascript?

    The window is the actual global object.

    The screen is the screen, it contains properties about the user's display.

    The document is where the DOM is.

    Incorrect string value: '\xF0\x9F\x8E\xB6\xF0\x9F...' MySQL

    It may be obvious, but it still was surprising to me, that SET NAMES utf8 is not compatible with utf8mb4 encoding. So for some apps changing table/column encoding was not enough. I had to change encoding in app configuration.

    Redmine (ruby, ROR)

    In config/database.yml:

    production:
      adapter: mysql2
      database: redmine
      host: localhost
      username: redmine
      password: passowrd
      encoding: utf8mb4
    

    Custom Yii application (PHP)

    In config/db.php:

    return [
        'class' => yii\db\Connection::class,
        'dsn' => 'mysql:host=localhost;dbname=yii',
        'username' => 'yii',
        'password' => 'password',
        'charset' => 'utf8mb4',
    ],
    

    If you have utf8mb4 as a column/table encoding and still getting errors like this, make sure that you have configured correct charset for DB connection in your application.

    How can I initialize an ArrayList with all zeroes in Java?

    It's not like that. ArrayList just uses array as internal respentation. If you add more then 60 elements then underlaying array will be exapanded. How ever you can add as much elements to this array as much RAM you have.

    How to parseInt in Angular.js

    Inside template this working finely.

    <!DOCTYPE html>
    <html>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
    <body>
    
    <div ng-app="">
    <input ng-model="name" value="0">
    <p>My first expression: {{ (name-0) + 5 }}</p>
    </div>
    
    </body>
    </html>
    

    How to Set RadioButtonFor() in ASp.net MVC 2 as Checked by default

    If you're using jquery, you can call this right before your radio buttons.

    $('input:radio:first').attr('checked', true);
    

    ^ This will check the first radio box, but you can look at more jquery to cycle through to the one you want selected.

    Check if selected dropdown value is empty using jQuery

    You can try this also-

    if( !$('#EventStartTimeMin').val() ) {
    // do something
    }
    

    How do I enable --enable-soap in php on linux?

    As far as your question goes: no, if activating from .ini is not enough and you can't upgrade PHP, there's not much you can do. Some modules, but not all, can be added without recompilation (zypper install php5-soap, yum install php-soap). If it is not enough, try installing some PEAR class for interpreted SOAP support (NuSOAP, etc.).

    In general, the double-dash --switches are designed to be used when recompiling PHP from scratch.

    You would download the PHP source package (as a compressed .tgz tarball, say), expand it somewhere and then, e.g. under Linux, run the configure script

    ./configure --prefix ...
    

    The configure command used by your PHP may be shown with phpinfo(). Repeating it identical should give you an exact copy of the PHP you now have installed. Adding --enable-soap will then enable SOAP in addition to everything else.

    That said, if you aren't familiar with PHP recompilation, don't do it. It also requires several ancillary libraries that you might, or might not, have available - freetype, gd, libjpeg, XML, expat, and so on and so forth (it's not enough they are installed; they must be a developer version, i.e. with headers and so on; in most distributions, having libjpeg installed might not be enough, and you might need libjpeg-dev also).

    I have to keep a separate virtual machine with everything installed for my recompilation purposes.

    sql server invalid object name - but tables are listed in SSMS tables list

    I ran into the problem with : ODBC and SQL-Server-Authentication in ODBC and Firedac-Connection

    Solution : I had to set the Param MetaDefSchema to sqlserver username : FDConnection1.Params.AddPair('MetaDefSchema', self.FDConnection1.Params.UserName);

    The wikidoc sais : MetaDefSchema=Default schema name. The Design time code >>excludes<< !! the schema name from the object SQL-Server-Authenticatoinname if it is equal to MetaDefSchema.

    without setting, the automatic coder creates : dbname.username.tablename -> invalid object name

    With setting MetaDefSchema to sqlserver-username : dbname.tablename -> works !

    See also the embarcadero-doc at : http://docwiki.embarcadero.com/RADStudio/Rio/en/Connect_to_Microsoft_SQL_Server_(FireDAC)

    Hope, it helps someone else..

    regards, Lutz

    Error: Unexpected value 'undefined' imported by the module

    Make sure the modules don't import each other. So, there shouldn't be

    In Module A: imports[ModuleB]

    In Module B: imports[ModuleA]

    Query grants for a table in postgres

    \z mytable from psql gives you all the grants from a table, but you'd then have to split it up by individual user.

    How do I register a DLL file on Windows 7 64-bit?

    I just tested this extremely simple method and it works perfectly--but I use the built-in Administrator account, so I don't have to jump through hoops for elevated privileges.

    The following batch file relieves the user of the need to move files in/out of system folders. It also leaves it up to Windows to apply the proper version of Regsvr32.

    INSTRUCTIONS:

    • In the folder that contains the library (-.dll or -.ax) file you wish to register, open a new text file and paste in ONE of the routines below :

      echo BEGIN DRAG-AND-DROP %n1 REGISTRAR FOR 64-BIT SYSTEMS
      copy %1 C:\Windows\System32
      regsvr32 "%nx1"
      echo END BATCH FILE
      pause
      

      echo BEGIN DRAG-AND-DROP %n1 REGISTRAR FOR 32-BIT SYSTEMS
      copy %1 C:\Windows\SysWOW64
      regsvr32 "%nx1"
      echo END BATCH FILE
      pause
      
    • Save your new text file as a batch (-.bat) file; then simply drag-and-drop your -.dll or -.ax file on top of the batch file.

    • If UAC doesn't give you the opportunity to run the batch file as an Administrator, you may need to manually elevate privileges (instructions are for Windows 7):

      1. Right-click on the batch file;
      2. Select Create shortcut;
      3. Right-click on the shortcut;
      4. Select Properties;
      5. Click the Compatibility tab;
      6. Check the box labeled Run this program as administrator;
      7. Drag-and-drop your -.dll or -.ax file on top of the new shortcut instead of the batch file.

    That's it. I chose COPY instead of MOVE to prevent the failure of any UAC-related follow-up attempt(s). Successful registration should be followed by deletion of the original library (-.dll or -.ax) file.

    Don't worry about copies made to the system folder (C:\Windows\System32 or C:\Windows\SysWOW64) by previous passes--they will be overwritten every time you run the batch file.

    Unless you ran the wrong batch file, in which case you will probably want to delete the copy made to the wrong system folder (C:\Windows\System32 or C:\Windows\SysWOW64) before running the proper batch file, ...or...

    • Help Windows choose the right library file to register by fully-qualifying its directory location.

      1. From the right batch file copy the system folder path
        • If 64-bit: C:\Windows\System32
        • If 32-bit: C:\Windows\SysWOW64
      2. Paste it on the next line so that it precedes %nx1
        • If 64-bit: regsvr32 "C:\Windows\System32\%nx1"
        • If 32-bit: regsvr32 "C:\Windows\SysWOW64\%nx1"
          • Paste path inside quotation marks
          • Insert backslash to separate %nx1 from system folder path
        • or ...

    • Run this shotgun batch file, which will (in order):

      1. Perform cleanup of aborted registration processes
        • Reverse any registration process completed by your library file;
        • Delete any copies of your library file that have been saved to either system folder;
        • Pause to allow you to terminate the batch file at this point (and run another if you would like).
      2. Attempt 64-Bit Installation on your library file
        • Copy your library file to C:\Windows\System32;
        • Register your library file as a 64-bit process;
        • Pause to allow you to terminate the batch file at this point.
      3. Undo 64-Bit Installation
        • Reverse any registration of your library file as a 64-bit process;
        • Delete your library file from C:\Windows\System32;
        • Pause to allow you to terminate the batch file at this point (and run another if you would like).
      4. Attempt 32-Bit Installation on your library file
        • Copy your library file to C:\Windows\SystemWOW64
        • Register your library file as a 32-bit process;
        • Pause to allow you to terminate the batch file at this point.
      5. Delete original, unregistered copy of library file

    Express.js req.body undefined

    I solved it with:

    app.post('/', bodyParser.json(), (req, res) => {//we have req.body JSON
    });
    

    How to Git stash pop specific stash in 1.8.3?

    First check the list:-

    git stash list
    

    copy the index you wanted to pop from the stash list

    git stash pop stash@{index_number}
    

    eg.:

    git stash pop stash@{1}
    

    LEFT OUTER JOIN in LINQ

    I would like to add that if you get the MoreLinq extension there is now support for both homogenous and heterogeneous left joins now

    http://morelinq.github.io/2.8/ref/api/html/Overload_MoreLinq_MoreEnumerable_LeftJoin.htm

    example:

    //Pretend a ClientCompany object and an Employee object both have a ClientCompanyID key on them
    
    return DataContext.ClientCompany
        .LeftJoin(DataContext.Employees,                         //Table being joined
            company => company.ClientCompanyID,                  //First key
            employee => employee.ClientCompanyID,                //Second Key
            company => new {company, employee = (Employee)null}, //Result selector when there isn't a match
            (company, employee) => new { company, employee });   //Result selector when there is a match
    

    EDIT:

    In retrospect this may work, but it converts the IQueryable to an IEnumerable as morelinq does not convert the query to SQL.

    You can instead use a GroupJoin as described here: https://stackoverflow.com/a/24273804/4251433

    This will ensure that it stays as an IQueryable in case you need to do further logical operations on it later.

    CocoaPods Errors on Project Build

    For me to get rid of this error, I needed to delete the Pods directory and delete the Podfile.lock file.

    What is CDATA in HTML?

    From http://en.wikipedia.org/wiki/CDATA:

    Since it is useful to be able to use less-than signs (<) and ampersands (&) in web page scripts, and to a lesser extent styles, without having to remember to escape them, it is common to use CDATA markers around the text of inline and elements in XHTML documents. But so that the document can also be parsed by HTML parsers, which do not recognise the CDATA markers, the CDATA markers are usually commented-out, as in this JavaScript example:

    <script type="text/javascript">
    //<![CDATA[
    document.write("<");
    //]]>
    </script>
    

    @Cacheable key on multiple method arguments

    You can use a Spring-EL expression, for eg on JDK 1.7:

    @Cacheable(value="bookCache", key="T(java.util.Objects).hash(#p0,#p1, #p2)")
    

    How to use regex in XPath "contains" function

    XPath 1.0 doesn't handle regex natively, you could try something like

    //*[starts-with(@id, 'sometext') and ends-with(@id, '_text')]
    

    (as pointed out by paul t, //*[boolean(number(substring-before(substring-after(@id, "sometext"), "_text")))] could be used to perform the same check your original regex does, if you need to check for middle digits as well)

    In XPath 2.0, try

    //*[matches(@id, 'sometext\d+_text')]
    

    C++ static virtual members?

    No, this is not possible, because static member functions lack a this pointer. And static members (both functions and variables) are not really class members per-se. They just happen to be invoked by ClassName::member, and adhere to the class access specifiers. Their storage is defined somewhere outside the class; storage is not created each time you instantiated an object of the class. Pointers to class members are special in semantics and syntax. A pointer to a static member is a normal pointer in all regards.

    virtual functions in a class needs the this pointer, and is very coupled to the class, hence they can't be static.

    How to use KeyListener

    The class which implements KeyListener interface becomes our custom key event listener. This listener can not directly listen the key events. It can only listen the key events through intermediate objects such as JFrame. So

    1. Make one Key listener class as

      class MyListener implements KeyListener{
      
         // override all the methods of KeyListener interface.
      }
      
    2. Now our class MyKeyListener is ready to listen the key events. But it can not directly do so.

    3. Create any object like JFrame object through which MyListener can listen the key events. for that you need to add MyListener object to the JFrame object.

      JFrame f=new JFrame();
      f.addKeyListener(new MyKeyListener);
      

    Get the POST request body from HttpServletRequest

    This works for both GET and POST:

    @Context
    private HttpServletRequest httpRequest;
    
    
    private void printRequest(HttpServletRequest httpRequest) {
        System.out.println(" \n\n Headers");
    
        Enumeration headerNames = httpRequest.getHeaderNames();
        while(headerNames.hasMoreElements()) {
            String headerName = (String)headerNames.nextElement();
            System.out.println(headerName + " = " + httpRequest.getHeader(headerName));
        }
    
        System.out.println("\n\nParameters");
    
        Enumeration params = httpRequest.getParameterNames();
        while(params.hasMoreElements()){
            String paramName = (String)params.nextElement();
            System.out.println(paramName + " = " + httpRequest.getParameter(paramName));
        }
    
        System.out.println("\n\n Row data");
        System.out.println(extractPostRequestBody(httpRequest));
    }
    
    static String extractPostRequestBody(HttpServletRequest request) {
        if ("POST".equalsIgnoreCase(request.getMethod())) {
            Scanner s = null;
            try {
                s = new Scanner(request.getInputStream(), "UTF-8").useDelimiter("\\A");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return s.hasNext() ? s.next() : "";
        }
        return "";
    }
    

    How to read a file from jar in Java?

    A JAR is basically a ZIP file so treat it as such. Below contains an example on how to extract one file from a WAR file (also treat it as a ZIP file) and outputs the string contents. For binary you'll need to modify the extraction process, but there are plenty of examples out there for that.

    public static void main(String args[]) {
        String relativeFilePath = "style/someCSSFile.css";
        String zipFilePath = "/someDirectory/someWarFile.war";
        String contents = readZipFile(zipFilePath,relativeFilePath);
        System.out.println(contents);
    }
    
    public static String readZipFile(String zipFilePath, String relativeFilePath) {
        try {
            ZipFile zipFile = new ZipFile(zipFilePath);
            Enumeration<? extends ZipEntry> e = zipFile.entries();
    
            while (e.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) e.nextElement();
                // if the entry is not directory and matches relative file then extract it
                if (!entry.isDirectory() && entry.getName().equals(relativeFilePath)) {
                    BufferedInputStream bis = new BufferedInputStream(
                            zipFile.getInputStream(entry));
                    // Read the file
                        // With Apache Commons I/O
                     String fileContentsStr = IOUtils.toString(bis, "UTF-8");
    
                        // With Guava
                    //String fileContentsStr = new String(ByteStreams.toByteArray(bis),Charsets.UTF_8);
                    // close the input stream.
                    bis.close();
                    return fileContentsStr;
                } else {
                    continue;
                }
            }
        } catch (IOException e) {
            logger.error("IOError :" + e);
            e.printStackTrace();
        }
        return null;
    }
    

    In this example I'm using Apache Commons I/O and if you are using Maven here is the dependency:

    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.4</version>
    </dependency>
    

    What is the purpose of a plus symbol before a variable?

    The + operator returns the numeric representation of the object. So in your particular case, it would appear to be predicating the if on whether or not d is a non-zero number.

    Reference here. And, as pointed out in comments, here.

    Checking if a worksheet-based checkbox is checked

    It seems that in VBA macro code for an ActiveX checkbox control you use

    If (ActiveSheet.OLEObjects("CheckBox1").Object.Value = True)

    and for a Form checkbox control you use

    If (ActiveSheet.Shapes("CheckBox1").OLEFormat.Object.Value = 1)

    What does 'index 0 is out of bounds for axis 0 with size 0' mean?

    Essentially it means you don't have the index you are trying to reference. For example:

    df = pd.DataFrame()
    df['this']=np.nan
    df['my']=np.nan
    df['data']=np.nan
    df['data'][0]=5 #I haven't yet assigned how long df[data] should be!
    print(df)
    

    will give me the error you are referring to, because I haven't told Pandas how long my dataframe is. Whereas if I do the exact same code but I DO assign an index length, I don't get an error:

    df = pd.DataFrame(index=[0,1,2,3,4])
    df['this']=np.nan
    df['is']=np.nan
    df['my']=np.nan
    df['data']=np.nan
    df['data'][0]=5 #since I've properly labelled my index, I don't run into this problem!
    print(df)
    

    Hope that answers your question!

    How to strip all non-alphabetic characters from string in SQL Server?

    This solution, inspired by Mr. Allen's solution, requires a Numbers table of integers (which you should have on hand if you want to do serious query operations with good performance). It does not require a CTE. You can change the NOT IN (...) expression to exclude specific characters, or change it to an IN (...) OR LIKE expression to retain only certain characters.

    SELECT (
        SELECT  SUBSTRING([YourString], N, 1)
        FROM    dbo.Numbers
        WHERE   N > 0 AND N <= CONVERT(INT, LEN([YourString]))
            AND SUBSTRING([YourString], N, 1) NOT IN ('(',')',',','.')
        FOR XML PATH('')
    ) AS [YourStringTransformed]
    FROM ...
    

    Visual Studio breakpoints not being hit

    If none of the above work, double-check your code. Sometimes the reason why the breakpoint appears to not be hitting is due to the block of code containing the breakpoint is not being executed for sometimes inadvertant reasons.

    For example, forgetting the "Handles Me.Load" has gotten me a few times when copying and pasting code:

        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
        --this block of code will not execute
        End Sub 
    

    vs

        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        --this block executes
        End Sub
    

    AngularJS 1.2 $injector:modulerr

    Its an injector error. You may have use lots of JavaScript files so the injector may be missing.

    Some are here:

    var app = angular.module('app', 
        ['ngSanitize', 'ui.router', 'pascalprecht.translate', 'ngResource', 
         'ngMaterial', 'angularMoment','md.data.table', 'angularFileUpload', 
         'ngMessages', 'ui.utils.masks', 'angular-sortable-view',          
         'mdPickers','ngDraggable','as.sortable', 'ngAnimate', 'ngTouch']
    );
    

    Please check the injector you need to insert in your app.js

    How to resize an image with OpenCV2.0 and Python2.6

    Here's a function to upscale or downscale an image by desired width or height while maintaining aspect ratio

    # Resizes a image and maintains aspect ratio
    def maintain_aspect_ratio_resize(image, width=None, height=None, inter=cv2.INTER_AREA):
        # Grab the image size and initialize dimensions
        dim = None
        (h, w) = image.shape[:2]
    
        # Return original image if no need to resize
        if width is None and height is None:
            return image
    
        # We are resizing height if width is none
        if width is None:
            # Calculate the ratio of the height and construct the dimensions
            r = height / float(h)
            dim = (int(w * r), height)
        # We are resizing width if height is none
        else:
            # Calculate the ratio of the width and construct the dimensions
            r = width / float(w)
            dim = (width, int(h * r))
    
        # Return the resized image
        return cv2.resize(image, dim, interpolation=inter)
    

    Usage

    import cv2
    
    image = cv2.imread('1.png')
    cv2.imshow('width_100', maintain_aspect_ratio_resize(image, width=100))
    cv2.imshow('width_300', maintain_aspect_ratio_resize(image, width=300))
    cv2.waitKey()
    

    Using this example image

    enter image description here

    Simply downscale to width=100 (left) or upscale to width=300 (right)

    enter image description here enter image description here

    How do I select between the 1st day of the current month and current day in MySQL?

    select * from table
    where date between 
    (date_add (CURRENT_DATE, INTERVAL(1 - DAYOFMonth(CURRENT_DATE)) day)) and current_date;
    

    How do you add Boost libraries in CMakeLists.txt?

    Adapting @LainIwakura's answer for modern CMake syntax with imported targets, this would be:

    set(Boost_USE_STATIC_LIBS OFF) 
    set(Boost_USE_MULTITHREADED ON)  
    set(Boost_USE_STATIC_RUNTIME OFF) 
    find_package(Boost 1.45.0 COMPONENTS filesystem regex) 
    
    if(Boost_FOUND)
        add_executable(progname file1.cxx file2.cxx) 
        target_link_libraries(progname Boost::filesystem Boost::regex)
    endif()
    

    Note that it is not necessary anymore to specify the include directories manually, since it is already taken care of through the imported targets Boost::filesystem and Boost::regex.
    regex and filesystem can be replaced by any boost libraries you need.

    Get string after character

    This should work:

    your_str='GenFiltEff=7.092200e-01'
    echo $your_str | cut -d "=" -f2
    

    Importing class/java files in Eclipse

    First, you don't need the .class files if they are compiled from your .java classes.

    To import your files, you need to create an empty Java project. They you either import them one by one (New -> File -> Advanced -> Link file) or directly copy them into their corresponding folder/package and refresh the project.

    Generate war file from tomcat webapp folder

    You can create .war file back from your existing folder.

    Using this command

    cd /to/your/folder/location
    jar -cvf my_web_app.war *
    

    How do I initialize a dictionary of empty lists in Python?

    Use defaultdict instead:

    from collections import defaultdict
    data = defaultdict(list)
    data[1].append('hello')
    

    This way you don't have to initialize all the keys you want to use to lists beforehand.

    What is happening in your example is that you use one (mutable) list:

    alist = [1]
    data = dict.fromkeys(range(2), alist)
    alist.append(2)
    print data
    

    would output {0: [1, 2], 1: [1, 2]}.

    How to draw a standard normal distribution in R

    By the way, instead of generating the x and y coordinates yourself, you can also use the curve() function, which is intended to draw curves corresponding to a function (such as the density of a standard normal function).

    see

    help(curve)
    

    and its examples.

    And if you want to add som text to properly label the mean and standard deviations, you can use the text() function (see also plotmath, for annotations with mathematical symbols) .

    see

    help(text)
    help(plotmath)
    

    Can't start Tomcat as Windows Service

    On a 64-bit system you have to make sure that both the Tomcat application and the JDK are the same architecture: either both are x86 or x64.

    In case you want to change the Tomcat instance to x64 you might have to download the tomcat8.exe or tomcat9.exe and the tcnative-1.dll with the appropriate x64 versions. You can get those at http://svn.apache.org/viewvc/tomcat/.

    Alternatively you can point Tomcat to the x86 JDK by changing the Java Virtual Machine path in the Tomcat config.

    String to LocalDate

    You may have to go from DateTime to LocalDate.

    Using Joda Time:

    DateTimeFormatter FORMATTER = DateTimeFormat.forPattern("yyyy-MMM-dd");
    DateTime dateTime = FORMATTER.parseDateTime("2005-nov-12");
    LocalDate localDate = dateTime.toLocalDate();
    

    maxFileSize and acceptFileTypes in blueimp file upload plugin do not work. Why?

    open the file named "jquery.fileupload-ui.js", you will see the code like this:

     $.widget('blueimp.fileupload', $.blueimp.fileupload, {
    
        options: {
            // By default, files added to the widget are uploaded as soon
            // as the user clicks on the start buttons. To enable automatic
            // uploads, set the following option to true:
            acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
            autoUpload: false,
            // The ID of the upload template:
            uploadTemplateId: 'template-upload',
            // The ID of the download template:
            downloadTemplateId: 'template-download',
            ????
    

    just add one line code --- the new attribute "acceptFileTypes",like this:

     options: {
            // By default, files added to the widget are uploaded as soon
            // as the user clicks on the start buttons. To enable automatic
            // uploads, set the following option to true:
            **acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,**
            autoUpload: false,
            // The ID of the upload template:
            uploadTemplateId: 'template-upload',
            // The ID of the download template:
            downloadTemplateId: 'template-d
    

    now you'll see everything is allright!~ you just take the attribute with a wrong place.

    How exactly does <script defer="defer"> work?

    Should be also noted that there might be problems in IE<=9 when using script defer in certain situations. More on this: https://github.com/h5bp/lazyweb-requests/issues/42

    How to use JQuery with ReactJS

    Yes, we can use jQuery in ReactJs. Here I will tell how we can use it using npm.

    step 1: Go to your project folder where the package.json file is present via using terminal using cd command.

    step 2: Write the following command to install jquery using npm : npm install jquery --save

    step 3: Now, import $ from jquery into your jsx file where you need to use.

    Example:

    write the below in index.jsx

    import React from 'react';
    import ReactDOM from 'react-dom';
    import $ from 'jquery';
    
    
    //   react code here
    
    
    $("button").click(function(){
        $.get("demo_test.asp", function(data, status){
            alert("Data: " + data + "\nStatus: " + status);
        });
    });
    
    // react code here
    

    write the below in index.html

    <!DOCTYPE html>
    <html>
    <head>
        <script src="index.jsx"></script>
        <!-- other scripting files -->
    </head>
    <body>
        <!-- other useful tags -->
        <div id="div1">
            <h2>Let jQuery AJAX Change This Text</h2>
        </div>
        <button>Get External Content</button>
    </body>
    </html>
    

    End-line characters from lines read from text file, using Python

    You may also consider using line.rstrip() to remove the whitespaces at the end of your line.

    Checking Value of Radio Button Group via JavaScript?

    Without loop:

    document.getElementsByName('gender').reduce(function(value, checkable) {
        if(checkable.checked == true) 
            value = checkable.value; 
        return value;
    }, '');
    

    reduce is just a function that will feed sequentially array elements to second argument of callback, and previously returned function to value, while for the first run, it will use value of second argument.

    The only minus of this approach is that reduce will traverse every element returned by getElementsByName even after it have found selected radio button.

    Load Image from javascript

    You can try this:

    <img id="id1" src="url/to/file.png" onload="showImage()">
    
    function showImage() {
     $('#id1').attr('src', 'new/file/link.png');
    }
    

    Also, try to remove the ~, that is just the operator, that is needed for Server-Side (for example ASP.NET) you don't need it in JS.

    This way, you can change the attribute for the image.

    Here is the fiddle: http://jsfiddle.net/afzaal_ahmad_zeeshan/8H4MC/

    Rendering HTML in a WebView with custom CSS

    Is it possible to have all the content rendered in-page, in a given div? You could then reset the css based on the id, and work on from there.

    Say you give your div id="ocon"

    In your css, have a definition like:

    #ocon *{background:none;padding:0;etc,etc,}
    

    and you can set values to clear all css from applying to the content. After that, you can just use

    #ocon ul{}
    

    or whatever, further down the stylesheet, to apply new styles to the content.

    Which HTTP methods match up to which CRUD methods?

    It depends on the concrete situation.. but in general:

    PUT = update or change a concrete resource with a concrete URI of the resource.

    POST = create a new resource under the source of the given URI.

    I.e.

    Edit a blog post:

    PUT: /blog/entry/1

    Create a new one:

    POST: /blog/entry

    PUT may create a new resource in some circumstances where the URI of the new ressource is clear before the request. POST can be used to implement several other use cases, too, which are not covered by the others (GET, PUT, DELETE, HEAD, OPTIONS)

    The general understanding for CRUD systems is GET = request, POST = create, Put = update, DELETE = delete

    Does the Java &= operator apply & or &&?

    It's the last one:

    a = a & b;
    

    Sort JavaScript object by key

    Using lodash this will work:

    some_map = { 'b' : 'asdsad', 'c' : 'masdas', 'a' : 'dsfdsfsdf' }
    
    // perform a function in order of ascending key
    _(some_map).keys().sort().each(function (key) {
      var value = some_map[key];
      // do something
    });
    
    // or alternatively to build a sorted list
    sorted_list = _(some_map).keys().sort().map(function (key) {
      var value = some_map[key];
      // return something that shall become an item in the sorted list
    }).value();
    

    Just food for thought.

    How to join two JavaScript Objects, without using JQUERY

    I've used this function to merge objects in the past, I use it to add or update existing properties on obj1 with values from obj2:

    var _mergeRecursive = function(obj1, obj2) {
    
          //iterate over all the properties in the object which is being consumed
          for (var p in obj2) {
              // Property in destination object set; update its value.
              if ( obj2.hasOwnProperty(p) && typeof obj1[p] !== "undefined" ) {
                _mergeRecursive(obj1[p], obj2[p]);
    
              } else {
                //We don't have that level in the heirarchy so add it
                obj1[p] = obj2[p];
    
              }
         }
    }
    

    It will handle multiple levels of hierarchy as well as single level objects. I used it as part of a utility library for manipulating JSON objects. You can find it here.

    Where is the Docker daemon log?

    It depends on your OS. Here are the few locations, with commands for few Operating Systems:

    • Ubuntu (old using upstart ) - /var/log/upstart/docker.log
    • Ubuntu (new using systemd ) - sudo journalctl -fu docker.service
    • Amazon Linux AMI - /var/log/docker
    • Boot2Docker - /var/log/docker.log
    • Debian GNU/Linux - /var/log/daemon.log
    • CentOS - /var/log/message | grep docker
    • CoreOS - journalctl -u docker.service
    • Fedora - journalctl -u docker.service
    • Red Hat Enterprise Linux Server - /var/log/messages | grep docker
    • OpenSuSE - journalctl -u docker.service
    • OSX - ~/Library/Containers/com.docker.docker/Data/com.docker.driver.amd64-linux/log/d??ocker.log
    • Windows - Get-EventLog -LogName Application -Source Docker -After (Get-Date).AddMinutes(-5) | Sort-Object Time, as mentioned here.

    Checking if sys.argv[x] is defined

    It's an ordinary Python list. The exception that you would catch for this is IndexError, but you're better off just checking the length instead.

    if len(sys.argv) >= 2:
      startingpoint = sys.argv[1]
    else:
      startingpoint = 'blah'
    

    MySQL Orderby a number, Nulls last

    NULL LAST

    SELECT * FROM table_name ORDER BY id IS NULL, id ASC
    

    Can the Twitter Bootstrap Carousel plugin fade in and out on slide transition

    Note: If you are using Bootstrap + AngularJS + UI Bootstrap, .left .right and .next classes are never added. Using the example at the following link and the CSS from Robert McKee answer works. I wanted to comment because it took 3 days to find a full solution. Hope this helps others!

    https://angular-ui.github.io/bootstrap/#/carousel

    Code snip from UI Bootstrap Demo at the above link.

    angular.module('ui.bootstrap.demo').controller('CarouselDemoCtrl', function ($scope) {
      $scope.myInterval = 5000;
      var slides = $scope.slides = [];
      $scope.addSlide = function() {
        var newWidth = 600 + slides.length + 1;
        slides.push({
          image: 'http://placekitten.com/' + newWidth + '/300',
          text: ['More','Extra','Lots of','Surplus'][slides.length % 4] + ' ' +
            ['Cats', 'Kittys', 'Felines', 'Cutes'][slides.length % 4]
        });
      };
      for (var i=0; i<4; i++) {
        $scope.addSlide();
      }
    });
    

    Html From UI Bootstrap, Notice I added the .fade class to the example.

    <div ng-controller="CarouselDemoCtrl">
        <div style="height: 305px">
            <carousel class="fade" interval="myInterval">
              <slide ng-repeat="slide in slides" active="slide.active">
                <img ng-src="{{slide.image}}" style="margin:auto;">
                <div class="carousel-caption">
                  <h4>Slide {{$index}}</h4>
                  <p>{{slide.text}}</p>
                </div>
              </slide>
            </carousel>
        </div>
    </div>
    

    CSS from Robert McKee's answer above

    .carousel.fade {
    opacity: 1;
    }
    .carousel.fade .item {
    -moz-transition: opacity ease-in-out .7s;
    -o-transition: opacity ease-in-out .7s;
    -webkit-transition: opacity ease-in-out .7s;
    transition: opacity ease-in-out .7s;
    left: 0 !important;
    opacity: 0;
    top:0;
    position:absolute;
    width: 100%;
    display:block !important;
    z-index:1;
    }
    .carousel.fade .item:first-child {
    top:auto;
    position:relative;
    }
    .carousel.fade .item.active {
    opacity: 1;
    -moz-transition: opacity ease-in-out .7s;
    -o-transition: opacity ease-in-out .7s;
    -webkit-transition: opacity ease-in-out .7s;
    transition: opacity ease-in-out .7s;
    z-index:2;
    }
    /*
    Added z-index to raise the left right controls to the top
    */
    .carousel-control {
    z-index:3;
    }
    

    How do I convert a String object into a Hash object?

    I had the same problem. I was storing a hash in Redis. When retrieving that hash, it was a string. I didn't want to call eval(str) because of security concerns. My solution was to save the hash as a json string instead of a ruby hash string. If you have the option, using json is easier.

      redis.set(key, ruby_hash.to_json)
      JSON.parse(redis.get(key))
    

    TL;DR: use to_json and JSON.parse

    How to properly import a selfsigned certificate into Java keystore that is available to all Java applications by default?

    Might want to try

    keytool -import -trustcacerts -noprompt -keystore <full path to cacerts> -storepass changeit -alias $REMHOST -file $REMHOST.pem
    

    i honestly have no idea where it puts your certificate if you just write cacerts just give it a full path

    How to set an environment variable from a Gradle build?

    In my project I have Gradle task for integration test in sub-module:

    task intTest(type: Test) {
    ...
    system.properties System.properties 
    ...
    

    this is the main point to inject all your system params into test environment. So, now you can run gradle like this to pass param with ABC value and use its value by ${param} in your code

    gradle :some-service:intTest -Dparam=ABC
    

    Using two CSS classes on one element

    If you want two classes on one element, do it this way:

    <div class="social first"></div>
    

    Reference it in css like so:

    .social.first {}
    

    Example:

    https://jsfiddle.net/tybro0103/covbtpaq/

    Python regex to match dates

    As the question title asks for a regex that finds many dates, I would like to propose a new solution, although there are many solutions already.

    In order to find all dates of a string that are in this millennium (2000 - 2999), for me it worked the following:

    dates = re.findall('([1-9]|1[0-9]|2[0-9]|3[0-1]|0[0-9])(.|-|\/)([1-9]|1[0-2]|0[0-9])(.|-|\/)(20[0-9][0-9])',dates_ele)
    
    dates = [''.join(dates[i]) for i in range(len(dates))]
    

    This regex is able to find multiple dates in the same string, like bla Bla 8.05/2020 \n BLAH bla15/05-2020 blaa. As one could observe, instead of / the date can have . or -, not necessary at the same time.

    Some explaining

    More specifically it can find dates of format day , moth year. Day is an one digit integer or a zero followed by one digit integer or 1 or 2 followed by an one digit integer or a 3 followed by 0 or 1. Month is an one digit integer or a zero followed by one digit integer or 1 followed by 0, 1, or 2. Year is the number 20 followed by any number between 00 and 99.

    Useful notes

    One can add more date splitting symbols by adding | symbol at the end of both (.|-|\/). For example for adding -- one would do (.|-|\/|--)

    To have years outside of this millennium one has to modify (20[0-9][0-9]) to ([0-9][0-9][0-9][0-9])

    Change the Theme in Jupyter Notebook?

    For Dark Mode Only: -

    I have used Raleway Font for styling

    To C:\User\UserName\.jupyter\custom\custom.css file

    append the given styles, this is specifically for Dark Mode for jupyter notebook...

    This should be your current custom.css file: -

    /* This file contains any manual css for this page that needs to override the global styles.
        This is only required when different pages style the same element differently. This is just
        a hack to deal with our current css styles and no new styling should be added in this file.*/
    
    #ipython-main-app {
        position: relative;
    }
    
    #jupyter-main-app {
        position: relative;
    }
    

    Content to be append starts now

    .header-bar {
        display: none;
    }
    
    #header-container img {
        display: none;
    }
    
    #notebook_name {
        margin-left: 0px !important;
    }
    
    #header-container {
        padding-left: 0px !important
    }
    
    html,
    body {
        overflow: hidden;
        font-family: OpenSans;
    }
    
    #header {
        background-color: #212121 !important;
        color: #fff;
        padding-top: 20px;
        padding-bottom: 50px;
    }
    
    .navbar-collapse {
        background-color: #212121 !important;
        color: #fff;
        border: none !important
    }
    
    #menus {
        border: none !important;
        color: white !important;
    }
    
    #menus .dropdown-toggle {
        color: white !important;
    }
    
    #filelink {
        color: white !important;
        text-align: centerimportant;
        padding-left: 7px;
        text-decoration: none !important;
    }
    
    .navbar-default .navbar-nav>.open>a,
    .navbar-default .navbar-nav>.open>a:hover,
    .navbar-default .navbar-nav>.open>a:focus {
        background-color: #191919 !important;
        color: #eee !important;
        text-align: left !important;
    }
    
    .dropdown-menu,
    .dropdown-menu a,
    .dropdown-submenu a {
        background-color: #191919;
        color: #fff !important;
    }
    
    .dropdown-menu>li>a:hover,
    .dropdown-menu>li>a:focus,
    .dropdown-submenu>a:after {
        background-color: #212121;
        color: #fff !important;
    }
    
    .btn-default {
        color: #fff !important;
        background-color: #212121 !important;
        border: none !important;
    }
    
    .dropdown {
        text-align: left !important;
    }
    
    .form-control.select-xs {
        background-color: #191919 !important;
        color: #eee !important;
        border: none;
        outline: none;
    }
    
    #modal_indicator {
        display: none;
    }
    
    #kernel_indicator {
        color: #fff;
    }
    
    #notification_trusted,
    #notification_notebook {
        background-color: #212121;
        color: #eee !important;
        border: none;
        border-bottom: 1px solid #eee;
    }
    
    #logout {
        background-color: #191919;
        color: #eee;
    }
    
    #maintoolbar-container {
        padding-top: 0px !important;
    }
    
    .notebook_app {
        background-color: #222222;
    }
    
    ::-webkit-scrollbar {
        display: none;
    }
    
    #notebook-container {
        background-color: #212121;
    }
    
    div.cell.selected,
    div.cell.selected.jupyter-soft-selected {
        border: none !important;
    }
    
    .cm-keyword {
        color: orange !important;
    }
    
    .input_area {
        background-color: #212121 !important;
        color: white !important;
        border: 1px solid rgba(255, 255, 255, 0.1) !important;
    }
    
    .cm-def {
        color: #5bc0de !important;
    }
    
    .cm-variable {
        color: yellow !important;
    }
    
    .output_subarea.output_text.output_result pre,
    .output_subarea.output_text.output_stream.output_stdout pre {
        color: white !important;
    }
    
    .CodeMirror-line {
        color: white !important;
    }
    
    .cm-operator {
        color: white !important;
    }
    
    .cm-number {
        color: lightblue !important;
    }
    
    .inner_cell {
        border: 1px thin #eee;
        border-radius: 50px !important;
    }
    
    .CodeMirror-lines {
        border-radius: 20px;
    }
    
    .prompt.input_prompt {
        color: #5cb85c !important;
    }
    
    .prompt.output_prompt {
        color: lightblue;
    }
    
    .cm-string {
        color: #6872ac !important;
    }
    
    .cm-builtin {
        color: #f0ad4e !important;
    }
    
    .run_this_cell {
        color: lightblue !important;
    }
    
    .input_area {
        border-radius: 20px;
    }
    
    .output_png {
        background-color: white;
    }
    
    .CodeMirror-cursor {
        border-left: 1.4px solid white;
    }
    
    .box-flex1.output_subarea.raw_input_container {
        color: white;
    }
    
    input.raw_input {
        color: black !important;
    }
    
    div.output_area pre {
        color: white
    }
    
    h1,
    h2,
    h3,
    h4,
    h5,
    h6 {
        color: white !important;
        font-weight: bolder !important;
    }
    
    .CodeMirror-gutter.CodeMirror-linenumber,
    .CodeMirror-gutters {
        background-color: #212121 !important;
    }
    
    
    span.filename:hover {
        color: #191919 !important;
        height: auto !important;
    }
    
    #site {
        background-color: #191919 !important;
        color: white !important;
    }
    
    #tabs li.active a {
        background-color: #212121 !important;
        color: white !important;
    }
    
    #tabs li {
        background-color: #191919 !important;
        color: white !important;
        border-top: 1px thin #eee;
    }
    
    #notebook_list_header {
        background-color: #212121 !important;
        color: white !important;
    }
    
    #running .panel-group .panel {
        background-color: #212121 !important;
        color: white !important;
    }
    
    #accordion.panel-heading {
        background-color: #212121 !important;
    }
    
    #running .panel-group .panel .panel-heading {
        background-color: #212121;
        color: white
    }
    
    .item_name {
        color: white !important;
        cursor: pointer !important;
    }
    
    .list_item:hover {
        background-color: #212121 !important;
    }
    
    .item_icon.icon-fixed-width {
        color: white !important;
    }
    
    #texteditor-backdrop {
        background-color: #191919 !important;
        border-top: 1px solid #eee;
    }
    
    .CodeMirror {
        background-color: #212121 !important;
    }
    
    #texteditor-backdrop #texteditor-container .CodeMirror-gutter,
    #texteditor-backdrop #texteditor-container .CodeMirror-gutters {
        background-color: #212121 !important;
    }
    
    .celltoolbar {
        background-color: #212121 !important;
        border: none !important;
    }
    

    Dark Mode for Jupyter Notebook

    Dark Mode for Jupyter Notebook

    Add new row to excel Table (VBA)

    I actually just found that if you want to add multiple rows below the selection in your table Selection.ListObject.ListRows.Add AlwaysInsert:=True works really well. I just duplicated the code five times to add five rows to my table

    What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?

    You can use function closures as data in larger expressions as well, as in this method of determining browser support for some of the html5 objects.

       navigator.html5={
         canvas: (function(){
          var dc= document.createElement('canvas');
          if(!dc.getContext) return 0;
          var c= dc.getContext('2d');
          return typeof c.fillText== 'function'? 2: 1;
         })(),
         localStorage: (function(){
          return !!window.localStorage;
         })(),
         webworkers: (function(){
          return !!window.Worker;
         })(),
         offline: (function(){
          return !!window.applicationCache;
         })()
        }
    

    How to center canvas in html5

    To center the canvas element horizontally, you must specify it as a block level and leave its left and right margin properties to the browser:

    canvas{
        margin-right: auto;
        margin-left: auto;
        display: block;
    }
    

    If you wanted to center it vertically, the canvas element needs to be absolutely positioned:

    canvas{
        position: absolute;
        top: 50%;
        transform: translate(0, -50%);              
    }
    

    If you wanted to center it horizontally and vertically, do:

    canvas{
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);               
    }
    

    For more info visit: https://www.w3.org/Style/Examples/007/center.en.html

    Add image in pdf using jspdf

    maybe a little bit late, but I come to this situation recently and found a simple solution, 2 functions are needed.

    1. load the image.

      function getImgFromUrl(logo_url, callback) {
          var img = new Image();
          img.src = logo_url;
          img.onload = function () {
              callback(img);
          };
      } 
      
    2. in onload event on first step, make a callback to use the jspdf doc.

      function generatePDF(img){
          var options = {orientation: 'p', unit: 'mm', format: custom};
          var doc = new jsPDF(options);
          doc.addImage(img, 'JPEG', 0, 0, 100, 50);}
      
    3. use the above functions.

      var logo_url = "/images/logo.jpg";
      getImgFromUrl(logo_url, function (img) {
          generatePDF(img);
      });
      

    Google Chrome Printing Page Breaks

    I faced this issue on chrome before and the cause for it is that there was a div has min-height set to a value. The solution was to reset min-height while printing as follows:

    @media print {
        .wizard-content{
            min-height: 0;
        }
    }
    

    How to dynamically add a style for text-align using jQuery

     $(this).css({'text-align':'center'}); 
    

    You can use class name and id in place of this

    $('.classname').css({'text-align':'center'});
    

    or

    $('#id').css({'text-align':'center'});
    

    Postgres: SQL to list table foreign keys

    Use the name of the Primary Key to which the Keys are referencing and query the information_schema:

    select table_name, column_name
    from information_schema.key_column_usage
    where constraint_name IN (select constraint_name
      from information_schema.referential_constraints 
      where unique_constraint_name = 'TABLE_NAME_pkey')
    

    Here 'TABLE_NAME_pkey' is the name of the Primary Key referenced by the Foreign Keys.

    Single statement across multiple lines in VB.NET without the underscore character

    You can use XML literals to sort of do this:

    Dim s = <sql>
      Create table article
      (articleID int  -- sql comment
      ,articleName varchar(50)  <comment text="here's an xml comment" />
      )
    </sql>.Value
    

    warning: XML text rules apply, like &amp; for ampersand, &lt; for <, etc.

    Dim alertText = "Hello World"
    Dim js = <script>
              $(document).ready(function() {
               alert('<%= alertText %>');
              });
             </script>.ToString  'instead of .Value includes <script> tag
    

    note: the above is problematic when it includes characters that need to be escaped. Better to use "<script>"+js.Value+"</script>"

    How to maximize a plt.show() window using Python

    With Qt backend (FigureManagerQT) proper command is:

    figManager = plt.get_current_fig_manager()
    figManager.window.showMaximized()
    

    Firebug like plugin for Safari browser

    I work a lot with CSS panel and it's too slow in Safari Web Inspector. Apple knows about this problem and promise to fix this bug with freezes, except this thing web tools is much more powerful and convenient than firebug in mozilla, so waiting for fix.

    I'm getting Key error in python

    For dict, just use

    if key in dict

    and don't use searching in key list

    if key in dict.keys()

    The latter will be more time-consuming.

    get UTC time in PHP

    Other than calling gmdate you can also put this code before your rest of the code:

    <?php
    date_default_timezone_set("UTC");
    ?>
    

    That will make rest of your date/time related calls to use GMT/UTC timezone.

    WampServer: php-win.exe The program can't start because MSVCR110.dll is missing

    As far as I am aware, the MSVCRxxx.dlls are in %SystemRoot%\System32 (usually C:\Windows\System32).

    The xxx refers to the version of the MS Visual C Runtime (hence MSVCR...)

    However, the complication seems to be that the xxx version is not the same as the two digits of the year "version".

    For example, Visual C Runtime 2013 yields MSVCR120.dll and "...Runtime 2012" yields MSVCR110.dll. And then Microsoft packages these as vcredist_x86.exe or vcredist_x64.exe, seemingly irrespective of the xxx version or the Visual Studio version number (2012, 2013 etc) - confused? You have every right to be!

    So, firstly, you need to determine whether you need 32 bit, 64 bit or even both (some PHP distributions apparently do need both), then download the relevant vcredist... for the bits AND for the Visual Studio version. As far as I can tell, the only way to tell which vcredist... you have is to start to install it. Recent versions give an intro screen that quotes the Visual Studio version and the xxx version. I have renamed by vcredists to something like vcredist_x64_2012_V11.exe.

    [EDIT] Forgot to add earlier that if you are simply looking to "install" the missing DLL (as opposed to resolve some bigger set of issues), then you probably won't do any harm by simply installing the relevant vcredist for your architecture (32 bit, 64 bit) and "missing" version.

    Which Radio button in the group is checked?

    In addition to the CheckedChangedEvent wiring one could use the Controls "Tag" property to distinguish between the radio buttons... an (spaghetti code) alternative would be the "TabIndex" property ;P

    What should I use to open a url instead of urlopen in urllib3

    The new urllib3 library has a nice documentation here
    In order to get your desired result you shuld follow that:

    Import urllib3
    from bs4 import BeautifulSoup
    
    url = 'http://www.thefamouspeople.com/singers.php'
    
    http = urllib3.PoolManager()
    response = http.request('GET', url)
    soup = BeautifulSoup(response.data.decode('utf-8'))
    

    The "decode utf-8" part is optional. It worked without it when i tried, but i posted the option anyway.
    Source: User Guide

    Storing C++ template function definitions in a .CPP file

    There is, in the latest standard, a keyword (export) that would help alleviate this issue, but it isn't implemented in any compiler that I'm aware of, other than Comeau.

    See the FAQ-lite about this.

    CSS "and" and "or"

    I guess you hate to write more selectors and divide them by a comma?

    .registration_form_right input:not([type="radio"]),  
    .registration_form_right input:not([type="checkbox"])  
    {  
    }
    

    and BTW this

    not([type="radio" && type="checkbox"])  
    

    looks to me more like "input which does not have both these types" :)

    Angular - Use pipes in services and components

    This answer is now outdated

    recommend using DI approach from other answers instead of this approach

    Original answer:

    You should be able to use the class directly

    new DatePipe().transform(myDate, 'yyyy-MM-dd');
    

    For instance

    var raw = new Date(2015, 1, 12);
    var formatted = new DatePipe().transform(raw, 'yyyy-MM-dd');
    expect(formatted).toEqual('2015-02-12');
    

    Get UTC time in seconds

    You say you're using:

    time.asctime(time.localtime(date_in_seconds_from_bash))
    

    where date_in_seconds_from_bash is presumably the output of date +%s.

    The time.localtime function, as the name implies, gives you local time.

    If you want UTC, use time.gmtime() rather than time.localtime().

    As JamesNoonan33's answer says, the output of date +%s is timezone invariant, so date +%s is exactly equivalent to date -u %s. It prints the number of seconds since the "epoch", which is 1970-01-01 00:00:00 UTC. The output you show in your question is entirely consistent with that:

    date -u
    Thu Jul 3 07:28:20 UTC 2014
    
    date +%s
    1404372514   # 14 seconds after "date -u" command
    
    date -u +%s
    1404372515   # 15 seconds after "date -u" command
    

    Powershell: convert string to number

    Simply casting the string as an int won't work reliably. You need to convert it to an int32. For this you can use the .NET convert class and its ToInt32 method. The method requires a string ($strNum) as the main input, and the base number (10) for the number system to convert to. This is because you can not only convert to the decimal system (the 10 base number), but also to, for example, the binary system (base 2).

    Give this method a try:

    [string]$strNum = "1.500"
    [int]$intNum = [convert]::ToInt32($strNum, 10)
    
    $intNum
    

    How To change the column order of An Existing Table in SQL Server 2008

    If your table doesn't have any records you can just drop then create your table.

    If it has records you can do it using your SQL Server Management Studio.

    Just click your table > right click > click Design then you can now arrange the order of the columns by dragging the fields on the order that you want then click save.

    Best Regards

    Eclipse: Enable autocomplete / content assist

    If you would like to use autocomplete all the time without having to worry about hitting Ctrl + Spacebar or your own keyboard shortcut, you can make the following adjustment in the Eclipse preferences to trigger autocomplete simply by typing several different characters:

    1. Eclipse > Preferences > Java > Editor > Content Assist
    2. Auto Activation > Auto activation triggers for Java
    3. Enter all the characters you want to trigger autocomplete, such as the following:

    abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ._

    Now any time that you type any of these characters, Eclipse will trigger autocomplete suggestions based on the context.

    assign headers based on existing row in dataframe in R

    Try this:

    colnames(DF) = DF[1, ] # the first row will be the header
    DF = DF[-1, ]          # removing the first row.
    

    However, get a look if the data has been properly read. If you data.frame has numeric variables but the first row were characters, all the data has been read as character. To avoid this problem, it's better to save the data and read again with header=TRUE as you suggest. You can also get a look to this question: Reading a CSV file organized horizontally.

    How to use ArrayList.addAll()?

    Assuming you have an ArrayList that contains characters, you could do this:

    List<Character> list = new ArrayList<Character>();
    list.addAll(Arrays.asList('+', '-', '*', '^'));
    

    The maximum message size quota for incoming messages (65536) has been exceeded

    You also need to increase maxBufferSize. Also note that you might need to increase the readerQuotas.

    Restricting JTextField input to Integers

    I used to use the Key Listener for this but I failed big time with that approach. Best approach as recommended already is to use a DocumentFilter. Below is a utility method I created for building textfields with only number input. Just beware that it'll also take single '.' character as well since it's usable for decimal input.

    public static void installNumberCharacters(AbstractDocument document) {
            document.setDocumentFilter(new DocumentFilter() {
                @Override
                public void insertString(FilterBypass fb, int offset,
                        String string, AttributeSet attr)
                        throws BadLocationException {
                    try {
                        if (string.equals(".")
                                && !fb.getDocument()
                                        .getText(0, fb.getDocument().getLength())
                                        .contains(".")) {
                            super.insertString(fb, offset, string, attr);
                            return;
                        }
                        Double.parseDouble(string);
                        super.insertString(fb, offset, string, attr);
                    } catch (Exception e) {
                        Toolkit.getDefaultToolkit().beep();
                    }
    
                }
    
                @Override
                public void replace(FilterBypass fb, int offset, int length,
                        String text, AttributeSet attrs)
                        throws BadLocationException {
                    try {
                        if (text.equals(".")
                                && !fb.getDocument()
                                        .getText(0, fb.getDocument().getLength())
                                        .contains(".")) {
                            super.insertString(fb, offset, text, attrs);
                            return;
                        }
                        Double.parseDouble(text);
                        super.replace(fb, offset, length, text, attrs);
                    } catch (Exception e) {
                        Toolkit.getDefaultToolkit().beep();
                    }
                }
            });
        }
    

    How to set up file permissions for Laravel?

    This worked for me:

    cd [..LARAVEL PROJECT ROOT]
    sudo find . -type f -exec chmod 644 {} \;
    sudo find . -type d -exec chmod 755 {} \;
    sudo chmod -R 777 ./storage
    sudo chmod -R 777 ./bootstrap/cache/
    

    Only if you use npm (VUE, compiling SASS, etc..) add this:

    sudo chmod -R 777 ./node_modules/
    

    What it does:

    • Change all file permissions to 644
    • Change all folder permissions to 755
    • For storage and bootstrap cache (special folders used by laravel for creating and executing files, not available from outside) set permission to 777, for anything inside
    • For nodeJS executable, same as above

    Note: Maybe you can not, or don't need, to do it with sudo prefix. it depends on your user's permissions, group, etc...

    Set time to 00:00:00

    Here are couple of utility functions I use to do just this.

    /**
     * sets all the time related fields to ZERO!
     *
     * @param date
     *
     * @return Date with hours, minutes, seconds and ms set to ZERO!
     */
    public static Date zeroTime( final Date date )
    {
        return DateTimeUtil.setTime( date, 0, 0, 0, 0 );
    }
    
    /**
     * Set the time of the given Date
     *
     * @param date
     * @param hourOfDay
     * @param minute
     * @param second
     * @param ms
     *
     * @return new instance of java.util.Date with the time set
     */
    public static Date setTime( final Date date, final int hourOfDay, final int minute, final int second, final int ms )
    {
        final GregorianCalendar gc = new GregorianCalendar();
        gc.setTime( date );
        gc.set( Calendar.HOUR_OF_DAY, hourOfDay );
        gc.set( Calendar.MINUTE, minute );
        gc.set( Calendar.SECOND, second );
        gc.set( Calendar.MILLISECOND, ms );
        return gc.getTime();
    }
    

    How to Display Multiple Google Maps per page with API V3

    I needed to load dynamic number of google maps, with dynamic locations. So I ended up with something like this. Hope it helps. I add LatLng as data-attribute on map div.

    So, just create divs with class "maps". Every map canvas can than have a various IDs and LatLng like this. Of course you can set up various data attributes for zoom and so...

    Maybe the code might be cleaner, but it works for me pretty well.

    <div id="map123" class="maps" data-gps="46.1461154,17.1580882"></div>
    <div id="map456" class="maps" data-gps="45.1461154,13.1080882"></div>
    
      <script>
          var map;
          function initialize() {
            // Get all map canvas with ".maps" and store them to a variable.
            var maps = document.getElementsByClassName("maps");
    
            var ids, gps, mapId = '';
    
            // Loop: Explore all elements with ".maps" and create a new Google Map object for them
            for(var i=0; i<maps.length; i++) {
    
              // Get ID of single div
              mapId = document.getElementById(maps[i].id);
    
              // Get LatLng stored in data attribute. 
              // !!! Make sure there is no space in data-attribute !!!
              // !!! and the values are separated with comma !!!
              gps = mapId.getAttribute('data-gps');
    
              // Convert LatLng to an array
              gps = gps.split(",");
    
              // Create new Google Map object for single canvas 
              map = new google.maps.Map(mapId, {
                zoom: 15,
                // Use our LatLng array bellow
                center: new google.maps.LatLng(parseFloat(gps[0]), parseFloat(gps[1])),
                mapTypeId: 'roadmap',
                mapTypeControl: true,
                zoomControlOptions: {
                    position: google.maps.ControlPosition.RIGHT_TOP
                }
              });
    
              // Create new Google Marker object for new map
              var marker = new google.maps.Marker({
                // Use our LatLng array bellow
                position: new google.maps.LatLng(parseFloat(gps[0]), parseFloat(gps[1])),
                map: map
              });
            }
          }
      </script>
    

    Can you use if/else conditions in CSS?

    I've devised the below demo using a mix of tricks which allows simulating if/else scenarios for some properties. Any property which is numerical in its essence is easy target for this method, but properties with text values are.

    This code has 3 if/else scenarios, for opacity, background color & width. All 3 are governed by two Boolean variables bool and its opposite notBool.

    Those two Booleans are the key to this method, and to achieve a Boolean out of a none-boolean dynamic value, requires some math which luckily CSS allows using min & max functions.

    Obviously those functions (min/max) are supported in recent browsers' versions which also supports CSS custom properties (variables).

    _x000D_
    _x000D_
    var elm = document.querySelector('div')
    
    setInterval(()=>{
      elm.style.setProperty('--width', Math.round(Math.random()*80 + 20))
    }, 1000)
    _x000D_
    :root{
       --color1: lightgreen;
       --color2: salmon;
       --width: 70;  /* starting value, randomly changed by javascript every 1 second */
    }
    
    div{
     --widthThreshold: 50;
     --is-width-above-limit: Min(1, Max(var(--width) - var(--widthThreshold), 0));
     --is-width-below-limit: calc(1 - var(--is-width-above-limit));
     
     --opacity-wide: .4;     /* if width is ABOVE 50 */
     --radius-narrow: 10px;  /* if width is BELOW 50 */
     --radius-wide: 60px;    /* if width is ABOVE 50 */
     --height-narrow: 80px;  /* if width is ABOVE 50 */
     --height-wide: 160px;   /* if width is ABOVE 50 */
     
     --radiusToggle: Max(var(--radius-narrow), var(--radius-wide) * var(--is-width-above-limit));
     --opacityToggle: calc(calc(1 + var(--opacity-wide)) - var(--is-width-above-limit));
     --colorsToggle: var(--color1) calc(100% * var(--is-width-above-limit)), 
                     var(--color2) calc(100% * var(--is-width-above-limit)), 
                     var(--color2) calc(100% * (1 - var(--is-width-above-limit)));
      
     --height: Max(var(--height-wide) * var(--is-width-above-limit), var(--height-narrow));
     
     height: var(--height);
     text-align: center;
     line-height: var(--height);
    
     width: calc(var(--width) * 1%);
     opacity: var(--opacityToggle);
     border-radius: var(--radiusToggle);
     background: linear-gradient(var(--colorsToggle));
    
     transition: .3s;
    }
    
    /* prints some variables */
    div::before{
      counter-reset: aa var(--width);
      content: counter(aa)"%";
    }
    
    div::after{
      counter-reset: bb var(--is-width-above-limit);
      content: " is over 50% ? "counter(bb);
    }
    _x000D_
    <div></div>
    _x000D_
    _x000D_
    _x000D_

    Another simply way using clamp:

    _x000D_
    _x000D_
    label{ --width: 150 }
    input:checked + div{ --width: 400 }
    
    div{
      --isWide: Clamp(0,   (var(--width) - 150) * 99999  , 1);
      width: calc(var(--width) * 1px);
      height: 150px;
      border-radius: calc(var(--isWide) * 20px); /* if wide - add radius */
      background: lightgreen;
    }
    _x000D_
    <label>
    <input type='checkbox' hidden> 
    <div>Click to toggle width</div>
    </label>
    _x000D_
    _x000D_
    _x000D_

    Best so far:

    I have come up with a totally unique method, which is even simpler!

    This method is so cool because it is so easy to implement and also to understand. it is based on animation step() function.

    Since bool can be easily calculated as either 0 or 1, this value can be used in the step! if only a single step is defined, then the if/else problem is solved.

    Using the keyword forwards persist the changes.

    _x000D_
    _x000D_
    var elm = document.querySelector('div')
    
    setInterval(()=>{
      elm.style.setProperty('--width', Math.round(Math.random()*80 + 20))
    }, 1000)
    _x000D_
    :root{
       --color1: salmon;
       --color2: lightgreen;
    }
    
    @keyframes if-over-threshold--container{
      to{ 
         --height: 160px;
         --radius: 30px;
         --color: var(--color2);
         opacity: .4; /* consider this as additional, never-before, style */
      }
    }
    
    @keyframes if-over-threshold--after{
      to{ 
        content: "true"; 
        color: green; 
      }
    }
    
    div{
     --width: 70;           /* must be unitless */
     --height: 80px;
     --radius: 10px;
     --color: var(--color1);
     --widthThreshold: 50;
     --is-width-over-threshold: Min(1, Max(var(--width) - var(--widthThreshold), 0));
    
     
     text-align: center;
     white-space: nowrap;
     transition: .3s;
     
     /* if element is narrower than --widthThreshold */
     width: calc(var(--width) * 1%);
     height: var(--height);
     line-height: var(--height);
     border-radius: var(--radius);
     background: var(--color);
    
     /* else */
     animation: if-over-threshold--container forwards steps(var(--is-width-over-threshold));
    }
    
    /* prints some variables */
    div::before{
      counter-reset: aa var(--width);
      content: counter(aa)"% is over 50% width ? ";
    }
    
    div::after{
      content: 'false'; 
      font-weight: bold; 
      color: darkred;
      
      /* if element is wider than --widthThreshold */
      animation: if-over-threshold--after forwards steps(var(--is-width-over-threshold)) ;
    }
    _x000D_
    <div></div>
    _x000D_
    _x000D_
    _x000D_


    I've found a Chrome bug which I have reported that can affect this method in some situations where specific type of calculations is necessary, but there's a way around it.

    https://bugs.chromium.org/p/chromium/issues/detail?id=1138497

    MySQL VARCHAR size?

    Actually, it will takes 101 bytes.

    MySQL Reference

    How to get current SIM card number in Android?

    You have everything right, but the problem is with getLine1Number() function.

    getLine1Number()- this method returns the phone number string for line 1, i.e the MSISDN for a GSM phone. Return null if it is unavailable.

    this method works only for few cell phone but not all phones.

    So, if you need to perform operations according to the sim(other than calling), then you should use getSimSerialNumber(). It is always unique, valid and it always exists.

    Install sbt on ubuntu

    The simplest way of installing SBT on ubuntu is the deb package provided by Typesafe.

    Run the following shell commands:

    1. wget http://apt.typesafe.com/repo-deb-build-0002.deb
    2. sudo dpkg -i repo-deb-build-0002.deb
    3. sudo apt-get update
    4. sudo apt-get install sbt

    And you're done !