Programs & Examples On #Transition

Using javascript or css to animate an element from one state to another.

Activity transition in Android

Yes. You can tell the OS what kind of transition you want to have for your activity.

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    getWindow().setWindowAnimations(ANIMATION);

    ...

}

Where ANIMATION is an integer referring to a built in animation in the OS.

CSS3 transition on click using pure CSS

You can use JavaScript to do this, with onClick method. This maybe helps CSS3 transition click event

Can I change the Android startActivity() transition animation?

Use overridePendingTransition

startActivity();
overridePendingTransition(R.anim.fadein, R.anim.fadeout);

fadein.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <alpha xmlns:android="http://schemas.android.com/apk/res/android"
        android:interpolator="@android:anim/accelerate_interpolator"
        android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="500" />
</set>

fadeout.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <alpha xmlns:android="http://schemas.android.com/apk/res/android"
        android:interpolator="@android:anim/anticipate_interpolator"
        android:fromAlpha="1.0" android:toAlpha="0.0" android:duration="500" />
</set>

CSS Auto hide elements after 5 seconds

YES!

But you can't do it in the way you may immediately think, because you cant animate or create a transition around the properties you'd otherwise rely on (e.g. display, or changing dimensions and setting to overflow:hidden) in order to correctly hide the element and prevent it from taking up visible space.

Therefore, create an animation for the elements in question, and simply toggle visibility:hidden; after 5 seconds, whilst also setting height and width to zero to prevent the element from still occupying space in the DOM flow.

FIDDLE

CSS

html, body {
    height:100%;
    width:100%;
    margin:0;
    padding:0;
}
#hideMe {
    -moz-animation: cssAnimation 0s ease-in 5s forwards;
    /* Firefox */
    -webkit-animation: cssAnimation 0s ease-in 5s forwards;
    /* Safari and Chrome */
    -o-animation: cssAnimation 0s ease-in 5s forwards;
    /* Opera */
    animation: cssAnimation 0s ease-in 5s forwards;
    -webkit-animation-fill-mode: forwards;
    animation-fill-mode: forwards;
}
@keyframes cssAnimation {
    to {
        width:0;
        height:0;
        overflow:hidden;
    }
}
@-webkit-keyframes cssAnimation {
    to {
        width:0;
        height:0;
        visibility:hidden;
    }
}

HTML

<div id='hideMe'>Wait for it...</div>

css transition opacity fade background

It's not fading to "black transparent" or "white transparent". It's just showing whatever color is "behind" the image, which is not the image's background color - that color is completely hidden by the image.

If you want to fade to black(ish), you'll need a black container around the image. Something like:

.ctr {
    margin: 0; 
    padding: 0;
    background-color: black;
    display: inline-block;
}

and

<div class="ctr"><img ... /></div>

Change value of input and submit form in JavaScript

document.getElementById("myform").submit();

This won't work as your form tag doesn't have an id.

Change it like this and it should work:

<form name="myform" id="myform" action="action.php">

How to use Bootstrap in an Angular project?

Procedure with Angular 6+ & Bootstrap 4+ :

  1. Open a shell on the folder of your project
  2. Install bootstrap with the command : npm install --save [email protected]
  3. Bootstrap need the dependency jquery, so if you don't have it, you can install it with the command : npm install --save jquery 1.9.1
  4. You may need to fix vulnerability with the command : npm audit fix
  5. In your main style.scss file, add the following line : @import "../node_modules/bootstrap/dist/css/bootstrap.min.css";

OR

Add this line to your main index.html file : <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

DataColumn Name from DataRow (not DataTable)

You can make it easier in your code (if you're doing this a lot anyway) by using an extension on the DataRow object, like:

static class Extensions
{
    public static string GetColumn(this DataRow Row, int Ordinal)
    {
        return Row.Table.Columns[Ordinal].ColumnName;
    }
}

Then call it using:

string MyColumnName = MyRow.GetColumn(5);

Git, How to reset origin/master to a commit?

origin/xxx branches are always pointer to a remote. You cannot check them out as they're not pointer to your local repository (you only checkout the commit. That's why you won't see the name written in the command line interface branch marker, only the commit hash).

What you need to do to update the remote is to force push your local changes to master:

git checkout master
git reset --hard e3f1e37
git push --force origin master
# Then to prove it (it won't print any diff)
git diff master..origin/master

How do I update the element at a certain position in an ArrayList?

arrayList.set(location,newValue); location= where u wnna insert, newValue= new element you are inserting.

notify is optional, depends on conditions.

Undefined reference to pthread_create in Linux

I believe the proper way of adding pthread in CMake is with the following

find_package (Threads REQUIRED)

target_link_libraries(helloworld
    ${CMAKE_THREAD_LIBS_INIT}
)

How to start color picker on Mac OS?

Take a look into NSColorWell class reference.

Reading all files in a directory, store them in objects, and send the object

I just wrote this and it looks more clean to me:

_x000D_
_x000D_
const fs = require('fs');
const util = require('util');

const readdir = util.promisify(fs.readdir);
const readFile = util.promisify(fs.readFile);

const readFiles = async dirname => {
    try {
        const filenames = await readdir(dirname);
        console.log({ filenames });
        const files_promise = filenames.map(filename => {
            return readFile(dirname + filename, 'utf-8');
        });
        const response = await Promise.all(files_promise);
        //console.log({ response })
        //return response
        return filenames.reduce((accumlater, filename, currentIndex) => {
            const content = response[currentIndex];
            accumlater[filename] = {
                content,
            };
            return accumlater;
        }, {});
    } catch (error) {
        console.error(error);
    }
};

const main = async () => {

    const response = await readFiles(
        './folder-name',
    );
    console.log({ response });
};
_x000D_
_x000D_
_x000D_

You can modify the response format according to your need. The response format from this code will look like:

{
   "filename-01":{
      "content":"This is the sample content of the file"
   },
   "filename-02":{
      "content":"This is the sample content of the file"
   }
}

C# Create New T()

Why hasn't anyone suggested Activator.CreateInstance ?

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

T obj = (T)Activator.CreateInstance(typeof(T));

How to create a new file in unix?

Try > workdirectory/filename.txt

This would:

  • truncate the file if it exists
  • create if it doesn't exist

You can consider it equivalent to:

rm -f workdirectory/filename.txt; touch workdirectory/filename.txt

Switch statement fall-through...should it be allowed?

I don't like my switch statements to fall through - it's far too error prone and hard to read. The only exception is when multiple case statements all do exactly the same thing.

If there is some common code that multiple branches of a switch statement want to use, I extract that into a separate common function that can be called in any branch.

How to describe table in SQL Server 2008?

You can use keyboard short-cut for Description/ detailed information of Table in SQL Server 2008.

Follow steps:

  1. Write Table Name,
  2. Select it, and press Alt + F1
  3. It will show detailed information/ description of mentioned table as,

    1) Table created date,
    2) Columns Description,
    3) Identity,
    4) Indexes,
    5) Constraints,
    6) References etc. As shown Below [example]:

Alt+F1 Demo

Inline SVG in CSS

I've forked a CodePen demo that had the same problem with embedding inline SVG into CSS. A solution that works with SCSS is to build a simple url-encoding function.

A string replacement function can be created from the built-in str-slice, str-index functions (see css-tricks, thanks to Hugo Giraudel).

Then, just replace %,<,>,",', with the %xxcodes:

@function svg-inline($string){
  $result: str-replace($string, "<svg", "<svg xmlns='http://www.w3.org/2000/svg'");
  $result: str-replace($result, '%', '%25');
  $result: str-replace($result, '"', '%22');
  $result: str-replace($result, "'", '%27');
  $result: str-replace($result, ' ', '%20');
  $result: str-replace($result, '<', '%3C');
  $result: str-replace($result, '>', '%3E');
  @return "data:image/svg+xml;utf8," + $result;
}

$mySVG: svg-inline("<svg>...</svg>");

html {
  height: 100vh;
  background: url($mySVG) 50% no-repeat;
}

There is also a image-inline helper function available in Compass, but since it is not supported in CodePen, this solution might probably be useful.

Demo on CodePen: http://codepen.io/terabaud/details/PZdaJo/

npm ERR! registry error parsing json - While trying to install Cordova for Ionic Framework in Windows 8

I had similar problem. I r?n npm cache clear, closed android SDK manager(which was open before) and re-ran npm install -g cordova and that was enough to solve the problem.

Django template how to look up a dictionary value with a variable

Fetch both the key and the value from the dictionary in the loop:

{% for key, value in mydict.items %}
    {{ value }}
{% endfor %}

I find this easier to read and it avoids the need for special coding. I usually need the key and the value inside the loop anyway.

jQuery hasClass() - check for more than one class

element.is('.class1, .class2')

works, but it's 35% slower than

element.hasClass('class1') || element.hasClass('class2')

enter image description here

If you doubt what i say, you can verify on jsperf.com.

Hope this help someone.

Print Combining Strings and Numbers

if you are using 3.6 try this

 k = 250
 print(f"User pressed the: {k}")

Output: User pressed the: 250

How to press back button in android programmatically?

Simply add finish(); in your first class' (login activity) onPause(); method. that's all

Get a list of all git commits, including the 'lost' ones

Like @Kieran 's Answer, but for the console: git log --oneline --all --graph --decorate $(git reflog | awk '{print $1}')

How to run python script with elevated privilege on windows

Here is a solution with an stdout redirection:

def elevate():
    import ctypes, win32com.shell.shell, win32event, win32process
    outpath = r'%s\%s.out' % (os.environ["TEMP"], os.path.basename(__file__))
    if ctypes.windll.shell32.IsUserAnAdmin():
        if os.path.isfile(outpath):
            sys.stderr = sys.stdout = open(outpath, 'w', 0)
        return
    with open(outpath, 'w+', 0) as outfile:
        hProc = win32com.shell.shell.ShellExecuteEx(lpFile=sys.executable, \
            lpVerb='runas', lpParameters=' '.join(sys.argv), fMask=64, nShow=0)['hProcess']
        while True:
            hr = win32event.WaitForSingleObject(hProc, 40)
            while True:
                line = outfile.readline()
                if not line: break
                sys.stdout.write(line)
            if hr != 0x102: break
    os.remove(outpath)
    sys.stderr = ''
    sys.exit(win32process.GetExitCodeProcess(hProc))

if __name__ == '__main__':
    elevate()
    main()

Getting PEAR to work on XAMPP (Apache/MySQL stack on Windows)

Another gotcha for this kind of problem: avoid running pear within a Unix shell (e.g., Git Bash or Cygwin) on a Windows machine. I had the same problem and the path fix suggested above didn't help. Switched over to a Windows shell, and the pear command works as expected.

Logarithmic returns in pandas dataframe

Log returns are simply the natural log of 1 plus the arithmetic return. So how about this?

df['pct_change'] = df.price.pct_change()
df['log_return'] = np.log(1 + df.pct_change)

Even more concise, utilizing Ximix's suggestion:

df['log_return'] = np.log1p(df.price.pct_change())

PDO with INSERT INTO through prepared statements

Please add try catch also in your code so that you can be sure that there in no exception.

try {
    $hostname = "servername";
    $dbname = "dbname";
    $username = "username";
    $pw = "password";
    $pdo = new PDO ("mssql:host=$hostname;dbname=$dbname","$username","$pw");
  } catch (PDOException $e) {
    echo "Failed to get DB handle: " . $e->getMessage() . "\n";
    exit;
  }

How to pass password automatically for rsync SSH command?

You should use a keyfile without passphrase for scripted ssh logins. This is obviously a security risk, take care that the keyfile itself is adequately secured.

Instructions for setting up passwordless ssh access

How do I wait until Task is finished in C#?

Your Print method likely needs to wait for the continuation to finish (ContinueWith returns a task which you can wait on). Otherwise the second ReadAsStringAsync finishes, the method returns (before result is assigned in the continuation). Same problem exists in your send method. Both need to wait on the continuation to consistently get the results you want. Similar to below

private static string Send(int id)
{
    Task<HttpResponseMessage> responseTask = client.GetAsync("aaaaa");
    string result = string.Empty;
    Task continuation = responseTask.ContinueWith(x => result = Print(x));
    continuation.Wait();
    return result;
}

private static string Print(Task<HttpResponseMessage> httpTask)
{
    Task<string> task = httpTask.Result.Content.ReadAsStringAsync();
    string result = string.Empty;
    Task continuation = task.ContinueWith(t =>
    {
        Console.WriteLine("Result: " + t.Result);
        result = t.Result;
    });
    continuation.Wait();  
    return result;
}

MVC3 EditorFor readOnly

i think this is simple than other by using [Editable(false)] attribute

for example:

 public class MyModel
    {
        [Editable(false)]
        public string userName { get; set; }
    }

how to check if string value is in the Enum list?

You can use the Enum.TryParse method:

Age age;
if (Enum.TryParse<Age>("New_Born", out age))
{
    // You now have the value in age 
}

Passing JavaScript array to PHP through jQuery $.ajax

Use the JQuery Serialize function

http://docs.jquery.com/Ajax/serialize

Serialize is typically used to prepare user input data to be posted to a server. The serialized data is in a standard format that is compatible with almost all server side programming languages and frameworks.

How do I calculate tables size in Oracle

First, gather optimiser stats on the table (if you haven't already):

begin
   dbms_stats.gather_table_stats('MYSCHEMA','MYTABLE');
end;
/

WARNING: As Justin says in his answer, gathering optimiser stats affects query optimisation and should not be done without due care and consideration!

Then find the number of blocks occupied by the table from the generated stats:

select blocks, empty_blocks, num_freelist_blocks
from   all_tables
where  owner = 'MYSCHEMA'
and    table_name = 'MYTABLE';
  • The total number of blocks allocated to the table is blocks + empty_blocks + num_freelist_blocks.

  • blocks is the number of blocks that actually contain data.

Multiply the number of blocks by the block size in use (usually 8KB) to get the space consumed - e.g. 17 blocks x 8KB = 136KB.

To do this for all tables in a schema at once:

begin
    dbms_stats.gather_schema_stats ('MYSCHEMA');
end;
/

select table_name, blocks, empty_blocks, num_freelist_blocks
from   user_tables;

Note: Changes made to the above after reading this AskTom thread

Writing a Python list of lists to a csv file

If you don't want to import csv module for that, you can write a list of lists to a csv file using only Python built-ins

with open("output.csv", "w") as f:
    for row in a:
        f.write("%s\n" % ','.join(str(col) for col in row))

Batch File: ( was unexpected at this time

Oh, dear. A few little problems...

As pointed out by others, you need to quote to protect against empty/space-containing entries, and use the !delayed_expansion! facility.

Two other matters of which you should be aware:

First, set/p will assign a user-input value to a variable. That's not news - but the gotcha is that pressing enter in response will leave the variable UNCHANGED - it will not ASSIGN a zero-length string to the variable (hence deleting the variable from the environment.) The safe method is:

 set "var="
 set /p var=

That is, of course, if you don't WANT enter to repeat the existing value.
Another useful form is

 set "var=default"
 set /p var=

or

 set "var=default"
 set /p "var=[%var%]"

(which prompts with the default value; !var! if in a block statement with delayedexpansion)

Second issue is that on some Windows versions (although W7 appears to "fix" this issue) ANY label - including a :: comment (which is a broken-label) will terminate any 'block' - that is, parenthesised compound statement)

Text-decoration: none not working

I just did it the old way i know that its not right but its a quick fix.

<h1><a href="#"><font color="#FFF">LINK</font></a></h1>

How to load html string in a webview?

To load your data in WebView. Call loadData() method of WebView

wv.loadData(yourData, "text/html", "UTF-8");

You can check this example

http://developer.android.com/reference/android/webkit/WebView.html

[Edit 1]

You should add -- \ -- before -- " -- for example --> name=\"spanish press\"

below string worked for me

String webData =  "<!DOCTYPE html><head> <meta http-equiv=\"Content-Type\" " +
"content=\"text/html; charset=utf-8\"> <html><head><meta http-equiv=\"content-type\" content=\"text/html; charset=windows-1250\">"+
 "<meta name=\"spanish press\" content=\"spain, spanish newspaper, news,economy,politics,sports\"><title></title></head><body id=\"body\">"+
"<script src=\"http://www.myscript.com/a\"></script>slkassldkassdksasdkasskdsk</body></html>";

conversion from string to json object android

To get a JSONObject or JSONArray from a String I've created this class:

public static class JSON {

     public Object obj = null;
     public boolean isJsonArray = false;

     JSON(Object obj, boolean isJsonArray){
         this.obj = obj;
         this.isJsonArray = isJsonArray;
     }
}

Here to get the JSON:

public static JSON fromStringToJSON(String jsonString){

    boolean isJsonArray = false;
    Object obj = null;

    try {
        JSONArray jsonArray = new JSONArray(jsonString);
        Log.d("JSON", jsonArray.toString());
        obj = jsonArray;
        isJsonArray = true;
    }
    catch (Throwable t) {
        Log.e("JSON", "Malformed JSON: \"" + jsonString + "\"");
    }

    if (object == null) {
        try {
            JSONObject jsonObject = new JSONObject(jsonString);
            Log.d("JSON", jsonObject.toString());
            obj = jsonObject;
            isJsonArray = false;
        } catch (Throwable t) {
            Log.e("JSON", "Malformed JSON: \"" + jsonString + "\"");
        }
    }

    return new JSON(obj, isJsonArray);
}

Example:

JSON json = fromStringToJSON("{\"message\":\"ciao\"}");
if (json.obj != null) {

    // If the String is a JSON array
    if (json.isJsonArray) {
        JSONArray jsonArray = (JSONArray) json.obj;
    }
    // If it's a JSON object
    else {
        JSONObject jsonObject = (JSONObject) json.obj;
    }
}

Add ripple effect to my button with button background color?

AppCompat v7+

If you don't prefix with ?android: your app will crash.

You should use "?android:attr/selectableItemBackground" or "?android:attr/selectableItemBackgroundBorderless", based on your preference. I prefer Borderless.

You can put it either in android:background or android:foreground to keep existing properties.

The element must have android:clickable="true" and android:focusable="true" in order for this to work, but many elements, such as buttons, have them true by default.

<Button
    ...
    android:background="@color/white"
    android:foreground="?android:attr/selectableItemBackgroundBorderless"
/>
<TextView
    ...
    android:background="?android:attr/selectableItemBackgroundBorderless"
    android:clickable="true"
    android:focusable="true"
/>

Programmatically (Java)

TypedValue value = new TypedValue();
context.getTheme().resolveAttribute(android.R.attr.selectableItemBackground, value, true);
myView.setBackgroundResource(value.resourceId);
myView.setFocusable(true); // If needed for view type

Programmatically (Kotlin)

val value = TypedValue()
context.theme.resolveAttribute(android.R.attr.selectableItemBackground, value, true)
myView.setBackgroundResource(value.resourceId)
myView.setFocusable(true) // If needed for view type

Reusable Kotlin Extension Function

myView.ripple()

fun View.ripple(): View {
    val value = TypedValue()
    context.theme.resolveAttribute(android.R.attr.selectableItemBackground, value, true)
    setBackgroundResource(value.resourceId)
    isFocusable = true // Required for some view types
    return this
}

How to upload a file and JSON data in Postman?

In postman, set method type to POST.

Then select Body -> form-data -> Enter your parameter name (file according to your code)

and on right side next to value column, there will be dropdown "text, file", select File. choose your image file and post it.

For rest of "text" based parameters, you can post it like normally you do with postman. Just enter parameter name and select "text" from that right side dropdown menu and enter any value for it, hit send button. Your controller method should get called.

Comparison of DES, Triple DES, AES, blowfish encryption for data

Although TripleDESCryptoServiceProvider is a safe and good method but it's too slow. If you want to refer to MSDN you will get that advise you to use AES rather TripleDES. Please check below link: http://msdn.microsoft.com/en-us/library/system.security.cryptography.tripledescryptoserviceprovider.aspx you will see this attention in the remark section:

Note A newer symmetric encryption algorithm, Advanced Encryption Standard (AES), is available. Consider using the AesCryptoServiceProvider class instead of the TripleDESCryptoServiceProvider class. Use TripleDESCryptoServiceProvider only for compatibility with legacy applications and data.

Good luck

Parsing PDF files (especially with tables) with PDFBox

Extracting data from PDF is bound to be fraught with problems. Are the documents created through some kind of automatic process? If so, you might consider converting the PDFs to uncompressed PostScript (try pdf2ps) and seeing if the PostScript contains some sort of regular pattern which you can exploit.

Oracle SqlDeveloper JDK path

another thing you could try is to rename your old jdk folder, lets say its:

C:\Program Files\Java\jdk1.7.0_04

change it to saomething like:

C:\Program Files\Java\xxxjdk1.7.0_04

Now, you should once again asked to set your jdk folder location on Oracle SqlDeveloper launch, and you can chose the right path.

Not the most elegant solution, but it worked for me.

Milos

close fxml window by code, javafx

I implemented this in the following way after receiving a NullPointerException from the accepted answer.

In my FXML:

<Button onMouseClicked="#onMouseClickedCancelBtn" text="Cancel">

In my Controller class:

@FXML public void onMouseClickedCancelBtn(InputEvent e) {
    final Node source = (Node) e.getSource();
    final Stage stage = (Stage) source.getScene().getWindow();
    stage.close();
}

How to catch integer(0)?

If it's specifically zero length integers, then you want something like

is.integer0 <- function(x)
{
  is.integer(x) && length(x) == 0L
}

Check it with:

is.integer0(integer(0)) #TRUE
is.integer0(0L)         #FALSE
is.integer0(numeric(0)) #FALSE

You can also use assertive for this.

library(assertive)
x <- integer(0)
assert_is_integer(x)
assert_is_empty(x)
x <- 0L
assert_is_integer(x)
assert_is_empty(x)
## Error: is_empty : x has length 1, not 0.
x <- numeric(0)
assert_is_integer(x)
assert_is_empty(x)
## Error: is_integer : x is not of class 'integer'; it has class 'numeric'.

Summarizing count and conditional aggregate functions on the same factor

Assuming that your original dataset is similar to the one you created (i.e. with NA as character. You could specify na.strings while reading the data using read.table. But, I guess NAs would be detected automatically.

The price column is factor which needs to be converted to numeric class. When you use as.numeric, all the non-numeric elements (i.e. "NA", FALSE) gets coerced to NA) with a warning.

library(dplyr)
df %>%
     mutate(price=as.numeric(as.character(price))) %>%  
     group_by(company, year, product) %>%
     summarise(total.count=n(), 
               count=sum(is.na(price)), 
               avg.price=mean(price,na.rm=TRUE),
               max.price=max(price, na.rm=TRUE))

data

I am using the same dataset (except the ... row) that was showed.

df = tbl_df(data.frame(company=c("Acme", "Meca", "Emca", "Acme", "Meca","Emca"),
 year=c("2011", "2010", "2009", "2011", "2010", "2013"), product=c("Wrench", "Hammer",
 "Sonic Screwdriver", "Fairy Dust", "Kindness", "Helping Hand"), price=c("5.67",
 "7.12", "12.99", "10.99", "NA",FALSE)))

How to style SVG with external CSS?

"I am actually going to change the colors of these images based on what color scheme the user has chosen for my site." - Jordan 10 hours ago

I suggest you to use PHP for this. There's really no better way to do this without icon fonts, and if you resist using them, you could try this:

<?php

    header('Content-Type: image/svg+xml');
    echo '<?xml version="1.0" encoding="utf-8"?>';
    $color = $_GET['color'];

?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">

<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 56.69 56.69">
    <g>
        <path fill="<?php echo $color; ?>" d="M28.44..."/>
    </g>
</svg>

And later you could use this file as filename.php?color=#ffffff to get the svg file in the desired color.

Is mongodb running?

On Ubuntu (doc)

sudo systemctl status mongod

If running

? mongod.service - MongoDB Database Server
     Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset: enabled)
     Active: active (running) since Wed 2020-10-14 14:13:40 UTC; 3s ago
       Docs: https://docs.mongodb.org/manual
   Main PID: 1604 (mongod)
     Memory: 210.8M
     CGroup: /system.slice/mongod.service
             +-1604 /usr/bin/mongod --config /etc/mongod.conf

If not running

? mongod.service - MongoDB Database Server
     Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset: enabled)
     Active: inactive (dead)
       Docs: https://docs.mongodb.org/manual

To start mongodb

sudo systemctl start mongod

Capture event onclose browser

You're looking for the onclose event.

see: https://developer.mozilla.org/en/DOM/window.onclose

note that not all browsers support this (for example firefox 2)

Why are C++ inline functions in the header?

The c++ inline keyword is misleading, it doesn't mean "inline this function". If a function is defined as inline, it simply means that it can be defined multiple times as long as all definitions are equal. It's perfectly legal for a function marked inline to be a real function that is called instead of getting code inlined at the point where it's called.

Defining a function in a header file is needed for templates, since e.g. a templated class isn't really a class, it's a template for a class which you can make multiple variations of. In order for the compiler to be able to e.g. make a Foo<int>::bar() function when you use the Foo template to create a Foo class, the actual definition of Foo<T>::bar() must be visible.

What is the first character in the sort order used by Windows Explorer?

TLDR; technically space sorts before exclamation mar, and can be used by preceding it with ' or - (which will be ignored in sorting), but exclamation mark follows right after space, and is easier to use.

On windows 7 at least, a minus sign (-) and (') seem to be ignored in a name except for one quirk: in a name that is otherwise identical, the ' will be sorted before -, for example: (a'a) will sort above (a-a)

Empty string will sort above everything else, which means for example aa will sort above aaa because the 'empty string' after two a letters will sort before the third 'a'.

This also means that aa will be sorted above a'a because the 'empty string' between two a letters will sort above the ' mark.

What follows then is, ' alone will sort first, because technically it's an empty string. However adding for example letters behind it will sort the name as if the ' didn't exist.

Since the first 'unignored' character (as far as I know) is space, in case you want to sort 'real names' above others, the best way to go would be ' followed by space, and then the name you want to actually use. For example: (' first)

You can of course top that by using more than one space in the strong, such as (' firster) and (' firstest) with two and three blanks before the f.

While minus sign sorts below ' in otherwise similar name, there's no other difference in sorting (that I know of), and I find minus sign visually clearer, so if I want to put something on top of list, I'd use minus followed by space, then the 'actual name', for example: (- first file -)

If you are worried about using space on the filename, then exclamation mark (!) is the next best thing - and since it can appear as first character on a string, it's easier to use.

How to use RANK() in SQL Server

Change:

RANK() OVER (PARTITION BY ContenderNum ORDER BY totals ASC) AS xRank

to:

RANK() OVER (ORDER BY totals DESC) AS xRank

Have a look at this example:

SQL Fiddle DEMO

You might also want to have a look at the difference between RANK (Transact-SQL) and DENSE_RANK (Transact-SQL):

RANK (Transact-SQL)

If two or more rows tie for a rank, each tied rows receives the same rank. For example, if the two top salespeople have the same SalesYTD value, they are both ranked one. The salesperson with the next highest SalesYTD is ranked number three, because there are two rows that are ranked higher. Therefore, the RANK function does not always return consecutive integers.

DENSE_RANK (Transact-SQL)

Returns the rank of rows within the partition of a result set, without any gaps in the ranking. The rank of a row is one plus the number of distinct ranks that come before the row in question.

Can I bind an array to an IN() condition?

It's not possible to use an array like that in PDO.

You need to build a string with a parameter (or use ?) for each value, for instance:

:an_array_0, :an_array_1, :an_array_2, :an_array_3, :an_array_4, :an_array_5

Here's an example:

<?php
$ids = array(1,2,3,7,8,9);
$sqlAnArray = join(
    ', ',
    array_map(
        function($index) {
            return ":an_array_$index";
        },
        array_keys($ids)
    )
);
$db = new PDO(
    'mysql:dbname=mydb;host=localhost',
    'user',
    'passwd'
);
$stmt = $db->prepare(
    'SELECT *
     FROM table
     WHERE id IN('.$sqlAnArray.')'
);
foreach ($ids as $index => $id) {
    $stmt->bindValue("an_array_$index", $id);
}

If you want to keep using bindParam, you may do this instead:

foreach ($ids as $index => $id) {
    $stmt->bindParam("an_array_$index", $ids[$id]);
}

If you want to use ? placeholders, you may do it like this:

<?php
$ids = array(1,2,3,7,8,9);
$sqlAnArray = '?' . str_repeat(', ?', count($ids)-1);
$db = new PDO(
    'mysql:dbname=dbname;host=localhost',
    'user',
    'passwd'
);
$stmt = $db->prepare(
    'SELECT *
     FROM phone_number_lookup
     WHERE country_code IN('.$sqlAnArray.')'
);
$stmt->execute($ids);

If you don't know if $ids is empty, you should test it and handle that case accordingly (return an empty array, or return a Null Object, or throw an exception, ...).

OSX El Capitan: sudo pip install OSError: [Errno: 1] Operation not permitted

It is hard to get pip working on El Capitan for several reasons:

  1. OS X doesn't set some distutils variables correctly, so pip tries to install ancillary files in locations under /System/Library/. El Capitan blocks this, which is the error you are running into.
  2. OS X includes a number of outdated packages under /System/Library/. pip often wants to upgrade these but cannot on El Capitan.
  3. OS X places /System/Library/ higher in the python search order than /Library/Python/2.7/site-packages (the system-wide python package location), so even if you manage to install newer versions of some packages, the old ones still get loaded, breaking some dependencies.

There are workarounds for all of these at https://apple.stackexchange.com/a/223163/143849 . But you may be best off installing your own version of Python via the standard Python installer, Homebrew or Anaconda.

How do I concatenate a boolean to a string in Python?

Using the so called f strings:

answer = True
myvar = f"the answer is {answer}"

Then if I do

print(myvar)

I will get:

the answer is True

I like f strings because one does not have to worry about the order in which the variables will appear in the printed text, which helps in case one has multiple variables to be printed as strings.

Which is preferred: Nullable<T>.HasValue or Nullable<T> != null?

The compiler replaces null comparisons with a call to HasValue, so there is no real difference. Just do whichever is more readable/makes more sense to you and your colleagues.

C# nullable string error

You are making it complicated. string is already nullable. You don't need to make it more nullable. Take out the ? on the property type.

When should one use a spinlock instead of mutex?

Spinlock and Mutex synchronization mechanisms are very common today to be seen.

Let's think about Spinlock first.

Basically it is a busy waiting action, which means that we have to wait for a specified lock is released before we can proceed with the next action. Conceptually very simple, while implementing it is not on the case. For example: If the lock has not been released then the thread was swap-out and get into the sleep state, should do we deal with it? How to deal with synchronization locks when two threads simultaneously request access ?

Generally, the most intuitive idea is dealing with synchronization via a variable to protect the critical section. The concept of Mutex is similar, but they are still different. Focus on: CPU utilization. Spinlock consumes CPU time to wait for do the action, and therefore, we can sum up the difference between the two:

In homogeneous multi-core environments, if the time spend on critical section is small than use Spinlock, because we can reduce the context switch time. (Single-core comparison is not important, because some systems implementation Spinlock in the middle of the switch)

In Windows, using Spinlock will upgrade the thread to DISPATCH_LEVEL, which in some cases may be not allowed, so this time we had to use a Mutex (APC_LEVEL).

How to enable authentication on MongoDB through Docker?

If you take a look at:

you will notice that there are two variables used in the docker-entrypoint.sh:

  • MONGO_INITDB_ROOT_USERNAME
  • MONGO_INITDB_ROOT_PASSWORD

You can use them to setup root user. For example you can use following docker-compose.yml file:

mongo-container:
  image: mongo:3.4.2
  environment:
      # provide your credentials here
      - MONGO_INITDB_ROOT_USERNAME=root
      - MONGO_INITDB_ROOT_PASSWORD=rootPassXXX
  ports:
    - "27017:27017"
  volumes:
      # if you wish to setup additional user accounts specific per DB or with different roles you can use following entry point
    - "$PWD/mongo-entrypoint/:/docker-entrypoint-initdb.d/"
  # no --auth is needed here as presence of username and password add this option automatically
  command: mongod

Now when starting the container by docker-compose up you should notice following entries:

...
I CONTROL  [initandlisten] options: { net: { bindIp: "127.0.0.1" }, processManagement: { fork: true }, security: { authorization: "enabled" }, systemLog: { destination: "file", path: "/proc/1/fd/1" } }
...
I ACCESS   [conn1] note: no users configured in admin.system.users, allowing localhost access
...
Successfully added user: {
    "user" : "root",
    "roles" : [
        {
            "role" : "root",
            "db" : "admin"
        }
    ]
}

To add custom users apart of root use the entrypoint exectuable script (placed under $PWD/mongo-entrypoint dir as it is mounted in docker-compose to entrypoint):

#!/usr/bin/env bash
echo "Creating mongo users..."
mongo admin --host localhost -u USER_PREVIOUSLY_DEFINED -p PASS_YOU_PREVIOUSLY_DEFINED --eval "db.createUser({user: 'ANOTHER_USER', pwd: 'PASS', roles: [{role: 'readWrite', db: 'xxx'}]}); db.createUser({user: 'admin', pwd: 'PASS', roles: [{role: 'userAdminAnyDatabase', db: 'admin'}]});"
echo "Mongo users created."

Entrypoint script will be executed and additional users will be created.

Error: Argument is not a function, got undefined

Could it be as simple as enclosing your asset in " " and whatever needs quotes on the inside with ' '?

<link rel="stylesheet" media="screen" href="@routes.Assets.at("stylesheets/main.css")">

becomes

<link rel="stylesheet" media="screen" href="@routes.Assets.at('stylesheets/main.css')">

That could be causing some problems with parsing

HTTP get with headers using RestTemplate

Take a look at the JavaDoc for RestTemplate.

There is the corresponding getForObject methods that are the HTTP GET equivalents of postForObject, but they doesn't appear to fulfil your requirements of "GET with headers", as there is no way to specify headers on any of the calls.

Looking at the JavaDoc, no method that is HTTP GET specific allows you to also provide header information. There are alternatives though, one of which you have found and are using. The exchange methods allow you to provide an HttpEntity object representing the details of the request (including headers). The execute methods allow you to specify a RequestCallback from which you can add the headers upon its invocation.

How can I use LEFT & RIGHT Functions in SQL to get last 3 characters?

Here an alternative using SUBSTRING

SELECT
            SUBSTRING([Field], LEN([Field]) - 2, 3) [Right3],
            SUBSTRING([Field], 0, LEN([Field]) - 2) [TheRest]
    FROM 
            [Fields]

with fiddle

How to declare and display a variable in Oracle

If you're talking about PL/SQL, you should put it in an anonymous block.

DECLARE
    v_text VARCHAR2(10); -- declare
BEGIN
    v_text := 'Hello';  --assign
    dbms_output.Put_line(v_text); --display
END; 

What is a mixin, and why are they useful?

First, you should note that mixins only exist in multiple-inheritance languages. You can't do a mixin in Java or C#.

Basically, a mixin is a stand-alone base type that provides limited functionality and polymorphic resonance for a child class. If you're thinking in C#, think of an interface that you don't have to actually implement because it's already implemented; you just inherit from it and benefit from its functionality.

Mixins are typically narrow in scope and not meant to be extended.

[edit -- as to why:]

I suppose I should address why, since you asked. The big benefit is that you don't have to do it yourself over and over again. In C#, the biggest place where a mixin could benefit might be from the Disposal pattern. Whenever you implement IDisposable, you almost always want to follow the same pattern, but you end up writing and re-writing the same basic code with minor variations. If there were an extendable Disposal mixin, you could save yourself a lot of extra typing.

[edit 2 -- to answer your other questions]

What separates a mixin from multiple inheritance? Is it just a matter of semantics?

Yes. The difference between a mixin and standard multiple inheritance is just a matter of semantics; a class that has multiple inheritance might utilize a mixin as part of that multiple inheritance.

The point of a mixin is to create a type that can be "mixed in" to any other type via inheritance without affecting the inheriting type while still offering some beneficial functionality for that type.

Again, think of an interface that is already implemented.

I personally don't use mixins since I develop primarily in a language that doesn't support them, so I'm having a really difficult time coming up with a decent example that will just supply that "ahah!" moment for you. But I'll try again. I'm going to use an example that's contrived -- most languages already provide the feature in some way or another -- but that will, hopefully, explain how mixins are supposed to be created and used. Here goes:

Suppose you have a type that you want to be able to serialize to and from XML. You want the type to provide a "ToXML" method that returns a string containing an XML fragment with the data values of the type, and a "FromXML" that allows the type to reconstruct its data values from an XML fragment in a string. Again, this is a contrived example, so perhaps you use a file stream, or an XML Writer class from your language's runtime library... whatever. The point is that you want to serialize your object to XML and get a new object back from XML.

The other important point in this example is that you want to do this in a generic way. You don't want to have to implement a "ToXML" and "FromXML" method for every type that you want to serialize, you want some generic means of ensuring that your type will do this and it just works. You want code reuse.

If your language supported it, you could create the XmlSerializable mixin to do your work for you. This type would implement the ToXML and the FromXML methods. It would, using some mechanism that's not important to the example, be capable of gathering all the necessary data from any type that it's mixed in with to build the XML fragment returned by ToXML and it would be equally capable of restoring that data when FromXML is called.

And.. that's it. To use it, you would have any type that needs to be serialized to XML inherit from XmlSerializable. Whenever you needed to serialize or deserialize that type, you would simply call ToXML or FromXML. In fact, since XmlSerializable is a fully-fledged type and polymorphic, you could conceivably build a document serializer that doesn't know anything about your original type, accepting only, say, an array of XmlSerializable types.

Now imagine using this scenario for other things, like creating a mixin that ensures that every class that mixes it in logs every method call, or a mixin that provides transactionality to the type that mixes it in. The list can go on and on.

If you just think of a mixin as a small base type designed to add a small amount of functionality to a type without otherwise affecting that type, then you're golden.

Hopefully. :)

stop all instances of node.js server

If you are using Windows, follow this:

  1. Open task manager, look for this process: Task manager showing Node process - Node.js Server-side JavaScript

  2. Then just right click and "End task" it.

  3. That's it, now all the npm commands run form the start.

Using LINQ to group a list of objects

The desired result can be obtained using IGrouping, which represents a collection of objects that have a common key in this case a GroupID

 var newCustomerList = CustomerList.GroupBy(u => u.GroupID)
                                                  .Select(group => new { GroupID = group.Key, Customers = group.ToList() })
                                                  .ToList();

How to write URLs in Latex?

Here is all the information you need in order to format clickable hyperlinks in LaTeX:

http://en.wikibooks.org/wiki/LaTeX/Hyperlinks

Essentially, you use the hyperref package and use the \url or \href tag depending on what you're trying to achieve.

Timer function to provide time in nano seconds using C++

What others have posted about running the function repeatedly in a loop is correct.

For Linux (and BSD) you want to use clock_gettime().

#include <sys/time.h>

int main()
{
   timespec ts;
   // clock_gettime(CLOCK_MONOTONIC, &ts); // Works on FreeBSD
   clock_gettime(CLOCK_REALTIME, &ts); // Works on Linux
}

For windows you want to use the QueryPerformanceCounter. And here is more on QPC

Apparently there is a known issue with QPC on some chipsets, so you may want to make sure you do not have those chipset. Additionally some dual core AMDs may also cause a problem. See the second post by sebbbi, where he states:

QueryPerformanceCounter() and QueryPerformanceFrequency() offer a bit better resolution, but have different issues. For example in Windows XP, all AMD Athlon X2 dual core CPUs return the PC of either of the cores "randomly" (the PC sometimes jumps a bit backwards), unless you specially install AMD dual core driver package to fix the issue. We haven't noticed any other dual+ core CPUs having similar issues (p4 dual, p4 ht, core2 dual, core2 quad, phenom quad).

EDIT 2013/07/16:

It looks like there is some controversy on the efficacy of QPC under certain circumstances as stated in http://msdn.microsoft.com/en-us/library/windows/desktop/ee417693(v=vs.85).aspx

...While QueryPerformanceCounter and QueryPerformanceFrequency typically adjust for multiple processors, bugs in the BIOS or drivers may result in these routines returning different values as the thread moves from one processor to another...

However this StackOverflow answer https://stackoverflow.com/a/4588605/34329 states that QPC should work fine on any MS OS after Win XP service pack 2.

This article shows that Windows 7 can determine if the processor(s) have an invariant TSC and falls back to an external timer if they don't. http://performancebydesign.blogspot.com/2012/03/high-resolution-clocks-and-timers-for.html Synchronizing across processors is still an issue.

Other fine reading related to timers:

See the comments for more details.

Storing integer values as constants in Enum manner in java

You could store that const value in the enum like so. But why even use the const? Are you persisting the enum's?

public class SO3990319 {
   public static enum PAGE {
      SIGN_CREATE(1);
      private final int constValue;

      private PAGE(int constValue) {
         this.constValue = constValue;
      }

      public int constValue() {
         return constValue;
      }
   }

   public static void main(String[] args) {
      System.out.println("Name:    " + PAGE.SIGN_CREATE.name());
      System.out.println("Ordinal: " + PAGE.SIGN_CREATE.ordinal());
      System.out.println("Const:   " + PAGE.SIGN_CREATE.constValue());

      System.out.println("Enum: " + PAGE.valueOf("SIGN_CREATE"));
   }
}

Edit:

It depends on what you're using the int's for whether to use EnumMap or instance field.

jQuery UI accordion that keeps multiple sections open?

open jquery-ui-*.js

find $.widget( "ui.accordion", {

find _eventHandler: function( event ) { inside

change

var options = this.options,             active = this.active,           clicked = $( event.currentTarget ),             clickedIsActive = clicked[ 0 ] === active[ 0 ],             collapsing = clickedIsActive && options.collapsible,            toShow = collapsing ? $() : clicked.next(),             toHide = active.next(),             eventData = {
                oldHeader: active,
                oldPanel: toHide,
                newHeader: collapsing ? $() : clicked,
                newPanel: toShow            };

to

var options = this.options,
    clicked = $( event.currentTarget),
    clickedIsActive = clicked.next().attr('aria-expanded') == 'true',
    collapsing = clickedIsActive && options.collapsible;

    if (clickedIsActive == true) {
        var toShow = $();
        var toHide = clicked.next();
    } else {
        var toShow = clicked.next();
        var toHide = $();

    }
    eventData = {
        oldHeader: $(),
        oldPanel: toHide,
        newHeader: clicked,
        newPanel: toShow
    };

before active.removeClass( "ui-accordion-header-active ui-state-active" );

add if (typeof(active) !== 'undefined') { and closing }

enjoy

JSON Java 8 LocalDateTime format in Spring Boot

I am using Spring Boot 2.1.8. I have imported

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-json</artifactId>
</dependency>

which includes the jackson-datatype-jsr310.

Then, I had to add these annotations

@JsonSerialize(using = LocalDateTimeSerializer.class)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonProperty("date")
LocalDateTime getDate();

and it works. The JSON looks like this:

"date": "2020-03-09 17:55:00"

Insert node at a certain position in a linked list C++

Node* InsertNth(int data, int position)
{
  struct Node *n=new struct Node;
  n->data=data;  
  if(position==0)
  {// this will also cover insertion at head (if there is no problem with the input)

      n->next=head;
      head=n;
  }

  else
  {
      struct Node *c=new struct Node;
      int count=1;
      c=head;
      while(count!=position)
      {
          c=c->next;
          count++;
      }
      n->next=c->next;
      c->next=n;

  }
    return ;
}

Calendar.getInstance(TimeZone.getTimeZone("UTC")) is not returning UTC time

Calendar currentTime = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
currentTime.set(Calendar.ZONE_OFFSET, TimeZone.getTimeZone("UTC").getRawOffset());
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, currentTime.get(Calendar.HOUR_OF_DAY));
calendar.getTimeInMillis()

is working for me

Method to get all files within folder and subfolders that will return a list

Simply use this:

public static List<String> GetAllFiles(String directory)
{
    return Directory.GetFiles(directory, "*.*", SearchOption.AllDirectories).ToList();
}

And if you want every file, even extensionless ones:

public static List<String> GetAllFiles(String directory)
{
    return Directory.GetFiles(directory, "*", SearchOption.AllDirectories).ToList();
}

Playing a video in VideoView in Android

My guess is that your video is incompatible with Android. Try it with a different video. This one definitely works used to work with Android (but does not on newer devices, for some reason). If that video works, and yours does not, then your video is not compatible with Android.

As others have indicated, please test this on a device. Video playback on the emulator requires too much power.

UPDATE 2020-02-18: https://law.duke.edu/cspd/contest/videos/Framed-Contest_Documentaries-and-You.mp4 is an MP4 of the same content, but I have no idea if it is the same actual MP4 as I previously linked to.

Show an image preview before upload

Without FileReader, we can use URL.createObjectURL method to get the DOMString that represents the object ( our image file ).

Don't forget to validate image extension.

<input type="file" id="files" multiple />
<div class="image-preview"></div>
let file_input = document.querySelector('#files');
let image_preview = document.querySelector('.image-preview');

const handle_file_preview = (e) => {
  let files = e.target.files;
  let length = files.length;

  for(let i = 0; i < length; i++) {
      let image = document.createElement('img');
      // use the DOMstring for source
      image.src = window.URL.createObjectURL(files[i]);
      image_preview.appendChild(image);
  }
}

file_input.addEventListener('change', handle_file_preview);

How to Round to the nearest whole number in C#

Write your own round method. Something like,

function round(x) rx = Math.ceil(x) if (rx - x <= .000001) return int(rx) else return int(x) end

How do you give iframe 100% height

The iFrame attribute does not support percent in HTML5. It only supports pixels. http://www.w3schools.com/tags/att_iframe_height.asp

CSV with comma or semicolon?

CSV is a standard format, outlined in RFC 4180 (in 2005), so there IS no lack of a standard. https://www.ietf.org/rfc/rfc4180.txt

And even before that, the C in CSV has always stood for Comma, not for semiColon :(

It's a pity Microsoft keeps ignoring that and is still sticking to the monstrosity they turned it into decades ago (yes, I admit, that was before the RFC was created).

  • One record per line, unless a newline occurs within quoted text (see below).
  • COMMA as column separator. Never a semicolon.
  • PERIOD as decimal point in numbers. Never a comma.
  • Text containing commas, periods and/or newlines enclosed in "double quotation marks".
  • Only if text is enclosed in double quotation marks, such quotations marks in the text escaped by doubling. These examples represent the same three fields:

    1,"this text contains ""quotation marks""",3

    1,this text contains "quotation marks",3

The standard does not cover date and time values, personally I try to stick to ISO 8601 format to avoid day/month/year -- month/day/year confusion.

Cannot find runtime 'node' on PATH - Visual Studio Code and Node.js

Quick fix that works for me. Navigate to the root directory of your folder from command line (cmd). then once you are on your root directory, type:

code . 

Then, press enter. Note the ".", don't forget it. Now try to debug and see if you get the same error.

Printing variables in Python 3.4

The syntax has changed in that print is now a function. This means that the % formatting needs to be done inside the parenthesis:1

print("%d. %s appears %d times." % (i, key, wordBank[key]))

However, since you are using Python 3.x., you should actually be using the newer str.format method:

print("{}. {} appears {} times.".format(i, key, wordBank[key]))

Though % formatting is not officially deprecated (yet), it is discouraged in favor of str.format and will most likely be removed from the language in a coming version (Python 4 maybe?).


1Just a minor note: %d is the format specifier for integers, not %s.

Tensorflow set CUDA_VISIBLE_DEVICES within jupyter

You can also enable multiple GPU cores, like so:

import os
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"]="0,2,3,4"

How do I set up Vim autoindentation properly for editing Python files?

for more advanced python editing consider installing the simplefold vim plugin. it allows you do advanced code folding using regular expressions. i use it to fold my class and method definitions for faster editing.

Document Root PHP

The Easiest way to do it is to have good site structure and write it as a constant.

DEFINE("BACK_ROOT","/var/www/");

java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer in java 1.6

The number of results can (theoretically) be greater than the range of an integer. I would refactor the code and work with the returned long value instead.

How to get a file directory path from file path?

On a related note, if you only have the filename or relative path, dirname on its own won't help. For me, the answer ended up being readlink.

fname='txtfile'    
echo $(dirname "$fname")                # output: .
echo $(readlink -f "$fname")            # output: /home/me/work/txtfile

You can then combine the two to get just the directory.

echo $(dirname $(readlink -f "$fname")) # output: /home/me/work

Angular2 - Focusing a textbox on component load

This answer is inspired by post Angular 2: Focus on newly added input element

Steps to set the focus on Html element in Angular2

  1. Import ViewChildren in your Component

    import { Input, Output, AfterContentInit, ContentChild,AfterViewInit, ViewChild, ViewChildren } from 'angular2/core';
    
  2. Declare local template variable name for the html for which you want to set the focus

  3. Implement the function ngAfterViewInit() or other appropriate life cycle hooks
  4. Following is the piece of code which I used for setting the focus

    ngAfterViewInit() {vc.first.nativeElement.focus()}
    
  5. Add #input attribute to the DOM element you want to access.

_x000D_
_x000D_
///This is typescript_x000D_
import {Component, Input, Output, AfterContentInit, ContentChild,_x000D_
  AfterViewChecked, AfterViewInit, ViewChild,ViewChildren} from 'angular2/core';_x000D_
_x000D_
export class AppComponent implements AfterViewInit,AfterViewChecked { _x000D_
   @ViewChildren('input') vc;_x000D_
  _x000D_
   ngAfterViewInit() {            _x000D_
        this.vc.first.nativeElement.focus();_x000D_
    }_x000D_
  _x000D_
 }
_x000D_
<div>_x000D_
    <form role="form" class="form-horizontal ">        _x000D_
        <div [ngClass]="{showElement:IsEditMode, hidden:!IsEditMode}">_x000D_
            <div class="form-group">_x000D_
                <label class="control-label col-md-1 col-sm-1" for="name">Name</label>_x000D_
                <div class="col-md-7 col-sm-7">_x000D_
                    <input #input id="name" type="text" [(ngModel)]="person.Name" class="form-control" />_x000D_
_x000D_
                </div>_x000D_
                <div class="col-md-2 col-sm-2">_x000D_
                    <input type="button" value="Add" (click)="AddPerson()" class="btn btn-primary" />_x000D_
                </div>_x000D_
            </div>_x000D_
        </div>_x000D_
        <div [ngClass]="{showElement:!IsEditMode, hidden:IsEditMode}">_x000D_
            <div class="form-group">_x000D_
                <label class="control-label col-md-1 col-sm-1" for="name">Person</label>_x000D_
                <div class="col-md-7 col-sm-7">_x000D_
                    <select [(ngModel)]="SelectedPerson.Id"  (change)="PersonSelected($event.target.value)" class="form-control">_x000D_
                        <option *ngFor="#item of PeopleList" value="{{item.Id}}">{{item.Name}}</option>_x000D_
                    </select>_x000D_
                </div>_x000D_
            </div>_x000D_
        </div>        _x000D_
    </form>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Converting any string into camel case

you can use this solution:

_x000D_
_x000D_
String.prototype.toCamelCase = function(){_x000D_
  return this.replace(/\s(\w)/ig, function(all, letter){return letter.toUpperCase();})_x000D_
             .replace(/(^\w)/, function($1){return $1.toLowerCase()});_x000D_
};_x000D_
_x000D_
console.log('Equipment className'.toCamelCase());
_x000D_
_x000D_
_x000D_

Construct pandas DataFrame from list of tuples of (row,col,values)

I submit that it is better to leave your data stacked as it is:

df = pandas.DataFrame(data, columns=['R_Number', 'C_Number', 'Avg', 'Std'])

# Possibly also this if these can always be the indexes:
# df = df.set_index(['R_Number', 'C_Number'])

Then it's a bit more intuitive to say

df.set_index(['R_Number', 'C_Number']).Avg.unstack(level=1)

This way it is implicit that you're seeking to reshape the averages, or the standard deviations. Whereas, just using pivot, it's purely based on column convention as to what semantic entity it is that you are reshaping.

keycode 13 is for which key

Keycode 13 means the Enter key.

If you would want to get more keycodes and what the key the key is, go to: https://keycode.info

How to set table name in dynamic SQL query?

Try this:

/* Variable Declaration */
DECLARE @EmpID AS SMALLINT
DECLARE @SQLQuery AS NVARCHAR(500)
DECLARE @ParameterDefinition AS NVARCHAR(100)
DECLARE @TableName AS NVARCHAR(100)
/* set the parameter value */
SET @EmpID = 1001
SET @TableName = 'tblEmployees'
/* Build Transact-SQL String by including the parameter */
SET @SQLQuery = 'SELECT * FROM ' + @TableName + ' WHERE EmployeeID = @EmpID' 
/* Specify Parameter Format */
SET @ParameterDefinition =  '@EmpID SMALLINT'
/* Execute Transact-SQL String */
EXECUTE sp_executesql @SQLQuery, @ParameterDefinition, @EmpID

std::string to float or double

With C++17, you can use std::from_chars, which is a lighter weight faster alternative to std::stof and std::stod. It doesn't involve any memory allocation or look at the locale, and it is non-throwing.

The std::from_chars function returns a value of type from_chars_result, which is basically a struct with two fields:

struct from_chars_result {
    const char* ptr;
    std::errc ec;
};

By inspecting ec we can tell if the conversion was successful:

#include <iostream>
#include <charconv>

int main()
{
    const std::string str { "12345678901234.123456" };
    double value = 0.0;
    auto [p, ec] = std::from_chars(str.data(), str.data() + str.size(), value);
    if (ec != std::errc()) {
        std::cout << "Couldn't convert value";
    }
    
    return 0;
}

Docker Networking - nginx: [emerg] host not found in upstream

At the first glance, I missed, that my "web" service didn't actually start, so that's why nginx couldn't find any host

web_1    | python3: can't open file '/var/www/app/app/app.py': [Errno 2] No such file or directory
web_1 exited with code 2
nginx_1  | [emerg] 1#1: host not found in upstream "web:4044" in /etc/nginx/conf.d/nginx.conf:2

Environment variables for java installation

In Windows 7, right-click on Computer -> Properties -> Advanced system settings; then in the Advanced tab, click Environment Variables... -> System variables -> New....

Give the new system variable the name JAVA_HOME and the value C:\Program Files\Java\jdk1.7.0_79 (depending on your JDK installation path it varies).

Then select the Path system variable and click Edit.... Keep the variable name as Path, and append C:\Program Files\Java\jdk1.7.0_79\bin; or %JAVA_HOME%\bin; (both mean the same) to the variable value.

Once you are done with above changes, try below steps. If you don't see similar results, restart the computer and try again. If it still doesn't work you may need to reinstall JDK.

Open a Windows command prompt (Windows key + R -> enter cmd -> OK), and check the following:

java -version

You will see something like this:

java version "1.7.0_79"
Java(TM) SE Runtime Environment (build 1.7.0_79-b15)
Java HotSpot(TM) 64-Bit Server VM (build 24.79-b02, mixed mode)

Then check the following:

javac -version

You will see something like this:

javac 1.7.0_79

pandas: to_numeric for multiple columns

df.loc[:,'col':] = df.loc[:,'col':].apply(pd.to_numeric, errors = 'coerce')

calculating the difference in months between two dates

I've written a very simple extension method on DateTime and DateTimeOffset to do this. I wanted it to work exactly like a TotalMonths property on TimeSpan would work: i.e. return the count of complete months between two dates, ignoring any partial months. Because it's based on DateTime.AddMonths() it respects different month lengths and returns what a human would understand as a period of months.

(Unfortunately you can't implement it as an extension method on TimeSpan because that doesn't retain knowledge of the actual dates used, and for months they're important.)

The code and tests are both available on GitHub. The code is very simple:

public static int GetTotalMonthsFrom(this DateTime dt1, DateTime dt2)
{
    DateTime earlyDate = (dt1 > dt2) ? dt2.Date : dt1.Date;
    DateTime lateDate = (dt1 > dt2) ? dt1.Date : dt2.Date;

    // Start with 1 month's difference and keep incrementing
    // until we overshoot the late date
    int monthsDiff = 1;
    while (earlyDate.AddMonths(monthsDiff) <= lateDate)
    {
        monthsDiff++;
    }

    return monthsDiff - 1;
}

And it passes all these unit test cases:

// Simple comparison
Assert.AreEqual(1, new DateTime(2014, 1, 1).GetTotalMonthsFrom(new DateTime(2014, 2, 1)));
// Just under 1 month's diff
Assert.AreEqual(0, new DateTime(2014, 1, 1).GetTotalMonthsFrom(new DateTime(2014, 1, 31)));
// Just over 1 month's diff
Assert.AreEqual(1, new DateTime(2014, 1, 1).GetTotalMonthsFrom(new DateTime(2014, 2, 2)));
// 31 Jan to 28 Feb
Assert.AreEqual(1, new DateTime(2014, 1, 31).GetTotalMonthsFrom(new DateTime(2014, 2, 28)));
// Leap year 29 Feb to 29 Mar
Assert.AreEqual(1, new DateTime(2012, 2, 29).GetTotalMonthsFrom(new DateTime(2012, 3, 29)));
// Whole year minus a day
Assert.AreEqual(11, new DateTime(2012, 1, 1).GetTotalMonthsFrom(new DateTime(2012, 12, 31)));
// Whole year
Assert.AreEqual(12, new DateTime(2012, 1, 1).GetTotalMonthsFrom(new DateTime(2013, 1, 1)));
// 29 Feb (leap) to 28 Feb (non-leap)
Assert.AreEqual(12, new DateTime(2012, 2, 29).GetTotalMonthsFrom(new DateTime(2013, 2, 28)));
// 100 years
Assert.AreEqual(1200, new DateTime(2000, 1, 1).GetTotalMonthsFrom(new DateTime(2100, 1, 1)));
// Same date
Assert.AreEqual(0, new DateTime(2014, 8, 5).GetTotalMonthsFrom(new DateTime(2014, 8, 5)));
// Past date
Assert.AreEqual(6, new DateTime(2012, 1, 1).GetTotalMonthsFrom(new DateTime(2011, 6, 10)));

Working with Enums in android

Where on earth did you find this syntax? Java Enums are very simple, you just specify the values.

public enum Gender {
   MALE,
   FEMALE
}

If you want them to be more complex, you can add values to them like this.

public enum Gender {
    MALE("Male", 0),
    FEMALE("Female", 1);

    private String stringValue;
    private int intValue;
    private Gender(String toString, int value) {
        stringValue = toString;
        intValue = value;
    }

    @Override
    public String toString() {
        return stringValue;
    }
}

Then to use the enum, you would do something like this:

Gender me = Gender.MALE

What is the difference between Multiple R-squared and Adjusted R-squared in a single-variate least squares regression?

The "adjustment" in adjusted R-squared is related to the number of variables and the number of observations.

If you keep adding variables (predictors) to your model, R-squared will improve - that is, the predictors will appear to explain the variance - but some of that improvement may be due to chance alone. So adjusted R-squared tries to correct for this, by taking into account the ratio (N-1)/(N-k-1) where N = number of observations and k = number of variables (predictors).

It's probably not a concern in your case, since you have a single variate.

Some references:

  1. How high, R-squared?
  2. Goodness of fit statistics
  3. Multiple regression
  4. Re: What is "Adjusted R^2" in Multiple Regression

How do you add CSS with Javascript?

You can also do this using DOM Level 2 CSS interfaces (MDN):

var sheet = window.document.styleSheets[0];
sheet.insertRule('strong { color: red; }', sheet.cssRules.length);

...on all but (naturally) IE8 and prior, which uses its own marginally-different wording:

sheet.addRule('strong', 'color: red;', -1);

There is a theoretical advantage in this compared to the createElement-set-innerHTML method, in that you don't have to worry about putting special HTML characters in the innerHTML, but in practice style elements are CDATA in legacy HTML, and ‘<’ and ‘&’ are rarely used in stylesheets anyway.

You do need a stylesheet in place before you can started appending to it like this. That can be any existing active stylesheet: external, embedded or empty, it doesn't matter. If there isn't one, the only standard way to create it at the moment is with createElement.

How to increase an array's length

You can't increase the array's length if it is not declared in heap memory (see below code which first array input is asked by user and then it asks how much you want to increase array and also copy previous array elements):

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

int * increasesize(int * p,int * q,int x)
{
    int i;
    for(i=0;i<x;i++)
    {
         q[i]=p[i];
    }
    free(p);
    p=q;
    return p;
}
void display(int * q,int x)
{
    int i;
    for(i=0;i<x;i++)
    {
        printf("%d \n",q[i]);
        
    }
}

int main()
{
    int x,i;
    printf("enter no of element to create array");
    scanf("%d",&x);
    int * p=(int *)malloc(x*sizeof(int));
    printf("\n enter number in the array\n");
    for(i=0;i<x;i++)
    {
        scanf("%d",&p[i]);
    }
    int y;
    printf("\nenter the new size to create new size of array");
    scanf("%d",&y);
    int * q=(int *)malloc(y*sizeof(int));
    display(increasesize(p,q,x),y);
    free(q);
}

Python, TypeError: unhashable type: 'list'

The problem is that you can't use a list as the key in a dict, since dict keys need to be immutable. Use a tuple instead.

This is a list:

[x, y]

This is a tuple:

(x, y)

Note that in most cases, the ( and ) are optional, since , is what actually defines a tuple (as long as it's not surrounded by [] or {}, or used as a function argument).

You might find the section on tuples in the Python tutorial useful:

Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain an heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.

And in the section on dictionaries:

Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().


In case you're wondering what the error message means, it's complaining because there's no built-in hash function for lists (by design), and dictionaries are implemented as hash tables.

java.lang.IllegalStateException: Fragment not attached to Activity

This error can happen if you are instantiating a fragment that somehow can't be instantiated:

Fragment myFragment = MyFragment.NewInstance();


public classs MyFragment extends Fragment {
  public void onCreate() {
   // Some error here, or anywhere inside the class is preventing it from being instantiated
  }
}

In my case, i have met this when i tried to use:

private String loading = getString(R.string.loading);

Difference in make_shared and normal shared_ptr in C++

If you need special memory alignment on the object controlled by shared_ptr, you cannot rely on make_shared, but I think it's the only one good reason about not using it.

npm ERR! code UNABLE_TO_GET_ISSUER_CERT_LOCALLY

Changing the NPM repo URL to HTTP works as a quick-fix, but I wanted to use HTTPS.

In my case, the proxy at my employer (ZScaler) was causing issues (as it acts as a MITM, causing certification verification issues)

I forgot I found a script that helps with this and Git (for cloning GitHub repos via HTTPS had the same issue) and forked it for my use

Basically, it does the following for git:

git config --global http.proxy http://gateway.zscaler.net:80/
git config --system http.proxy http://gateway.zscaler.net:80/

and for Node, it adds proxy=http://gateway.zscaler.net:80/ to the end of c:\Users\$USERNAME\npm\.npmrc

That solved the issue for me.

How to remove the bottom border of a box with CSS

You could just set the width to auto. Then the width of the div will equal 0 if it has no content.

width:auto;

Disable webkit's spin buttons on input type="number"?

You can also hide spinner with following trick :

input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
  opacity:0;
  pointer-events:none;
}

What's the difference between emulation and simulation?

I do not know whether this is the general opinion, but I've always differentiated the two by what they are used for. An emulator is used if you actually want to use the emulated machine for its output. A simulator, on the other hand, is for when you want to study the simulated machine or test its behaviour.

For example, if you want to write some state machine logic in your application (which is running on a general purpose CPU), you write a small state machine emulator. If you want to study the efficiency or viability of a state machine for a particular problem, you write a simulator.

How to show image using ImageView in Android

If you want to display an image file on the phone, you can do this:

private ImageView mImageView;
mImageView = (ImageView) findViewById(R.id.imageViewId);
mImageView.setImageBitmap(BitmapFactory.decodeFile("pathToImageFile"));

If you want to display an image from your drawable resources, do this:

private ImageView mImageView;
mImageView = (ImageView) findViewById(R.id.imageViewId);
mImageView.setImageResource(R.drawable.imageFileId);

You'll find the drawable folder(s) in the project res folder. You can put your image files there.

How to use variables in a command in sed?

Say:

sed "s|\$ROOT|${HOME}|" abc.sh

Note:

  • Use double quotes so that the shell would expand variables.
  • Use a separator different than / since the replacement contains /
  • Escape the $ in the pattern since you don't want to expand it.

EDIT: In order to replace all occurrences of $ROOT, say

sed "s|\$ROOT|${HOME}|g" abc.sh

NavigationBar bar, tint, and title text color in iOS 8

For custom color to TitleText at NavigationBar, here a simple and short code for Swift 3:

UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName : UIColor.white]

or

navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName :UIColor.white]

How to Query Database Name in Oracle SQL Developer?

DESCRIBE DATABASE NAME; you need to specify the name of the database and the results will include the data type of each attribute.

proper name for python * operator?

For a colloquial name there is "splatting".

For arguments (list type) you use single * and for keyword arguments (dictionary type) you use double **.

Both * and ** is sometimes referred to as "splatting".

See for reference of this name being used: https://stackoverflow.com/a/47875892/14305096

How to change navigation bar color in iOS 7 or 6?

In iOS7, if your navigation controller is contained in tab bar, splitview or some other container, then for globally changing navigationbar appearance use following method ::

[[UINavigationBar appearanceWhenContainedIn:[UITabBarController class],nil] setBarTintColor:[UIColor blueColor]];

How to execute AngularJS controller function on page load?

I had the same problem and only this solution worked for me (it runs a function after a complete DOM has been loaded). I use this for scroll to anchor after page has been loaded:

angular.element(window.document.body).ready(function () {

                        // Your function that runs after all DOM is loaded

                    });

How do I wait for an asynchronously dispatched block to finish?

dispatch_semaphore_t sema = dispatch_semaphore_create(0);
[object blockToExecute:^{
    // ... your code to execute
    dispatch_semaphore_signal(sema);
}];

while (dispatch_semaphore_wait(semaphore, DISPATCH_TIME_NOW)) {
    [[NSRunLoop currentRunLoop]
        runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0]];
}

This did it for me.

sqlplus statement from command line

Just be aware that on Unix/Linux your username/password can be seen by anyone that can run "ps -ef" command if you place it directly on the command line . Could be a big security issue (or turn into a big security issue).

I usually recommend creating a file or using here document so you can protect the username/password from being viewed with "ps -ef" command in Unix/Linux. If the username/password is contained in a script file or sql file you can protect using appropriate user/group read permissions. Then you can keep the user/pass inside the file like this in a shell script:

sqlplus -s /nolog <<EOF
connect user/pass
select blah;
quit
EOF

Oracle - how to remove white spaces?

This sounds like an output formatting issue? If using SQL Plus, use the COLUMN command like this (assuming you want a maximum display width of 20 chars for each):

column a format a20
column b format a20
select a, b from mytable;

How to loop over files in directory and change path and add suffix to filename

A couple of notes first: when you use Data/data1.txt as an argument, should it really be /Data/data1.txt (with a leading slash)? Also, should the outer loop scan only for .txt files, or all files in /Data? Here's an answer, assuming /Data/data1.txt and .txt files only:

#!/bin/bash
for filename in /Data/*.txt; do
    for ((i=0; i<=3; i++)); do
        ./MyProgram.exe "$filename" "Logs/$(basename "$filename" .txt)_Log$i.txt"
    done
done

Notes:

  • /Data/*.txt expands to the paths of the text files in /Data (including the /Data/ part)
  • $( ... ) runs a shell command and inserts its output at that point in the command line
  • basename somepath .txt outputs the base part of somepath, with .txt removed from the end (e.g. /Data/file.txt -> file)

If you needed to run MyProgram with Data/file.txt instead of /Data/file.txt, use "${filename#/}" to remove the leading slash. On the other hand, if it's really Data not /Data you want to scan, just use for filename in Data/*.txt.

How to change a DIV padding without affecting the width/height ?

Solution is to wrap your padded div, with fixed width outer div

HTML

<div class="outer">
    <div class="inner">

        <!-- your content -->

    </div><!-- end .inner -->
</div><!-- end .outer -->

CSS

.outer, .inner {
    display: block;
}

.outer {
    /* specify fixed width */
    width: 300px;
    padding: 0;
}

.inner {
    /* specify padding, can be changed while remaining fixed width of .outer */
    padding: 5px;
}

Issue in installing php7.2-mcrypt

I followed below steps to install mcrypt for PHP7.2 using PECL.

  1. Install PECL

apt-get install php-pecl

  1. Before installing MCRYPT you must install libmcrypt

apt-get install libmcrypt-dev libreadline-dev

  1. Install MCRYPT 1.0.1 using PECL

pecl install mcrypt-1.0.1

  1. After the successful installation

You should add "extension=mcrypt.so" to php.ini

Please comment below if you need any assistance. :-)

IMPORTANT !

According to php.net reference many (all) mcrypt functions have been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged.

C# refresh DataGridView when updating or inserted on another form

DataGridView.Refresh and And DataGridView.Update are methods that are inherited from Control. They have to do with redrawing the control which is why new rows don't appear.

My guess is the data retrieval is on the Form_Load. If you want your Button on Form B to retrieve the latest data from the database then that's what you have to do whatever Form_Load is doing.

A nice way to do that is to separate your data retrieval calls into a separate function and call it from both the From Load and Button Click events.

How to return a resultset / cursor from a Oracle PL/SQL anonymous block that executes Dynamic SQL?

You can write a PL/SQL function to return that cursor (or you could put that function in a package if you have more code related to this):

CREATE OR REPLACE FUNCTION get_allitems
  RETURN SYS_REFCURSOR
AS
  my_cursor SYS_REFCURSOR;
BEGIN
  OPEN my_cursor FOR SELECT * FROM allitems;
  RETURN my_cursor;
END get_allitems;

This will return the cursor.

Make sure not to put your SELECT-String into quotes in PL/SQL when possible. Putting it in strings means that it can not be checked at compile time, and that it has to be parsed whenever you use it.


If you really need to use dynamic SQL you can put your query in single quotes:

  OPEN my_cursor FOR 'SELECT * FROM allitems';

This string has to be parsed whenever the function is called, which will usually be slower and hides errors in your query until runtime.

Make sure to use bind-variables where possible to avoid hard parses:

  OPEN my_cursor FOR 'SELECT * FROM allitems WHERE id = :id' USING my_id;

Where does Chrome store cookies?

You can find a solution on SuperUser :

Chrome cookies folder in Windows 7:-

C:\Users\your_username\AppData\Local\Google\Chrome\User Data\Default\
You'll need a program like SQLite Database Browser to read it.

For Mac OS X, the file is located at :-
~/Library/Application Support/Google/Chrome/Default/Cookies

Setting and getting localStorage with jQuery

Use setItem and getItem if you want to write simple strings to localStorage. Also you should be using text() if it's the text you're after as you say, else you will get the full HTML as a string.

Sample using .text()

// get the text
var text = $('#test').text();

// set the item in localStorage
localStorage.setItem('test', text);

// alert the value to check if we got it
alert(localStorage.getItem('test'));

JSFiddle: https://jsfiddle.net/f3zLa3zc/


Storing the HTML itself

// get html
var html = $('#test')[0].outerHTML;

// set localstorage
localStorage.setItem('htmltest', html);

// test if it works
alert(localStorage.getItem('htmltest'));

JSFiddle:
https://jsfiddle.net/psfL82q3/1/


Update on user comment

A user want to update the localStorage when the div's content changes. Since it's unclear how the div contents changes (ajax, other method?) contenteditable and blur() is used to change the contents of the div and overwrite the old localStorage entry.

// get the text
var text = $('#test').text();

// set the item in localStorage
localStorage.setItem('test', text);

// bind text to 'blur' event for div
$('#test').on('blur', function() {

    // check the new text
    var newText = $(this).text();

    // overwrite the old text
    localStorage.setItem('test', newText);

    // test if it works
    alert(localStorage.getItem('test'));

});

If we were using ajax we would instead trigger the function it via the function responsible for updating the contents.

JSFiddle:
https://jsfiddle.net/g1b8m1fc/

How to run a makefile in Windows?

Firstly, add path of visual studio common tools (c:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Tools) into the system path. To learn how to add a path into system path, please check this website: http://www.computerhope.com/issues/ch000549.htm. You just need to this once.

After that, whenever you need, open a command line and execute vsvars32.bat to add all required visual studio tools' paths into the system path.

Then, you can call nmake -f makefile.mak

PS: Path of visual studio common tools might be different in your system. Please change it accordingly.

Datatype for storing ip address in SQL Server

The technically correct way to store IPv4 is binary(4), since that is what it actually is (no, not even an INT32/INT(4), the numeric textual form that we all know and love (255.255.255.255) being just the display conversion of its binary content).

If you do it this way, you will want functions to convert to and from the textual-display format:

Here's how to convert the textual display form to binary:

CREATE FUNCTION dbo.fnBinaryIPv4(@ip AS VARCHAR(15)) RETURNS BINARY(4)
AS
BEGIN
    DECLARE @bin AS BINARY(4)

    SELECT @bin = CAST( CAST( PARSENAME( @ip, 4 ) AS INTEGER) AS BINARY(1))
                + CAST( CAST( PARSENAME( @ip, 3 ) AS INTEGER) AS BINARY(1))
                + CAST( CAST( PARSENAME( @ip, 2 ) AS INTEGER) AS BINARY(1))
                + CAST( CAST( PARSENAME( @ip, 1 ) AS INTEGER) AS BINARY(1))

    RETURN @bin
END
go

And here's how to convert the binary back to the textual display form:

CREATE FUNCTION dbo.fnDisplayIPv4(@ip AS BINARY(4)) RETURNS VARCHAR(15)
AS
BEGIN
    DECLARE @str AS VARCHAR(15) 

    SELECT @str = CAST( CAST( SUBSTRING( @ip, 1, 1) AS INTEGER) AS VARCHAR(3) ) + '.'
                + CAST( CAST( SUBSTRING( @ip, 2, 1) AS INTEGER) AS VARCHAR(3) ) + '.'
                + CAST( CAST( SUBSTRING( @ip, 3, 1) AS INTEGER) AS VARCHAR(3) ) + '.'
                + CAST( CAST( SUBSTRING( @ip, 4, 1) AS INTEGER) AS VARCHAR(3) );

    RETURN @str
END;
go

Here's a demo of how to use them:

SELECT dbo.fnBinaryIPv4('192.65.68.201')
--should return 0xC04144C9
go

SELECT dbo.fnDisplayIPv4( 0xC04144C9 )
-- should return '192.65.68.201'
go

Finally, when doing lookups and compares, always use the binary form if you want to be able to leverage your indexes.


UPDATE:

I wanted to add that one way to address the inherent performance problems of scalar UDFs in SQL Server, but still retain the code-reuse of a function is to use an iTVF (inline table-valued function) instead. Here's how the first function above (string to binary) can be re-written as an iTVF:

CREATE FUNCTION dbo.itvfBinaryIPv4(@ip AS VARCHAR(15)) RETURNS TABLE
AS RETURN (
    SELECT CAST(
               CAST( CAST( PARSENAME( @ip, 4 ) AS INTEGER) AS BINARY(1))
            +  CAST( CAST( PARSENAME( @ip, 3 ) AS INTEGER) AS BINARY(1))
            +  CAST( CAST( PARSENAME( @ip, 2 ) AS INTEGER) AS BINARY(1))
            +  CAST( CAST( PARSENAME( @ip, 1 ) AS INTEGER) AS BINARY(1))
                AS BINARY(4)) As bin
        )
go

Here's it in the example:

SELECT bin FROM dbo.fnBinaryIPv4('192.65.68.201')
--should return 0xC04144C9
go

And here's how you would use it in an INSERT

INSERT INTo myIpTable
SELECT {other_column_values,...},
       (SELECT bin FROM dbo.itvfBinaryIPv4('192.65.68.201'))

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

The top answer here was a work around from an Angular problem which no longer exists (at least in versions >1.2.16 and "probably earlier") as @zumalifeguard has mentioned. But I'm left reading all these answers without an actual solution.

It seems to me that the answer now should be

  • use $broadcast from the $rootScope
  • listen using $on from the local $scope that needs to know about the event

So to publish

// EXAMPLE PUBLISHER
angular.module('test').controller('CtrlPublish', ['$rootScope', '$scope',
function ($rootScope, $scope) {

  $rootScope.$broadcast('topic', 'message');

}]);

And subscribe

// EXAMPLE SUBSCRIBER
angular.module('test').controller('ctrlSubscribe', ['$scope',
function ($scope) {

  $scope.$on('topic', function (event, arg) { 
    $scope.receiver = 'got your ' + arg;
  });

}]);

Plunkers

If you register the listener on the local $scope, it will be destroyed automatically by $destroy itself when the associated controller is removed.

How to store Emoji Character in MySQL Database

If you are inserting using PHP, and you have followed the various ALTER database and ALTER table options above, make sure your php connection's charset is utf8mb4.

Example of connection string:

$this->pdo = new PDO("mysql:host=$ip;port=$port;dbname=$db;charset=utf8mb4", etc etc

Notice the "charset" is utf8mb4, not just utf8!

Bootstrap 3 modal vertical position center

Consider using the bootstrap-modal plugin found here - https://github.com/jschr/bootstrap-modal

The plugin will center all of your modals

css - position div to bottom of containing div

.outside {
    width: 200px;
    height: 200px;
    background-color: #EEE; /*to make it visible*/
}

Needs to be

.outside {
    position: relative;
    width: 200px;
    height: 200px;
    background-color: #EEE; /*to make it visible*/
}

Absolute positioning looks for the nearest relatively positioned parent within the DOM, if one isn't defined it will use the body.

Prevent content from expanding grid items

The previous answer is pretty good, but I also wanted to mention that there is a fixed layout equivalent for grids, you just need to write minmax(0, 1fr) instead of 1fr as your track size.

Should you choose the MONEY or DECIMAL(x,y) datatypes in SQL Server?

Everything is dangerous if you don't know what you are doing

Even high-precision decimal types can't save the day:

declare @num1 numeric(38,22)
declare @num2 numeric(38,22)
set @num1 = .0000006
set @num2 = 1.0
select @num1 * @num2 * 1000000

1.000000 <- Should be 0.6000000


The money types are integers

The text representations of smallmoney and decimal(10,4) may look alike, but that doesn't make them interchangeable. Do you cringe when you see dates stored as varchar(10)? This is the same thing.

Behind the scenes, money/smallmoney are just a bigint/int The decimal point in the text representation of money is visual fluff, just like the dashes in a yyyy-mm-dd date. SQL doesn't actually store those internally.

Regarding decimal vs money, pick whatever is appropriate for your needs. The money types exist because storing accounting values as integer multiples of 1/10000th of unit is very common. Also, if you are dealing with actual money and calculations beyond simple addition and subtraction, you shouldn't be doing that at the database level! Do it at the application level with a library that supports Banker's Rounding (IEEE 754)

"Sub or Function not defined" when trying to run a VBA script in Outlook

I had a similar situation with this issue. In this case it would have looked like this

Sub Test()
   MsqBox ("Hello world")
End Sub

The problem was, that I had a lot more code there and couldn't recognize, that there was a misspelling in "MsqBox" (q instead of g) and therefore I had an error, it was really misleading, but since you can get on this error like that, maybe someone else will notice that it was cause by a misspelling like this...

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

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

MySQL Check if username and password matches in Database

//set vars
$user = $_POST['user'];
$pass = md5($_POST['pass']);

if ($user&&$pass) 
{
//connect to db
$connect = mysql_connect("$server","$username","$password") or die("not connecting");
mysql_select_db("users") or die("no db :'(");
$query = mysql_query("SELECT * FROM $tablename WHERE username='$user'");

$numrows = mysql_num_rows($query);


if ($numrows!=0)
{
//while loop
  while ($row = mysql_fetch_assoc($query))
  {
    $dbusername = $row['username'];
    $dbpassword = $row['password'];
  }
  else
      die("incorrect username/password!");
}
else
  echo "user does not exist!";
} 
else
    die("please enter a username and password!");

Error # 1045 - Cannot Log in to MySQL server -> phpmyadmin

When you change your passwords in the security tab, there are two sections, one above and one below. I think the common mistake here is that others try to log-in with the account they have set "below" the one used for htaccess, whereas they should log in to the password they set on the above section. That's how I fixed mine.

What's the best UML diagramming tool?

If you want to model at diagram level and also have a clean metamodel the new Omondo build allows live synchronization between MOF and UML Diagrams. Just amazing to see my diagram and the xmi live synchronized each time I change something in my diagram and the model is changed. What is most incredible is that the model is also the metamodel and the MOF because everything is lived synchronized. Very powerful new concept for my point of view.

I also like Java code annotation and JPA support in the class diagram and in the model. I don't know any other tool having these 2 incredible features !!

What does file:///android_asset/www/index.html mean?

file:/// is a URI (Uniform Resource Identifier) that simply distinguishes from the standard URI that we all know of too well - http://.

It does imply an absolute path name pointing to the root directory in any environment, but in the context of Android, it's a convention to tell the Android run-time to say "Here, the directory www has a file called index.html located in the assets folder in the root of the project".

That is how assets are loaded at runtime, for example, a WebView widget would know exactly where to load the embedded resource file by specifying the file:/// URI.

Consider the code example:

WebView webViewer = (WebView) findViewById(R.id.webViewer);
webView.loadUrl("file:///android_asset/www/index.html");

A very easy mistake to make here is this, some would infer it to as file:///android_assets, notice the plural of assets in the URI and wonder why the embedded resource is not working!

Create a directory if it does not exist and then create the files in that directory as well

Trying to make this as short and simple as possible. Creates directory if it doesn't exist, and then returns the desired file:

/** Creates parent directories if necessary. Then returns file */
private static File fileWithDirectoryAssurance(String directory, String filename) {
    File dir = new File(directory);
    if (!dir.exists()) dir.mkdirs();
    return new File(directory + "/" + filename);
}

Subtract days, months, years from a date in JavaScript

This does not answer the question fully, but for anyone who is able to calculate the number of days by which they would like to offset an initial date then the following method will work:

myDate.setUTCDate(myDate.getUTCDate() + offsetDays);

offsetDays can be positive or negative and the result will be correct for any given initial date with any given offset.

Count the number of occurrences of a string in a VARCHAR field?

SELECT 
id,
jsondata,    
ROUND (   
    (
        LENGTH(jsondata)
        - LENGTH( REPLACE ( jsondata, "sonal", "") ) 
    ) / LENGTH("sonal")        
)
+
ROUND (   
    (
        LENGTH(jsondata)
        - LENGTH( REPLACE ( jsondata, "khunt", "") ) 
    ) / LENGTH("khunt")        
)
AS count1    FROM test ORDER BY count1 DESC LIMIT 0, 2

Thanks Yannis, your solution worked for me and here I'm sharing same solution for multiple keywords with order and limit.

Android Studio AVD - Emulator: Process finished with exit code 1

Check android studio event log as it could be low storage issue.

emulator: ERROR: Not enough disk space to run AVD 'Nexus_5_API_21'. Exiting...

How to show the "Are you sure you want to navigate away from this page?" when changes committed?

When the user starts making changes to the form, a boolean flag will be set. If the user then tries to navigate away from the page, you check that flag in the window.onunload event. If the flag is set, you show the message by returning it as a string. Returning the message as a string will popup a confirmation dialog containing your message.

If you are using ajax to commit the changes, you can set the flag to false after the changes have been committed (i.e. in the ajax success event).

Android DialogFragment vs Dialog

Yes, use DialogFragment and in onCreateDialog you can simply use an AlertDialog builder anyway to create a simple AlertDialog with Yes/No confirmation buttons. Not very much code at all.

With regards handling events in your fragment there would be various ways of doing it but I simply define a message Handler in my Fragment, pass it into the DialogFragment via its constructor and then pass messages back to my fragment's handler as approprirate on the various click events. Again various ways of doing that but the following works for me.

In the dialog hold a message and instantiate it in the constructor:

private Message okMessage;
...
okMessage = handler.obtainMessage(MY_MSG_WHAT, MY_MSG_OK);

Implement the onClickListener in your dialog and then call the handler as appropriate:

public void onClick(.....
    if (which == DialogInterface.BUTTON_POSITIVE) {
        final Message toSend = Message.obtain(okMessage);
        toSend.sendToTarget();
    }
 }

Edit

And as Message is parcelable you can save it out in onSaveInstanceState and restore it

outState.putParcelable("okMessage", okMessage);

Then in onCreate

if (savedInstanceState != null) {
    okMessage = savedInstanceState.getParcelable("okMessage");
}

How can I create basic timestamps or dates? (Python 3.4)

Ultimately you want to review the datetime documentation and become familiar with the formatting variables, but here are some examples to get you started:

import datetime

print('Timestamp: {:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now()))
print('Timestamp: {:%Y-%b-%d %H:%M:%S}'.format(datetime.datetime.now()))
print('Date now: %s' % datetime.datetime.now())
print('Date today: %s' % datetime.date.today())

today = datetime.date.today()
print("Today's date is {:%b, %d %Y}".format(today))

schedule = '{:%b, %d %Y}'.format(today) + ' - 6 PM to 10 PM Pacific'
schedule2 = '{:%B, %d %Y}'.format(today) + ' - 1 PM to 6 PM Central'
print('Maintenance: %s' % schedule)
print('Maintenance: %s' % schedule2)

The output:

Timestamp: 2014-10-18 21:31:12

Timestamp: 2014-Oct-18 21:31:12

Date now: 2014-10-18 21:31:12.318340

Date today: 2014-10-18

Today's date is Oct, 18 2014

Maintenance: Oct, 18 2014 - 6 PM to 10 PM Pacific

Maintenance: October, 18 2014 - 1 PM to 6 PM Central

Reference link: https://docs.python.org/3.4/library/datetime.html#strftime-strptime-behavior

MySQl Error #1064

At first you need to add semi colon (;) after quantity INT NOT NULL) then remove ** from ,genre,quantity)**. to insert a value with numeric data type like int, decimal, float, etc you don't need to add single quote.

What is a stored procedure?

Stored procedures in SQL Server can accept input parameters and return multiple values of output parameters; in SQL Server, stored procedures program statements to perform operations in the database and return a status value to a calling procedure or batch.

The benefits of using stored procedures in SQL Server

They allow modular programming. They allow faster execution. They can reduce network traffic. They can be used as a security mechanism.

Here is an example of a stored procedure that takes a parameter, executes a query and return a result. Specifically, the stored procedure accepts the BusinessEntityID as a parameter and uses this to match the primary key of the HumanResources.Employee table to return the requested employee.

> create procedure HumanResources.uspFindEmployee    `*<<<---Store procedure name`*
@businessEntityID                                     `<<<----parameter`
as
begin
SET NOCOUNT ON;
Select businessEntityId,              <<<----select statement to return one employee row
NationalIdNumber,
LoginID,
JobTitle,
HireData,
From HumanResources.Employee
where businessEntityId =@businessEntityId     <<<---parameter used as criteria
end

I learned this from essential.com...it is very useful.

Python element-wise tuple operations like sum

Yes. But you can't redefine built-in types. You have to subclass them:

class MyTuple(tuple):
    def __add__(self, other):
         if len(self) != len(other):
             raise ValueError("tuple lengths don't match")
         return MyTuple(x + y for (x, y) in zip(self, other))

jQuery: Check if button is clicked

$('#btn1, #btn2').click(function() {
    let clickedButton = $(this).attr('id');
    console.log(clickedButton);
});

CSS force new line

Use the display property

a{
    display: block;
}

This will make the link to display in new line

If you want to remove list styling, use

li{
    list-style: none;
}

Last executed queries for a specific database

This works for me to find queries on any database in the instance. I'm sysadmin on the instance (check your privileges):

SELECT deqs.last_execution_time AS [Time], dest.text AS [Query], dest.*
FROM sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
WHERE dest.dbid = DB_ID('msdb')
ORDER BY deqs.last_execution_time DESC

This is the same answer that Aaron Bertrand provided but it wasn't placed in an answer.

Trying to git pull with error: cannot open .git/FETCH_HEAD: Permission denied

Simply go to your root folder and run this command:

chmod a+rw .git/FETCH_HEAD

removeEventListener on anonymous functions in JavaScript

A version of Otto Nascarella's solution that works in strict mode is:

button.addEventListener('click', function handler() {
      ///this will execute only once
      alert('only once!');
      this.removeEventListener('click', handler);
});

Nested Git repositories?

Place your third party libraries in a separate repository and use submodules to associate them with the main project. Here is a walk-through:

http://git-scm.com/book/en/Git-Tools-Submodules

In deciding how to segment a repo I would usually decide based on how often I would modify them. If it is a third-party library and only changes you are making to it is upgrading to a newer version then you should definitely separate it from the main project.

How to get current route in react-router 2.0.0-rc5

In App.js add the below code and try

window.location.pathname

How does += (plus equal) work?

that's just a shorthand notation in most languages.which means that

x=x+1;

we can do the same operation for x-=1,x*=1,x/=1; which means

> x=x-1; x=x*1; x=x/1;

How do I verify that a string only contains letters, numbers, underscores and dashes?

Here's something based on Jerub's "naive approach" (naive being his words, not mine!):

import string
ALLOWED = frozenset(string.ascii_letters + string.digits + '_' + '-')

def check(mystring):
    return all(c in ALLOWED for c in mystring)

If ALLOWED was a string then I think c in ALLOWED would involve iterating over each character in the string until it found a match or reached the end. Which, to quote Joel Spolsky, is something of a Shlemiel the Painter algorithm.

But testing for existence in a set should be more efficient, or at least less dependent on the number of allowed characters. Certainly this approach is a little bit faster on my machine. It's clear and I think it performs plenty well enough for most cases (on my slow machine I can validate tens of thousands of short-ish strings in a fraction of a second). I like it.

ACTUALLY on my machine a regexp works out several times faster, and is just as simple as this (arguably simpler). So that probably is the best way forward.

VLook-Up Match first 3 characters of one column with another column

=IF(ISNUMBER(SEARCH(LEFT(H2,3),I2)),"YES","NO")))

Difference between 3NF and BCNF in simple terms (must be able to explain to an 8-year old)

The difference between BCNF and 3NF

Using the BCNF definition

If and only if for every one of its dependencies X ? Y, at least one of the following conditions hold:

  • X ? Y is a trivial functional dependency (Y ? X), or
  • X is a super key for schema R

and the 3NF definition

If and only if, for each of its functional dependencies X ? A, at least one of the following conditions holds:

  • X contains A (that is, X ? A is trivial functional dependency), or
  • X is a superkey, or
  • Every element of A-X, the set difference between A and X, is a prime attribute (i.e., each attribute in A-X is contained in some candidate key)

We see the following difference, in simple terms:

  • In BCNF: Every partial key (prime attribute) can only depend on a superkey,

whereas

  • In 3NF: A partial key (prime attribute) can also depend on an attribute that is not a superkey (i.e. another partial key/prime attribute or even a non-prime attribute).

Where

  1. A prime attribute is an attribute found in a candidate key, and
  2. A candidate key is a minimal superkey for that relation, and
  3. A superkey is a set of attributes of a relation variable for which it holds that in all relations assigned to that variable, there are no two distinct tuples (rows) that have the same values for the attributes in this set.Equivalently a superkey can also be defined as a set of attributes of a relation schema upon which all attributes of the schema are functionally dependent. (A superkey always contains a candidate key/a candidate key is always a subset of a superkey. You can add any attribute in a relation to obtain one of the superkeys.)

That is, no partial subset (any non trivial subset except the full set) of a candidate key can be functionally dependent on anything other than a superkey.

A table/relation not in BCNF is subject to anomalies such as the update anomalies mentioned in the pizza example by another user. Unfortunately,

  • BNCF cannot always be obtained, while
  • 3NF can always be obtained.

3NF Versus BCNF Example

An example of the difference can currently be found at "3NF table not meeting BCNF (Boyce–Codd normal form)" on Wikipedia, where the following table meets 3NF but not BCNF because "Tennis Court" (a partial key/prime attribute) depends on "Rate Type" (a partial key/prime attribute that is not a superkey), which is a dependency we could determine by asking the clients of the database, the tennis club:

Today's Tennis Court Bookings (3NF, not BCNF)

Court   Start Time  End Time    Rate Type
------- ----------  --------    ---------
1       09:30       10:30       SAVER
1       11:00       12:00       SAVER
1       14:00       15:30       STANDARD
2       10:00       11:30       PREMIUM-B
2       11:30       13:30       PREMIUM-B
2       15:00       16:30       PREMIUM-A

The table's superkeys are:

S1 = {Court, Start Time}
S2 = {Court, End Time}
S3 = {Rate Type, Start Time}
S4 = {Rate Type, End Time}
S5 = {Court, Start Time, End Time}
S6 = {Rate Type, Start Time, End Time}
S7 = {Court, Rate Type, Start Time}
S8 = {Court, Rate Type, End Time}
ST = {Court, Rate Type, Start Time, End Time}, the trivial superkey

The 3NF problem: The partial key/prime attribute "Court" is dependent on something other than a superkey. Instead, it is dependent on the partial key/prime attribute "Rate Type". This means that the user must manually change the rate type if we upgrade a court, or manually change the court if wanting to apply a rate change.

  • But what if the user upgrades the court but does not remember to increase the rate? Or what if the wrong rate type is applied to a court?

(In technical terms, we cannot guarantee that the "Rate Type" -> "Court" functional dependency will not be violated.)

The BCNF solution: If we want to place the above table in BCNF we can decompose the given relation/table into the following two relations/tables (assuming we know that the rate type is dependent on only the court and membership status, which we could discover by asking the clients of our database, the owners of the tennis club):

Rate Types (BCNF and the weaker 3NF, which is implied by BCNF)

Rate Type   Court   Member Flag
---------   -----   -----------
SAVER       1       Yes
STANDARD    1       No
PREMIUM-A   2       Yes
PREMIUM-B   2       No

Today's Tennis Court Bookings (BCNF and the weaker 3NF, which is implied by BCNF)

Member Flag     Court     Start Time   End Time
-----------     -----     ----------   --------
Yes             1         09:30        10:30
Yes             1         11:00        12:00
No              1         14:00        15:30
No              2         10:00        11:30
No              2         11:30        13:30
Yes             2         15:00        16:30

Problem Solved: Now if we upgrade the court we can guarantee the rate type will reflect this change, and we cannot charge the wrong price for a court.

(In technical terms, we can guarantee that the functional dependency "Rate Type" -> "Court" will not be violated.)

Best way to update data with a RecyclerView adapter

DiffUtil can the best choice for updating the data in the RecyclerView Adapter which you can find in the android framework. DiffUtil is a utility class that can calculate the difference between two lists and output a list of update operations that converts the first list into the second one.

Most of the time our list changes completely and we set new list to RecyclerView Adapter. And we call notifyDataSetChanged to update adapter. NotifyDataSetChanged is costly. DiffUtil class solves that problem now. It does its job perfectly!

How do I compile the asm generated by GCC?

Yes, gcc can also compile assembly source code. Alternatively, you can invoke as, which is the assembler. (gcc is just a "driver" program that uses heuristics to call C compiler, C++ compiler, assembler, linker, etc..)

What is an unhandled promise rejection?

In my case was Promise with no reject neither resolve, because my Promise function threw an exception. This mistake cause UnhandledPromiseRejectionWarning message.

When do you use varargs in Java?

I use varargs frequently for constructors that can take some sort of filter object. For example, a large part of our system based on Hadoop is based on a Mapper that handles serialization and deserialization of items to JSON, and applies a number of processors that each take an item of content and either modify and return it, or return null to reject.

How to get char from string by index?

Another recommended exersice for understanding lists and indexes:

L = ['a', 'b', 'c']
for index, item in enumerate(L):
    print index + '\n' + item

0
a
1
b
2
c 

Convert from List into IEnumerable format

You can use the extension method AsEnumerable in Assembly System.Core and System.Linq namespace :

List<Book> list = new List<Book>();
return list.AsEnumerable();

This will, as said on this MSDN link change the type of the List in compile-time. This will give you the benefits also to only enumerate your collection we needed (see MSDN example for this).

Convert character to ASCII numeric value in java

Or you can use Stream API for 1 character or a String starting in Java 1.8:

public class ASCIIConversion {
    public static void main(String[] args) {
        String text = "adskjfhqewrilfgherqifvehwqfjklsdbnf";
        text.chars()
                .forEach(System.out::println);
    }
}

MySQL Database won't start in XAMPP Manager-osx

I am running XAMPP 5.6.3-0 for OS X Yosemite 10.10.2 and ran into the same issue twice, the first time was with Mavericks. With a bunch of different solutions to the issue with MySQL Database not starting using Manager App I wanted to confirm what had worked for me. The workaround that always worked and forced MySQL to start was by opening Terminal and using: sudo /Applications/XAMPP/xamppfiles/bin/mysql.server start I had the Manager App open and started ProFTPD and Apache and then ran the sudo command.

The other suggestion by wishap that worked was to locate /Applications/XAMPP/xamppfiles/etc/my.cnf file and change the permissions for "everyone" to Read only.

The other problem I had that seems to be another issue with many solutions is the problem after everything is started then entering localhost which brings me to the xampp splash screen and then nothing. The only thing that worked for me, to at the very least, to access the phpMyAdmin page is by entering localhost/phpmyadmin

I hope this helps others reading through a bunch of threads for an answer.

Regards, Erik

Artisan migrate could not find driver

We have solved the same error by following the below steps.

linux command for this type of error occurred then, first of all, check your php.ini file

If your php.ini file exists then in configuration file simply uncomment the extension:

;extension=php_pdo_mysql.dll 

Else follow below steps

step1:php -v

step2: Install php mysql extension

php 7.0 sudo apt-get install php7.0-mysql

php 7.1 sudo apt-get install php7.1-mysql

php 7.2 sudo apt-get install php7.2-mysql

php 7.3 sudo apt-get install php7.3-mysql

step3: service apache2 restart

step4: php artisan migrate

Unsupported major.minor version 52.0 when rendering in Android Studio

I also got the same error message of 'Unsupported major.minor version 52.0' when running ./gradlew makeJar to create a jar library by Android Studio 2.2.3.

After moving down the version of gradle plugin in build.gradle from 2.2.2 to 2.1.3, the error message disappeared and all worked well. classpath 'com.android.tools.build:gradle:2.1.3'

I don't know how the higer version of gradle plugin caused the error, but this did the trick for me. please let me know how this worked if you know the answer, thanks

jQuery Button.click() event is triggered twice

Strange behaviour which I was experienced also. So for me "return false" did the trick.

        $( '#selector' ).on( 'click', function() {
            //code
            return false;
        });

How to measure time elapsed on Javascript?

The Date documentation states that :

The JavaScript date is based on a time value that is milliseconds since midnight January 1, 1970, UTC

Click on start button then on end button. It will show you the number of seconds between the 2 clicks.

The milliseconds diff is in variable timeDiff. Play with it to find seconds/minutes/hours/ or what you need

_x000D_
_x000D_
var startTime, endTime;_x000D_
_x000D_
function start() {_x000D_
  startTime = new Date();_x000D_
};_x000D_
_x000D_
function end() {_x000D_
  endTime = new Date();_x000D_
  var timeDiff = endTime - startTime; //in ms_x000D_
  // strip the ms_x000D_
  timeDiff /= 1000;_x000D_
_x000D_
  // get seconds _x000D_
  var seconds = Math.round(timeDiff);_x000D_
  console.log(seconds + " seconds");_x000D_
}
_x000D_
<button onclick="start()">Start</button>_x000D_
_x000D_
<button onclick="end()">End</button>
_x000D_
_x000D_
_x000D_

OR another way of doing it for modern browser

Using performance.now() which returns a value representing the time elapsed since the time origin. This value is a double with microseconds in the fractional.

The time origin is a standard time which is considered to be the beginning of the current document's lifetime.

_x000D_
_x000D_
var startTime, endTime;_x000D_
_x000D_
function start() {_x000D_
  startTime = performance.now();_x000D_
};_x000D_
_x000D_
function end() {_x000D_
  endTime = performance.now();_x000D_
  var timeDiff = endTime - startTime; //in ms _x000D_
  // strip the ms _x000D_
  timeDiff /= 1000; _x000D_
  _x000D_
  // get seconds _x000D_
  var seconds = Math.round(timeDiff);_x000D_
  console.log(seconds + " seconds");_x000D_
}
_x000D_
<button onclick="start()">Start</button>_x000D_
<button onclick="end()">End</button>
_x000D_
_x000D_
_x000D_

How to attach a process in gdb

Try one of these:

gdb -p 12271
gdb /path/to/exe 12271

gdb /path/to/exe
(gdb) attach 12271

What are some great online database modeling tools?

I've used DBDesigner before. It is an open source tool. You might check that out. Not sure if it fits your needs.

Best of luck!

Trigger insert old values- values that was updated

In your trigger, you have two pseudo-tables available, Inserted and Deleted, which contain those values.

In the case of an UPDATE, the Deleted table will contain the old values, while the Inserted table contains the new values.

So if you want to log the ID, OldValue, NewValue in your trigger, you'd need to write something like:

CREATE TRIGGER trgEmployeeUpdate
ON dbo.Employees AFTER UPDATE
AS 
   INSERT INTO dbo.LogTable(ID, OldValue, NewValue)
      SELECT i.ID, d.Name, i.Name
      FROM Inserted i
      INNER JOIN Deleted d ON i.ID = d.ID

Basically, you join the Inserted and Deleted pseudo-tables, grab the ID (which is the same, I presume, in both cases), the old value from the Deleted table, the new value from the Inserted table, and you store everything in the LogTable

align 3 images in same row with equal spaces?

This should be your answer

<div align="center">
 <img src="@Url.Content("~/images/image3.bmp")" alt="" align="right" style="float:right"/>
 <img src="@Url.Content("~/images/image1.bmp")" alt="" align="left" style="float:left" />
 <div id="content" align="center"> 
     <img src="@Url.Content("~/images/image2.bmp")" alt="" align="center" />
 </div>
 </div>

How to write log to file

Building on Allison and Deepak's answer, I started using logrus and really like it:

var log = logrus.New()

func init() {

    // log to console and file
    f, err := os.OpenFile("crawler.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
    if err != nil {
        log.Fatalf("error opening file: %v", err)
    }
    wrt := io.MultiWriter(os.Stdout, f)

    log.SetOutput(wrt)
}

I have a defer f.Close() in the main function

Django 1.7 - "No migrations to apply" when run migrate after makemigrations

python manage.py migrate --fake APPNAME zero

This will make your migration to fake. Now you can run the migrate script

python manage.py migrate APPNAME

Tables will be created and you solved your problem.. Cheers!!!

How do you do a deep copy of an object in .NET?

I've seen a few different approaches to this, but I use a generic utility method as such:

public static T DeepClone<T>(this T obj)
{
 using (var ms = new MemoryStream())
 {
   var formatter = new BinaryFormatter();
   formatter.Serialize(ms, obj);
   ms.Position = 0;

   return (T) formatter.Deserialize(ms);
 }
}

Notes:

  • Your class MUST be marked as [Serializable] for this to work.
  • Your source file must include the following code:

    using System.Runtime.Serialization.Formatters.Binary;
    using System.IO;
    

ASP.NET 2.0 - How to use app_offline.htm

Note that this behaves the same on IIS 6 and 7.x, and .NET 2, 3, and 4.x.

Also note that when app_offline.htm is present, IIS will return this http status code:

HTTP/1.1 503 Service Unavailable

This is all by design. This allows your load balancer (or whatever) to see that the server is off line.

What is the difference between <jsp:include page = ... > and <%@ include file = ... >?

One is a static import (<%=@ include...>"), the other is a dynamic one (jsp:include). It will affect for example the path you gonna have to specify for your included file. A little research on Google will tell you more.

Is it possible to decompile a compiled .pyc file into a .py file?

Yes, it is possible.

There is a perfect open-source Python (.PYC) decompiler, called Decompyle++ https://github.com/zrax/pycdc/

Decompyle++ aims to translate compiled Python byte-code back into valid and human-readable Python source code. While other projects have achieved this with varied success, Decompyle++ is unique in that it seeks to support byte-code from any version of Python.

How to use pip with Python 3.x alongside Python 2.x

First, install Python 3 pip using:

sudo apt-get install python3-pip

Then, to use Python 3 pip use:

pip3 install <module-name>

For Python 2 pip use:

pip install <module-name>

Creating a chart in Excel that ignores #N/A or blank cells

Select the labels above the bar. Format Data Labels. Instead of selecting "VALUE" (unclick). SELECT Value from cells. Select the value. Use the following statement: if(cellvalue="","",cellvalue) where cellvalue is what ever the calculation is in the cell.

Equivalent of String.format in jQuery

The source code for ASP.NET AJAX is available for your reference, so you can pick through it and include the parts you want to continue using into a separate JS file. Or, you can port them to jQuery.

Here is the format function...

String.format = function() {
  var s = arguments[0];
  for (var i = 0; i < arguments.length - 1; i++) {       
    var reg = new RegExp("\\{" + i + "\\}", "gm");             
    s = s.replace(reg, arguments[i + 1]);
  }

  return s;
}

And here are the endsWith and startsWith prototype functions...

String.prototype.endsWith = function (suffix) {
  return (this.substr(this.length - suffix.length) === suffix);
}

String.prototype.startsWith = function(prefix) {
  return (this.substr(0, prefix.length) === prefix);
}

Setting action for back button in navigation controller

I don't believe this is possible, easily. The only way I believe to get around this is to make your own back button arrow image to place up there. It was frustrating for me at first but I see why, for consistency's sake, it was left out.

You can get close (without the arrow) by creating a regular button and hiding the default back button:

self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"Servers" style:UIBarButtonItemStyleDone target:nil action:nil] autorelease];
self.navigationItem.hidesBackButton = YES;

Jquery bind double click and single click separately

This solution works for me

var DELAY = 250, clicks = 0, timer = null;

$(".fc-event").click(function(e) {
    if (timer == null) {
        timer = setTimeout(function() {
           clicks = 0;
            timer = null;
            // single click code
        }, DELAY);
    }

    if(clicks === 1) {
         clearTimeout(timer);
         timer = null;
         clicks = -1;
         // double click code
    }
    clicks++;
});

How can I convert a PFX certificate file for use with Apache on a linux server?

Took some tooling around but this is what I ended up with.

Generated and installed a certificate on IIS7. Exported as PFX from IIS

Convert to pkcs12

openssl pkcs12 -in certificate.pfx -out certificate.cer -nodes

NOTE: While converting PFX to PEM format, openssl will put all the Certificates and Private Key into a single file. You will need to open the file in Text editor and copy each Certificate & Private key(including the BEGIN/END statements) to its own individual text file and save them as certificate.cer, CAcert.cer, privateKey.key respectively.

-----BEGIN PRIVATE KEY-----
Saved as certificate.key
-----END PRIVATE KEY-----

-----BEGIN CERTIFICATE-----
Saved as certificate.crt
-----END CERTIFICATE-----

Added to apache vhost w/ Webmin.

DbEntityValidationException - How can I easily tell what caused the error?

To quickly find a meaningful error message by inspecting the error during debugging:

  • Add a quick watch for:

    ((System.Data.Entity.Validation.DbEntityValidationException)$exception).EntityValidationErrors
    
  • Drill down into EntityValidationErrors like this:

    (collection item e.g. [0]) > ValidationErrors > (collection item e.g. [0]) > ErrorMessage

In Rails, how do you render JSON using a view?

You should be able to do something like this in your respond_to block:

respond_to do |format|
    format.json 
    render :partial => "users/show.json"
end

which will render the template in app/views/users/_show.json.erb.

Elasticsearch query to return all records

The maximum result which will return by elasticSearch is 10000 by providing the size

curl -XGET 'localhost:9200/index/type/_search?scroll=1m' -d '
{
   "size":10000,
   "query" : {
   "match_all" : {}
    }
}'

After that, you have to use Scroll API for getting the result and get the _scroll_id value and put this value in scroll_id

curl -XGET  'localhost:9200/_search/scroll'  -d'
{
   "scroll" : "1m", 
   "scroll_id" : "" 
}'

Centos/Linux setting logrotate to maximum file size for all logs

It specifies the size of the log file to trigger rotation. For example size 50M will trigger a log rotation once the file is 50MB or greater in size. You can use the suffix M for megabytes, k for kilobytes, and G for gigabytes. If no suffix is used, it will take it to mean bytes. You can check the example at the end. There are three directives available size, maxsize, and minsize. According to manpage:

minsize size
              Log  files  are  rotated when they grow bigger than size bytes,
              but not before the additionally specified time interval (daily,
              weekly,  monthly, or yearly).  The related size option is simi-
              lar except that it is mutually exclusive with the time interval
              options,  and  it causes log files to be rotated without regard
              for the last rotation time.  When minsize  is  used,  both  the
              size and timestamp of a log file are considered.

size size
              Log files are rotated only if they grow bigger then size bytes.
              If size is followed by k, the size is assumed to  be  in  kilo-
              bytes.  If the M is used, the size is in megabytes, and if G is
              used, the size is in gigabytes. So size 100,  size  100k,  size
              100M and size 100G are all valid.
maxsize size
              Log files are rotated when they grow bigger than size bytes even before
              the additionally specified time interval (daily, weekly, monthly, 
              or yearly).  The related size option is  similar  except  that  it 
              is mutually exclusive with the time interval options, and it causes
              log files to be rotated without regard for the last rotation time.  
              When maxsize is used, both the size and timestamp of a log file are                  
              considered.

Here is an example:

"/var/log/httpd/access.log" /var/log/httpd/error.log {
           rotate 5
           mail [email protected]
           size 100k
           sharedscripts
           postrotate
               /usr/bin/killall -HUP httpd
           endscript
       }

Here is an explanation for both files /var/log/httpd/access.log and /var/log/httpd/error.log. They are rotated whenever it grows over 100k in size, and the old logs files are mailed (uncompressed) to [email protected] after going through 5 rotations, rather than being removed. The sharedscripts means that the postrotate script will only be run once (after the old logs have been compressed), not once for each log which is rotated. Note that the double quotes around the first filename at the beginning of this section allows logrotate to rotate logs with spaces in the name. Normal shell quoting rules apply, with ,, and \ characters supported.

How can you tell when a layout has been drawn?

When onMeasure is called the view gets its measured width/height. After this, you can call layout.getMeasuredHeight().

In nodeJs is there a way to loop through an array without using array size?

    var count=0;
    let myArray = '{"1":"a","2":"b","3":"c","4":"d"}'
    var data = JSON.parse(myArray);
    for (let key in data) {
      let value =  data[key]; // get the value by key
      console.log("key: , value:", key, value);
      count = count + 1;
    }
   console.log("size:",count);

Why is the console window closing immediately once displayed my output?

The program is closing as soon as it's execution is complete. In this case when you return 0;. This is expected functionality. If you want to see the output then either run it in a terminal manually or set a wait at the end of the program so that it will stay open for a few seconds ( using the threading library ).

How does Facebook disable the browser's integrated Developer Tools?

I located the Facebook's console buster script using Chrome developer tools. Here is the script with minor changes for readability. I have removed the bits that I could not understand:

Object.defineProperty(window, "console", {
    value: console,
    writable: false,
    configurable: false
});

var i = 0;
function showWarningAndThrow() {
    if (!i) {
        setTimeout(function () {
            console.log("%cWarning message", "font: 2em sans-serif; color: yellow; background-color: red;");
        }, 1);
        i = 1;
    }
    throw "Console is disabled";
}

var l, n = {
        set: function (o) {
            l = o;
        },
        get: function () {
            showWarningAndThrow();
            return l;
        }
    };
Object.defineProperty(console, "_commandLineAPI", n);
Object.defineProperty(console, "__commandLineAPI", n);

With this, the console auto-complete fails silently while statements typed in console will fail to execute (the exception will be logged).

References:

android - setting LayoutParams programmatically

Just replace from bottom and add this

tv.setLayoutParams(new ViewGroup.LayoutParams(
    ViewGroup.LayoutParams.WRAP_CONTENT,
    ViewGroup.LayoutParams.WRAP_CONTENT));

before

llview.addView(tv);

Route.get() requires callback functions but got a "object Undefined"

node js and express 4 use this sequences

express = require('express');
var router = express.Router();

module.exports = router;

last line returns this type of error

SVN Repository Search

// Edit: Tool was already mentioned in another answer, so give all credits to Kuryaki.

Just found SupoSE which is a java based command line tool which scans a repository to create an index and afterwards is able to answer certain kinds of queries. We're still evaluating the tool but it looks promising. It's worth to mention that it makes a full index of all revisions including source code files and common office formats.

How to add `style=display:"block"` to an element using jQuery?

There are multiple function to do this work that wrote in bottom based on priority.

Set one or more CSS properties for the set of matched elements.

$("div").css("display", "block")
// Or add multiple CSS properties
$("div").css({
  display: "block",
  color: "red",
  ...
})

Display the matched elements and is roughly equivalent to calling .css("display", "block")

You can display element using .show() instead

$("div").show()

Set one or more attributes for the set of matched elements.

If target element hasn't style attribute, you can use this method to add inline style to element.

$("div").attr("style", "display:block")
// Or add multiple CSS properties
$("div").attr("style", "display:block; color:red")

  • JavaScript

You can add specific CSS property to element using pure javascript, if you don't want to use jQuery.

var div = document.querySelector("div");
// One property
div.style.display = "block";
// Multiple properties
div.style.cssText = "display:block; color:red"; 
// Multiple properties
div.setAttribute("style", "display:block; color:red");

Filter rows which contain a certain string

The answer to the question was already posted by the @latemail in the comments above. You can use regular expressions for the second and subsequent arguments of filter like this:

dplyr::filter(df, !grepl("RTB",TrackingPixel))

Since you have not provided the original data, I will add a toy example using the mtcars data set. Imagine you are only interested in cars produced by Mazda or Toyota.

mtcars$type <- rownames(mtcars)
dplyr::filter(mtcars, grepl('Toyota|Mazda', type))

   mpg cyl  disp  hp drat    wt  qsec vs am gear carb           type
1 21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4      Mazda RX4
2 21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4  Mazda RX4 Wag
3 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1 Toyota Corolla
4 21.5   4 120.1  97 3.70 2.465 20.01  1  0    3    1  Toyota Corona

If you would like to do it the other way round, namely excluding Toyota and Mazda cars, the filter command looks like this:

dplyr::filter(mtcars, !grepl('Toyota|Mazda', type))

Is it possible to specify a different ssh port when using rsync?

when you need to send files through a specific SSH port:

rsync -azP -e "ssh -p PORT_NUMBER" source destination

example

rsync -azP -e "ssh -p 2121" /path/to/files/source user@remoteip:/path/to/files/destination

Item frequency count in Python

freqs = {}
for word in words:
    freqs[word] = freqs.get(word, 0) + 1 # fetch and increment OR initialize

I think this results to the same as Triptych's solution, but without importing collections. Also a bit like Selinap's solution, but more readable imho. Almost identical to Thomas Weigel's solution, but without using Exceptions.

This could be slower than using defaultdict() from the collections library however. Since the value is fetched, incremented and then assigned again. Instead of just incremented. However using += might do just the same internally.

Want to show/hide div based on dropdown box selection

Wrap the code within $(document).ready(function(){...........}); handler , also remove the ; after if

$(document).ready(function(){
    $('#purpose').on('change', function() {
      if ( this.value == '1')
      //.....................^.......
      {
        $("#business").show();
      }
      else
      {
        $("#business").hide();
      }
    });
});

Fiddle Demo

Hashing a dictionary?

Answers from this thread with the highest upvotes didn't work for me as their hashing functions give different results on different machines due to PYTHOPYTHONHASHSEED.

I adjusted all the hints from this thread and came up with a solution that works for me.

import collections
import hashlib
import json


def simplify_object(o):
    if isinstance(o, dict):
        ordered_dict = collections.OrderedDict(sorted(o.items()))
        for k, v in ordered_dict.items():
            v = simplify_object(v)
            ordered_dict[str(k)] = v
        o = ordered_dict
    elif isinstance(o, (list, tuple, set)):
        o = [simplify_object(el) for el in o]
    else:
        o = str(o).strip()
    return o


def make_hash(o):
    o = simplify_object(o)
    bytes_val = json.dumps(o, sort_keys=True, ensure_ascii=True, default=str)
    hash_val = hashlib.sha1(bytes_val.encode()).hexdigest()
    return hash_val