Programs & Examples On #Glteximage2d

Difference between null and empty ("") Java String

"" and null both are different . the first one means as part of string variable declaration the string constant has been created in the string pool and some memory has been assigned for the same.

But when we are declaring it with null then it has just been instantiated jvm , but no memory has been allocated for it. therefore if you are trying to access this object by checking it with "" - blank variable , it can't prevent nullpointerexception . Please find below one use-case.

public class StringCheck {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    String s1 = "siddhartha";
    String s2 = "";
    String s3 = null;

    System.out.println("length s1 ="+s1.length());
    System.out.println("length s2 ="+s2.length());

    //this piece of code will still throw nullpointerexception . 
    if(s3 != ""){
        System.out.println("length s3 ="+s3.length());
    }
}

}

How to find tag with particular text with Beautiful Soup?

result = soup.find('strong', text='text I am looking for').text

How do I make flex box work in safari?

Just try -webkit-flexbox. it's working for safari. webkit-flex safari will not taking.

Get a list of checked checkboxes in a div using jQuery

$("#checkboxes").children("input:checked")

will give you an array of the elements themselves. If you just specifically need the names:

$("#checkboxes").children("input:checked").map(function() {
    return this.name;
});

Where can I find System.Web.Helpers, System.Web.WebPages, and System.Web.Razor?

To sum up all of the options for VS 2017, WebHelpers was installed by installing MVC in previous versions of Visual Studio. If you're getting this error, you probably don't have the older versions of VS installed anymore.

So, installing the Microsoft.AspNet.MVC NuGet package will require Microsoft.AspNet.WebPages and Microsoft.AspNet.Razor, and the Microsoft.AspNet.WebPages includes System.Web.Helpers.dll.

If you've got direct references to System.Web.Mvc.dll and you don't want to use NuGet for MVC, you can get the Microsoft.AspNet.WebPages NuGet, or there are some other NuGet packages that only contain System.Web.Helpers.dll, like the microsoft-web-helpers or System-Web-Helpers.dllpackages.

There appear to be 2 versions of System.Web.Helpers.dll, one for .Net 4.0 and one for 4.5. Choosing the correct version of MVC or AspNet.WebPages will ensure you get the right one.

What does print(... sep='', '\t' ) mean?

The sep='\t' can be use in many forms, for example if you want to read tab separated value: Example: I have a dataset tsv = tab separated value NOT comma separated value df = pd.read_csv('gapminder.tsv'). when you try to read this, it will give you an error because you have tab separated value not csv. so you need to give read csv a different parameter called sep='\t'.

Now you can read: df = pd.read_csv('gapminder.tsv, sep='\t'), with this you can read the it.

SQL Server FOR EACH Loop

Off course an old question. But I have a simple solution where no need of Looping, CTE, Table variables etc.

DECLARE @MyVar datetime = '1/1/2010'    
SELECT @MyVar

SELECT DATEADD (DD,NUMBER,@MyVar) 
FROM master.dbo.spt_values 
WHERE TYPE='P' AND NUMBER BETWEEN 0 AND 4 
ORDER BY NUMBER

Note : spt_values is a Mircrosoft's undocumented table. It has numbers for every type. Its not suggestible to use as it can be removed in any new versions of sql server without prior information, since it is undocumented. But we can use it as quick workaround in some scenario's like above.

WAITING at sun.misc.Unsafe.park(Native Method)

unsafe.park is pretty much the same as thread.wait, except that it's using architecture specific code (thus the reason it's 'unsafe'). unsafe is not made available publicly, but is used within java internal libraries where architecture specific code would offer significant optimization benefits. It's used a lot for thread pooling.

So, to answer your question, all the thread is doing is waiting for something, it's not really using any CPU. Considering that your original stack trace shows that you're using a lock I would assume a deadlock is going on in your case.

Yes I know you have almost certainly already solved this issue by now. However, you're one of the top results if someone googles sun.misc.unsafe.park. I figure answering the question may help others trying to understand what this method that seems to be using all their CPU is.

Longer object length is not a multiple of shorter object length?

Yes, this is something that you should worry about. Check the length of your objects with nrow(). R can auto-replicate objects so that they're the same length if they differ, which means you might be performing operations on mismatched data.

In this case you have an obvious flaw in that your subtracting aggregated data from raw data. These will definitely be of different lengths. I suggest that you merge them as time series (using the dates), then locf(), then do your subtraction. Otherwise merge them by truncating the original dates to the same interval as the aggregated series. Just be very careful that you don't drop observations.

Lastly, as some general advice as you get started: look at the result of your computations to see if they make sense. You might even pull them into a spreadsheet and replicate the results.

What happened to console.log in IE8?

I'm using Walter's approach from above (see: https://stackoverflow.com/a/14246240/3076102)

I mix in a solution I found here https://stackoverflow.com/a/7967670 to properly show Objects.

This means the trap function becomes:

function trap(){
    if(debugging){
        // create an Array from the arguments Object           
        var args = Array.prototype.slice.call(arguments);
        // console.raw captures the raw args, without converting toString
        console.raw.push(args);
        var index;
        for (index = 0; index < args.length; ++index) {
            //fix for objects
            if(typeof args[index] === 'object'){ 
                args[index] = JSON.stringify(args[index],null,'\t').replace(/\n/g,'<br>').replace(/\t/g,'&nbsp;&nbsp;&nbsp;');
            }
        }
        var message = args.join(' ');
        console.messages.push(message);
        // instead of a fallback function we use the next few lines to output logs
        // at the bottom of the page with jQuery
        if($){
            if($('#_console_log').length == 0) $('body').append($('<div />').attr('id', '_console_log'));
            $('#_console_log').append(message).append($('<br />'));
        }
    }
} 

I hope this is helpful:-)

how to add lines to existing file using python

If you want to append to the file, open it with 'a'. If you want to seek through the file to find the place where you should insert the line, use 'r+'. (docs)

How can I use an ES6 import in Node.js?

I don't know if this will work for your case, but I am running an Express.js server with this:

nodemon --inspect ./index.js --exec babel-node --presets es2015,stage-2

This gives me the ability to import and use spread operator even though I'm only using Node.js version 8.

You'll need to install babel-cli, babel-preset-es2015, and babel-preset-stage-2 to do what I'm doing.

Disabling of EditText in Android

As android:editable="false" deprecated In xml

Use android:enabled="false" it's simple. Why use more code?

If you want in java class you can also use this programmatically

 editText.setEnabled(false);

How to confirm RedHat Enterprise Linux version?

That is the release version of RHEL, or at least the release of RHEL from which the package supplying /etc/redhat-release was installed. A file like that is probably the closest you can come; you could also look at /etc/lsb-release.

It is theoretically possible to have packages installed from a mix of versions (e.g. upgrading part of the system to 5.5 while leaving other parts at 5.4), so if you depend on the versions of specific components you will need to check for those individually.

Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'

If seeing this message in Hive with new MySQL connector 8.x (MySQL metastore)

open hive-site.xml and change:

   <property>
      <name>javax.jdo.option.ConnectionDriverName</name>
      <value>com.mysql.jdbc.Driver</value>
      <description>MySQL JDBC driver class</description>
   </property>

to

   <property>
      <name>javax.jdo.option.ConnectionDriverName</name>
      <value>com.mysql.cj.jdbc.Driver</value>
      <description>MySQL JDBC driver class</description>
   </property>

html - table row like a link

This saves you having to duplicate the link in the tr - just fish it out of the first a.

$(".link-first-found").click(function() {
 var href;
href = $(this).find("a").attr("href");
if (href !== "") {
return document.location = href;
}
});

best way to get folder and file list in Javascript

I don't like adding new package into my project just to handle this simple task.

And also, I try my best to avoid RECURSIVE algorithm.... since, for most cases it is slower compared to non Recursive one.

So I made a function to get all the folder content (and its sub folder).... NON-Recursively

var getDirectoryContent = function(dirPath) {
    /* 
        get list of files and directories from given dirPath and all it's sub directories
        NON RECURSIVE ALGORITHM
        By. Dreamsavior
    */
    var RESULT = {'files':[], 'dirs':[]};

    var fs = fs||require('fs');
    if (Boolean(dirPath) == false) {
        return RESULT;
    }
    if (fs.existsSync(dirPath) == false) {
        console.warn("Path does not exist : ", dirPath);
        return RESULT;
    }

    var directoryList = []
    var DIRECTORY_SEPARATOR = "\\";
    if (dirPath[dirPath.length -1] !== DIRECTORY_SEPARATOR) dirPath = dirPath+DIRECTORY_SEPARATOR;

    directoryList.push(dirPath); // initial

    while (directoryList.length > 0) {
        var thisDir  = directoryList.shift(); 
        if (Boolean(fs.existsSync(thisDir) && fs.lstatSync(thisDir).isDirectory()) == false) continue;

        var thisDirContent = fs.readdirSync(thisDir);
        while (thisDirContent.length > 0) { 
            var thisFile  = thisDirContent.shift(); 
            var objPath = thisDir+thisFile

            if (fs.existsSync(objPath) == false) continue;
            if (fs.lstatSync(objPath).isDirectory()) { // is a directory
                let thisDirPath = objPath+DIRECTORY_SEPARATOR; 
                directoryList.push(thisDirPath);
                RESULT['dirs'].push(thisDirPath);

            } else  { // is a file
                RESULT['files'].push(objPath); 

            } 
        } 

    }
    return RESULT;
}

the only drawback of this function is that this is Synchronous function... You have been warned ;)

Get Last Part of URL PHP

One line working answer:

$url = "http://www.yoursite/one/two/three/drink";
echo $end = end((explode('/', $url)));

Output: drink

Mount current directory as a volume in Docker on Windows 10

docker run --rm -v /c/Users/Christian/manager/bin:/app --workdir=/app  php:7.2-cli php  app.php

Git bash

 cd /c/Users/Christian/manager
    docker run --rm -v  ${PWD}:/app  --workdir=/app  php:7.2-cli php  bin/app.php

echo ${PWD} result:

/c/Users/Christian/manager

cmd or PowerShell

  cd C:\Users\Christian\manager

echo ${PWD} result:

Path ---- C:\Users\Christian\manager

as we see in cmd or PowerShell $ {PWD} will not work

MySQL ERROR 1045 (28000): Access denied for user 'bill'@'localhost' (using password: YES)

I resolved this by deleting the old buggy user 'bill' entries (this is the important part: both from mysql.user and mysql.db), then created the same user as sad before:

FLUSH PRIVILEGES;
CREATE USER bill@localhost IDENTIFIED BY 'passpass';
grant all privileges on *.* to bill@localhost with grant option;
FLUSH PRIVILEGES;

Worked, user is connecting. Now I'll remove some previlegies from it :)

What is the easiest way to remove all packages installed by pip?

In my case, I had accidentally installed a number of packages globally using a Homebrew-installed pip on macOS. The easiest way to revert to the default packages was a simple:

$ brew reinstall python

Or, if you were using pip3:

$ brew reinstall python3

Set QLineEdit to accept only numbers

You could also set an inputMask:

QLineEdit.setInputMask("9")

This allows the user to type only one digit ranging from 0 to 9. Use multiple 9's to allow the user to enter multiple numbers. See also the complete list of characters that can be used in an input mask.

(My answer is in Python, but it should not be hard to transform it to C++)

App installation failed due to application-identifier entitlement

In most of the responses to this issue, there's one critical aspect being overlooked that was brought up by the original asker. The app needs to be installed without deleting the existing install. In my case, the app uses an SQLite database that stores quite a bit of data for the user. Obviously, if you delete the app, then you delete the data. A solution that allowed me to test it in the same way a user will update it was a must.

In my case, the issue was Xcode using a provisioning profile automatically generated by Xcode. This probably happened because I got a new computer and didn't transfer the distribution provisioning profile over. Not to mention, I had not updated the app in almost 2 years. So my original provisioning profile (which contains the Entitlements application-identifier) was long gone. Solution: in Xcode preferences-> Accounts-> Select the appropriate Apple ID-> View Details-> Under Provisioning Profiles, right-click on the Xcode-generated profile for that app (it's prefixed with XC iOS), and select Move to Trash.

Xcode provisioning profiles under Accounts

On the developer website, create a new distribution profile with your App's ID. Download the new profile, double click and Xcode should automatically install it. Conversely, you could return to the profiles listed in Xcode and tap the Download button next to your newly created profile. Build the app and try running again. By the way, my Xcode is set to automatically manage code signing, which other than this issue works great.

Write to UTF-8 file in Python

@S-Lott gives the right procedure, but expanding on the Unicode issues, the Python interpreter can provide more insights.

Jon Skeet is right (unusual) about the codecs module - it contains byte strings:

>>> import codecs
>>> codecs.BOM
'\xff\xfe'
>>> codecs.BOM_UTF8
'\xef\xbb\xbf'
>>> 

Picking another nit, the BOM has a standard Unicode name, and it can be entered as:

>>> bom= u"\N{ZERO WIDTH NO-BREAK SPACE}"
>>> bom
u'\ufeff'

It is also accessible via unicodedata:

>>> import unicodedata
>>> unicodedata.lookup('ZERO WIDTH NO-BREAK SPACE')
u'\ufeff'
>>> 

Output ("echo") a variable to a text file

The simplest Hello World example...

$hello = "Hello World"
$hello | Out-File c:\debug.txt

Environment variables for java installation

Set java Environment variable in Centos / Linux

/home/ vi .bashrc

export JAVA_HOME=/opt/oracle/product/java/jdk1.8.0_45

export PATH=$JAVA_HOME/bin:$PATH

java -version

Returning JSON object as response in Spring Boot

@RequestMapping("/api/status")
public Map doSomething()
{
    return Collections.singletonMap("status", myService.doSomething());
}

PS. Works only for 1 value

Relative div height

Percentage in width works but percentage in height will not work unless you specify a specific height for any parent in the dependent loop...

See this : percentage in height doesn’t work?

Comparing a variable with a string python not working when redirecting from bash script

When you read() the file, you may get a newline character '\n' in your string. Try either

if UserInput.strip() == 'List contents': 

or

if 'List contents' in UserInput: 

Also note that your second file open could also use with:

with open('/Users/.../USER_INPUT.txt', 'w+') as UserInputFile:     if UserInput.strip() == 'List contents': # or if s in f:         UserInputFile.write("ls")     else:         print "Didn't work" 

Why avoid increment ("++") and decrement ("--") operators in JavaScript?

If you read JavaScript The Good Parts, you'll see that Crockford's replacement for i++ in a for loop is i+=1 (not i=i+1). That's pretty clean and readable, and is less likely to morph into something "tricky."

Crockford made disallowing autoincrement and autodecrement an option in jsLint. You choose whether to follow the advice or not.

My own personal rule is to not do anything combined with autoincrement or autodecrement.

I've learned from years of experience in C that I don't get buffer overruns (or array index out of bounds) if I keep use of it simple. But I've discovered that I do get buffer overruns if I fall into the "excessively tricky" practice of doing other things in the same statement.

So, for my own rules, the use of i++ as the increment in a for loop is fine.

C string append

I write a function support dynamic variable string append, like PHP str append: str + str + ... etc.

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

int str_append(char **json, const char *format, ...)
{
    char *str = NULL;
    char *old_json = NULL, *new_json = NULL;

    va_list arg_ptr;
    va_start(arg_ptr, format);
    vasprintf(&str, format, arg_ptr);

    // save old json
    asprintf(&old_json, "%s", (*json == NULL ? "" : *json));

    // calloc new json memory
    new_json = (char *)calloc(strlen(old_json) + strlen(str) + 1, sizeof(char));

    strcat(new_json, old_json);
    strcat(new_json, str);

    if (*json) free(*json);
    *json = new_json;

    free(old_json);
    free(str);

    return 0;
}

int main(int argc, char *argv[])
{
    char *json = NULL;

    str_append(&json, "name: %d, %d, %d", 1, 2, 3);
    str_append(&json, "sex: %s", "male");
    str_append(&json, "end");
    str_append(&json, "");
    str_append(&json, "{\"ret\":true}");

    int i;
    for (i = 0; i < 10; i++) {
        str_append(&json, "id-%d", i);
    }

    printf("%s\n", json);

    if (json) free(json);

    return 0;
}

Java ArrayList - Check if list is empty

Good practice nowadays is to use CollectionUtils from either Apache Commons or Spring Framework.

CollectionUtils.isEmpty(list))

Use chrome as browser in C#?

Update for 2014:

I use geckofx, a healthy open source project that (as of this writing) keeps up to date pretty well with the latest Firefox releases.

To embed Chrome, you might consider another healthy looking open source project, Xilium.cefGlue, based on The Chromium Embedded Framework (CEF).

Both of these support WPF and Winforms, and both projects have support for .net and mono.

A button to start php script, how?

You could do it in one document if you had a conditional based on params sent over. Eg:

if (isset($_GET['secret_param'])) {
    <run script>
} else {
    <display button>
}

I think the best way though is to have two files.

In laymans terms, what does 'static' mean in Java?

The static keyword can be used in several different ways in Java and in almost all cases it is a modifier which means the thing it is modifying is usable without an enclosing object instance.

Java is an object oriented language and by default most code that you write requires an instance of the object to be used.

public class SomeObject {
    public int someField;
    public void someMethod() { };
    public Class SomeInnerClass { };
}

In order to use someField, someMethod, or SomeInnerClass I have to first create an instance of SomeObject.

public class SomeOtherObject {
    public void doSomeStuff() {
        SomeObject anInstance = new SomeObject();
        anInstance.someField = 7;
        anInstance.someMethod();
        //Non-static inner classes are usually not created outside of the
        //class instance so you don't normally see this syntax
        SomeInnerClass blah = anInstance.new SomeInnerClass();
    }
}

If I declare those things static then they do not require an enclosing instance.

public class SomeObjectWithStaticStuff {
    public static int someField;
    public static void someMethod() { };
    public static Class SomeInnerClass { };
}

public class SomeOtherObject {
    public void doSomeStuff() {
        SomeObjectWithStaticStuff.someField = 7;
        SomeObjectWithStaticStuff.someMethod();
        SomeObjectWithStaticStuff.SomeInnerClass blah = new SomeObjectWithStaticStuff.SomeInnerClass();
        //Or you can also do this if your imports are correct
        SomeInnerClass blah2 = new SomeInnerClass();
    }
}

Declaring something static has several implications.

First, there can only ever one value of a static field throughout your entire application.

public class SomeOtherObject {
    public void doSomeStuff() {
        //Two objects, two different values
        SomeObject instanceOne = new SomeObject();
        SomeObject instanceTwo = new SomeObject();
        instanceOne.someField = 7;
        instanceTwo.someField = 10;
        //Static object, only ever one value
        SomeObjectWithStaticStuff.someField = 7;
        SomeObjectWithStaticStuff.someField = 10; //Redefines the above set
    }
}

The second issue is that static methods and inner classes cannot access fields in the enclosing object (since there isn't one).

public class SomeObjectWithStaticStuff {
    private int nonStaticField;
    private void nonStaticMethod() { };

    public static void someStaticMethod() {
        nonStaticField = 7; //Not allowed
        this.nonStaticField = 7; //Not allowed, can never use *this* in static
        nonStaticMethod(); //Not allowed
        super.someSuperMethod(); //Not allowed, can never use *super* in static
    }

    public static class SomeStaticInnerClass {

        public void doStuff() {
            someStaticField = 7; //Not allowed
            nonStaticMethod(); //Not allowed
            someStaticMethod(); //This is ok
        }

    }
}

The static keyword can also be applied to inner interfaces, annotations, and enums.

public class SomeObject {
    public static interface SomeInterface { };
    public static @interface SomeAnnotation { };
    public static enum SomeEnum { };
}

In all of these cases the keyword is redundant and has no effect. Interfaces, annotations, and enums are static by default because they never have a relationship to an inner class.

This just describes what they keyword does. It does not describe whether the use of the keyword is a bad idea or not. That can be covered in more detail in other questions such as Is using a lot of static methods a bad thing?

There are also a few less common uses of the keyword static. There are static imports which allow you to use static types (including interfaces, annotations, and enums not redundantly marked static) unqualified.

//SomeStaticThing.java
public class SomeStaticThing {
    public static int StaticCounterOne = 0;
}

//SomeOtherStaticThing.java
public class SomeOtherStaticThing {
    public static int StaticCounterTwo = 0;
}

//SomeOtherClass.java
import static some.package.SomeStaticThing.*;
import some.package.SomeOtherStaticThing.*;

public class SomeOtherClass {
    public void doStuff() {
        StaticCounterOne++; //Ok
        StaticCounterTwo++; //Not ok
        SomeOtherStaticThing.StaticCounterTwo++; //Ok
    }
}

Lastly, there are static initializers which are blocks of code that are run when the class is first loaded (which is usually just before a class is instantiated for the first time in an application) and (like static methods) cannot access non-static fields or methods.

public class SomeObject {

    private static int x;

    static {
        x = 7;
    }
}

Is it possible to register a http+domain-based URL Scheme for iPhone apps, like YouTube and Maps?

In seeking to fix the problem of pop-up, I discovered that Apple had a way around this concern.

Indeed, when you click on this link, if you installed the application, it is rerouted to it; otherwise, you will be redirected to the webpage, without any pop-up.

Razor view engine - How can I add Partial Views

If you don't want to duplicate code, and like me you just want to show stats, in your view model, you could just pass in the models you want to get data from like so:

public class GameViewModel
{
    public virtual Ship Ship { get; set; }
    public virtual GamePlayer GamePlayer { get; set; }     
}

Then, in your controller just run your queries on the respective models, pass them to the view model and return it, example:

GameViewModel PlayerStats = new GameViewModel();

GamePlayer currentPlayer = (from c in db.GamePlayer [more queries]).FirstOrDefault();

[code to check if results]

//pass current player into custom view model
PlayerStats.GamePlayer = currentPlayer;

Like I said, you should only really do this if you want to display stats from the relevant tables, and there's no other part of the CRUD process happening, for security reasons other people have mentioned above.

Arduino Sketch upload issue - avrdude: stk500_recv(): programmer is not responding

On Windows 7, I had this problem multiple times, each time with different error messages. Basically, the IDE is sending to the wrong port.

To fix this, simply go to menu ToolsPorts → [select the COM port that your board is on].

Make sure to double check your board's port:

  1. Start Device Manager

    Start Menu

  2. Make sure your Arduino driver is listed under the port matching your IDE's port settings (mentioned above)

    Device Manager

  3. My board is listed under port COM1. If you want, you can simply change the port in the driver's advanced settings:

    Enter image description here

How to check if a string is numeric?

public static boolean isNumeric(String string) {
    if (string == null || string.isEmpty()) {
        return false;
    }
    int i = 0;
    int stringLength = string.length();
    if (string.charAt(0) == '-') {
        if (stringLength > 1) {
            i++;
        } else {
            return false;
        }
    }
    if (!Character.isDigit(string.charAt(i))
            || !Character.isDigit(string.charAt(stringLength - 1))) {
        return false;
    }
    i++;
    stringLength--;
    if (i >= stringLength) {
        return true;
    }
    for (; i < stringLength; i++) {
        if (!Character.isDigit(string.charAt(i))
                && string.charAt(i) != '.') {
            return false;
        }
    }
    return true;
}

WPF ListView turn off selection

This is for others who may encounter the following requirements:

  1. Completely replace the visual indication of "selected" (e.g. use some kind of shape), beyond just changing the color of the standard highlight
  2. Include this selected indication in the DataTemplate along with the other visual representations of your model, but,
  3. Don't want to have to add an "IsSelectedItem" property to your model class and be burdened with manually manipulating that property on all model objects.
  4. Require items to be selectable in the ListView
  5. Also would like to replace the visual representation of IsMouseOver

If you're like me (using WPF with .NET 4.5) and found that the solutions involving style triggers simply didn't work, here's my solution:

Replace the ControlTemplate of the ListViewItem in a style:

<ListView ItemsSource="{Binding MyStrings}" ItemTemplate="{StaticResource dtStrings}">
        <ListView.ItemContainerStyle>
            <Style TargetType="ListViewItem">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="ListViewItem">
                            <ContentPresenter/>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </ListView.ItemContainerStyle>
    </ListView>

..And the DataTemplate:

<DataTemplate x:Key="dtStrings">
        <Border Background="LightCoral" Width="80" Height="24" Margin="1">
            <Grid >
                <Border Grid.ColumnSpan="2" Background="#88FF0000" Visibility="{Binding RelativeSource={RelativeSource AncestorType=ListViewItem}, Path=IsMouseOver, Converter={StaticResource conBoolToVisibilityTrueIsVisibleFalseIsCollapsed}}"/>
                <Rectangle Grid.Column="0" Fill="Lime" Width="10" HorizontalAlignment="Left" Visibility="{Binding RelativeSource={RelativeSource AncestorType=ListViewItem}, Path=IsSelected, Converter={StaticResource conBoolToVisibilityTrueIsVisibleFalseIsCollapsed}}" />
                <TextBlock Grid.Column="1" Text="{Binding}" HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="White" />
            </Grid>
        </Border>
    </DataTemplate>

Results in this at runtime (item 'B' is selected, item 'D' has mouse over):

ListView appearance

Invisible characters - ASCII

An invisible Character is ?, or U+200b

?

Split array into chunks

I think this a nice recursive solution with ES6 syntax:

_x000D_
_x000D_
const chunk = function(array, size) {_x000D_
  if (!array.length) {_x000D_
    return [];_x000D_
  }_x000D_
  const head = array.slice(0, size);_x000D_
  const tail = array.slice(size);_x000D_
_x000D_
  return [head, ...chunk(tail, size)];_x000D_
};_x000D_
_x000D_
console.log(chunk([1,2,3], 2));
_x000D_
_x000D_
_x000D_

How to get the MD5 hash of a file in C++?

QFile file("bigimage.jpg");

if (file.open(QIODevice::ReadOnly))
{
    QByteArray fileData = file.readAll();

    QByteArray hashData = QCryptographicHash::hash(fileData,QCryptographicHash::Md5); // or QCryptographicHash::Sha1
    qDebug() << hashData.toHex();  // 0e0c2180dfd784dd84423b00af86e2fc

}

How to connect to my http://localhost web server from Android Emulator

Another workaround is to get a free domain from no-ip.org and point it to your local ip address. Then, instead of using http://localhost/yourwebservice you can try http://yourdomain.no-ip.org/yourwebservice

How do I get the current year using SQL on Oracle?

Since we are doing this one to death - you don't have to specify a year:

select * from demo
where  somedate between to_date('01/01 00:00:00', 'DD/MM HH24:MI:SS')
                and     to_date('31/12 23:59:59', 'DD/MM HH24:MI:SS');

However the accepted answer by FerranB makes more sense if you want to specify all date values that fall within the current year.

Jenkins - Configure Jenkins to poll changes in SCM

That's an old question, I know. But, according to me, it is missing proper answer.

The actual / optimal workflow here would be to incorporate SVN's post-commit hook so it triggers Jenkins job after the actual commit is issued only, not in any other case. This way you avoid unneeded polls on your SCM system.

You may find the following links interesting:

In case of my setup in the corp's SVN server, I utilize the following (censored) script as a post-commit hook on the subversion server side:

#!/bin/sh

# POST-COMMIT HOOK

REPOS="$1"
REV="$2"
#TXN_NAME="$3"
LOGFILE=/var/log/xxx/svn/xxx.post-commit.log

MSG=$(svnlook pg --revprop $REPOS svn:log -r$REV)
JENK="http://jenkins.xxx.com:8080/job/xxx/job/xxx/buildWithParameters?token=xxx&username=xxx&cause=xxx+r$REV"
JENKtest="http://jenkins.xxx.com:8080/view/all/job/xxx/job/xxxx/buildWithParameters?token=xxx&username=xxx&cause=xxx+r$REV"

echo post-commit $* >> $LOGFILE 2>&1

# trigger Jenkins job - xxx
svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -qP "branches/xxx/xxx/Source"
if test 0 -eq $? ; then
        echo $(date) - $REPOS - $REV: >> $LOGFILE
        svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -P "branches/xxx/xxx/Source" >> $LOGFILE 2>&1
        echo logmsg: $MSG >> $LOGFILE 2>&1
        echo curl -qs $JENK >> $LOGFILE 2>&1
        curl -qs $JENK >> $LOGFILE 2>&1
        echo -------- >> $LOGFILE
fi

# trigger Jenkins job - xxxx
svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -qP "branches/xxx_TEST"
if test 0 -eq $? ; then
        echo $(date) - $REPOS - $REV: >> $LOGFILE
        svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -P "branches/xxx_TEST" >> $LOGFILE 2>&1
        echo logmsg: $MSG >> $LOGFILE 2>&1
        echo curl -qs $JENKtest >> $LOGFILE 2>&1
        curl -qs $JENKtest >> $LOGFILE 2>&1
        echo -------- >> $LOGFILE
fi

exit 0

How to exit if a command failed?

The trap shell builtin allows catching signals, and other useful conditions, including failed command execution (i.e., a non-zero return status). So if you don't want to explicitly test return status of every single command you can say trap "your shell code" ERR and the shell code will be executed any time a command returns a non-zero status. For example:

trap "echo script failed; exit 1" ERR

Note that as with other cases of catching failed commands, pipelines need special treatment; the above won't catch false | true.

.do extension in web pages?

I've occasionally thought that it might serve a purpose to add a layer of security by obscuring the back-end interpreter through a remapping of .php or whatever to .aspx or whatever so that any potential hacker would be sent down the wrong path, at least for a while. I never bothered to try it and I don't do a lot of webserver work any more so I'm unlikely to.

However, I'd be interested in the perspective of an experienced server admin on that notion.

Auto-increment on partial primary key with Entity Framework Core

Annotate the property like below

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }

To use identity columns for all value-generated properties on a new model, simply place the following in your context's OnModelCreating():

builder.ForNpgsqlUseIdentityColumns();

This will create make all keys and other properties which have .ValueGeneratedOnAdd() have Identity by default. You can use ForNpgsqlUseIdentityAlwaysColumns() to have Identity always, and you can also specify identity on a property-by-property basis with UseNpgsqlIdentityColumn() and UseNpgsqlIdentityAlwaysColumn().

postgres efcore value generation

Insert images to XML file

The most common way of doing this is to include the binary as base-64 in an element. However, this is a workaround, and adds a bit of volume to the file.

For example, this is the bytes 00 to 09 (note we needed 16 bytes to encode 10 bytes worth of data):

<xml><image>AAECAwQFBgcICQ==</image></xml>

how you do this encoding varies per architecture. For example, with .NET you might use Convert.ToBase64String, or XmlWriter.WriteBase64.

Span inside anchor or anchor inside span or doesn't matter?

SPAN is a GENERIC inline container. It does not matter whether an a is inside span or span is inside a as both are inline elements. Feel free to do whatever seems logically correct to you.

How can I assign an ID to a view programmatically?

Yes, you can call setId(value) in any view with any (positive) integer value that you like and then find it in the parent container using findViewById(value). Note that it is valid to call setId() with the same value for different sibling views, but findViewById() will return only the first one.

HTML: How to center align a form

The last two lines are important to align in center:

.f01 {
    background-color: rgb(16, 216, 252);
    padding: 100px;
    text-align: left;
    margin: auto;
    display: table;
}

Simulate a button click in Jest

You may use something like this to call the handler written on click:

import { shallow } from 'enzyme'; // Mount is not required

page = <MyCoolPage />;
pageMounted = shallow(page);

// The below line will execute your click function
pageMounted.instance().yourOnClickFunction();

Java random numbers using a seed

Several of the examples here create a new Random instance, but this is unnecessary. There is also no reason to use synchronized as one solution does. Instead, take advantage of the methods on the ThreadLocalRandom class:

double randomGenerator() {
    return ThreadLocalRandom.current().nextDouble(0.5);
}

How to import data from one sheet to another

Saw this thread while looking for something else and I know it is super old, but I wanted to add my 2 cents.

NEVER USE VLOOKUP. It's one of the worst performing formulas in excel. Use index match instead. It even works without sorting data, unless you have a -1 or 1 in the end of the match formula (explained more below)

Here is a link with the appropriate formulas.

The Sheet 2 formula would be this: =IF(A2="","",INDEX(Sheet1!B:B,MATCH($A2,Sheet1!$A:$A,0)))

  • IF(A2="","", means if A2 is blank, return a blank value
  • INDEX(Sheet1!B:B, is saying INDEX B:B where B:B is the data you want to return. IE the name column.
  • Match(A2, is saying to Match A2 which is the ID you want to return the Name for.
  • Sheet1!A:A, is saying you want to match A2 to the ID column in the previous sheet
  • ,0)) is specifying you want an exact value. 0 means return an exact match to A2, -1 means return smallest value greater than or equal to A2, 1 means return the largest value that is less than or equal to A2. Keep in mind -1 and 1 have to be sorted.

More information on the Index/Match formula

Other fun facts: $ means absolute in a formula. So if you specify $B$1 when filling a formula down or over keeps that same value. If you over $B1, the B remains the same across the formula, but if you fill down, the 1 increases with the row count. Likewise, if you used B$1, filling to the right will increment the B, but keep the reference of row 1.

I also included the use of indirect in the second section. What indirect does is allow you to use the text of another cell in a formula. Since I created a named range sheet1!A:A = ID, sheet1!B:B = Name, and sheet1!C:C=Price, I can use the column name to have the exact same formula, but it uses the column heading to change the search criteria.

Good luck! Hope this helps.

Create an array or List of all dates between two dates

Our resident maestro Jon Skeet has a great Range Class that can do this for DateTimes and other types.

How to interpolate variables in strings in JavaScript, without concatenation?

String.prototype.interpole = function () {
    var c=0, txt=this;
    while (txt.search(/{var}/g) > 0){
        txt = txt.replace(/{var}/, arguments[c]);
        c++;
    }
    return txt;
}

Uso:

var hello = "foo";
var my_string = "I pity the {var}".interpole(hello);
//resultado "I pity the foo"

Splitting comma separated string in a PL/SQL stored proc

As for the connect by use case, this approach should work for you:

select regexp_substr('SMITH,ALLEN,WARD,JONES','[^,]+', 1, level)
from dual
connect by regexp_substr('SMITH,ALLEN,WARD,JONES', '[^,]+', 1, level) is not null;

Insert Multiple Rows Into Temp Table With SQL Server 2012

Yes, SQL Server 2012 supports multiple inserts - that feature was introduced in SQL Server 2008.

That makes me wonder if you have Management Studio 2012, but you're really connected to a SQL Server 2005 instance ...

What version of the SQL Server engine do you get from SELECT @@VERSION ??

C: What is the difference between ++i and i++?

You can think of internal conversion of that as a multiple statements;

  • case 1
i++;

you can think it as,

i;
i = i+1;
  • case 2
++i;

you can think it as,

i = i+i;
i;

Multipart File upload Spring Boot

@RequestMapping(value="/add/image", method=RequestMethod.POST)
public ResponseEntity upload(@RequestParam("id") Long id, HttpServletResponse response, HttpServletRequest request)
{   
    try {
        MultipartHttpServletRequest multipartRequest=(MultipartHttpServletRequest)request;
        Iterator<String> it=multipartRequest.getFileNames();
        MultipartFile multipart=multipartRequest.getFile(it.next());
        String fileName=id+".png";
        String imageName = fileName;

        byte[] bytes=multipart.getBytes();
        BufferedOutputStream stream= new BufferedOutputStream(new FileOutputStream("src/main/resources/static/image/book/"+fileName));;

        stream.write(bytes);
        stream.close();
        return new ResponseEntity("upload success", HttpStatus.OK);

    } catch (Exception e) {
        e.printStackTrace();
        return new ResponseEntity("Upload fialed", HttpStatus.BAD_REQUEST);
    }   
}

Among $_REQUEST, $_GET and $_POST which one is the fastest?

if (isset($_GET['s'])) {
  $temp = $_GET['s'];
}
else {
  $temp = $_POST['s'];
}

Use that because it is safer and it won't make noticeable speed difference

require(vendor/autoload.php): failed to open stream

In your project folder, the vendor folder is missing so you got this error:

Warning: require(vendor/autoload.php): failed to open stream: No such file or directory in

When you download the project through git, the project is downloaded without the vendor folder

You need /vendor because all your packages are there, including all the classes Laravel uses. The vendor directory contains your Composer dependencies.

The solution is simple, Just run this command:

composer update --no-scripts 
composer update
  • composer update --no-scripts It will Skips execution of scripts defined in composer.json file.
  • composer update It will update your depencencies as they are specified in composer.json file.

With this command, you will re-create the vendor folder in your project and after that your project will start working normally.

Trigger function when date is selected with jQuery UI datepicker

If the datepicker is in a row of a grid, try something like

editoptions : {
    dataInit : function (e) {
        $(e).datepicker({
            onSelect : function (ev) {
                // here your code
            }
        });
    }
}

Set CSS property in Javascript?

This works well with most CSS properties if there are no hyphens in them.

var element = document.createElement('select');
element.style.width = "100px";

For properties with hyphens in them like max-width, you should convert the sausage-case to camelCase

var element = document.createElement('select');
element.style.maxWidth = "100px";

Automatically capture output of last command into a variable using Bash?

There are more than one ways to do this. One way is to use v=$(command) which will assign the output of command to v. For example:

v=$(date)
echo $v

And you can use backquotes too.

v=`date`
echo $v

From Bash Beginners Guide,

When the old-style backquoted form of substitution is used, backslash retains its literal meaning except when followed by "$", "`", or "\". The first backticks not preceded by a backslash terminates the command substitution. When using the "$(COMMAND)" form, all characters between the parentheses make up the command; none are treated specially.

EDIT: After the edit in the question, it seems that this is not the thing that the OP is looking for. As far as I know, there is no special variable like $_ for the output of last command.

How do I center a Bootstrap div with a 'spanX' class?

Define the width as 960px, or whatever you prefer, and you're good to go!

#main {
 margin: 0 auto !important;
 float: none !important;
 text-align: center;
 width: 960px;
}

(I couldn't figure this out until I fixed the width, nothing else worked.)

Placing Unicode character in CSS content value

Why don't you just save/serve the CSS file as UTF-8?

nav a:hover:after {
    content: "?";
}

If that's not good enough, and you want to keep it all-ASCII:

nav a:hover:after {
    content: "\2193";
}

The general format for a Unicode character inside a string is \000000 to \FFFFFF – a backslash followed by six hexadecimal digits. You can leave out leading 0 digits when the Unicode character is the last character in the string or when you add a space after the Unicode character. See the spec below for full details.


Relevant part of the CSS2 spec:

Third, backslash escapes allow authors to refer to characters they cannot easily put in a document. In this case, the backslash is followed by at most six hexadecimal digits (0..9A..F), which stand for the ISO 10646 ([ISO10646]) character with that number, which must not be zero. (It is undefined in CSS 2.1 what happens if a style sheet does contain a character with Unicode codepoint zero.) If a character in the range [0-9a-fA-F] follows the hexadecimal number, the end of the number needs to be made clear. There are two ways to do that:

  1. with a space (or other white space character): "\26 B" ("&B"). In this case, user agents should treat a "CR/LF" pair (U+000D/U+000A) as a single white space character.
  2. by providing exactly 6 hexadecimal digits: "\000026B" ("&B")

In fact, these two methods may be combined. Only one white space character is ignored after a hexadecimal escape. Note that this means that a "real" space after the escape sequence must be doubled.

If the number is outside the range allowed by Unicode (e.g., "\110000" is above the maximum 10FFFF allowed in current Unicode), the UA may replace the escape with the "replacement character" (U+FFFD). If the character is to be displayed, the UA should show a visible symbol, such as a "missing character" glyph (cf. 15.2, point 5).

  • Note: Backslash escapes are always considered to be part of an identifier or a string (i.e., "\7B" is not punctuation, even though "{" is, and "\32" is allowed at the start of a class name, even though "2" is not).
    The identifier "te\st" is exactly the same identifier as "test".

Comprehensive list: Unicode Character 'DOWNWARDS ARROW' (U+2193).

How to open a website when a Button is clicked in Android application?

Add this to your button's click listener:

  Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
    try {
        intent.setData(Uri.parse(url));
        startActivity(intent);
    } catch (ActivityNotFoundException exception) {
        Toast.makeText(getContext(), "Error text", Toast.LENGTH_SHORT).show();
    }

If you have a website url as a variable instead of hardcoded string then don't forget to handle an ActivityNotFoundException and show error. Or you may receive invalid url and app will simply crash. (Pass random string instead of url variable and see for youself )

C error: Expected expression before int

This is actually a fairly interesting question. It's not as simple as it looks at first. For reference, I'm going to be basing this off of the latest C11 language grammar defined in N1570

I guess the counter-intuitive part of the question is: if this is correct C:

if (a == 1) {
  int b = 10;
}

then why is this not also correct C?

if (a == 1)
  int b = 10;

I mean, a one-line conditional if statement should be fine either with or without braces, right?

The answer lies in the grammar of the if statement, as defined by the C standard. The relevant parts of the grammar I've quoted below. Succinctly: the int b = 10 line is a declaration, not a statement, and the grammar for the if statement requires a statement after the conditional that it's testing. But if you enclose the declaration in braces, it becomes a statement and everything's well.

And just for the sake of answering the question completely -- this has nothing to do with scope. The b variable that exists inside that scope will be inaccessible from outside of it, but the program is still syntactically correct. Strictly speaking, the compiler shouldn't throw an error on it. Of course, you should be building with -Wall -Werror anyways ;-)

(6.7) declaration:
            declaration-speci?ers init-declarator-listopt ;
            static_assert-declaration

(6.7) init-declarator-list:
            init-declarator
            init-declarator-list , init-declarator

(6.7) init-declarator:
            declarator
            declarator = initializer

(6.8) statement:
            labeled-statement
            compound-statement
            expression-statement
            selection-statement
            iteration-statement
            jump-statement

(6.8.2) compound-statement:
            { block-item-listopt }

(6.8.4) selection-statement:
            if ( expression ) statement
            if ( expression ) statement else statement
            switch ( expression ) statement

Converting NSData to NSString in Objective c

Swift:

let jsonString = String(data: jsonData, encoding: .ascii)

or .utf8 or whatever encoding appropriate

Loading a properties file from Java package

public class Test{  
  static {
    loadProperties();
}
   static Properties prop;
   private static void loadProperties() {
    prop = new Properties();
    InputStream in = Test.class
            .getResourceAsStream("test.properties");
    try {
        prop.load(in);
        in.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

When to use CouchDB over MongoDB and vice versa

I summarize the answers found in that article:

http://www.quora.com/How-does-MongoDB-compare-to-CouchDB-What-are-the-advantages-and-disadvantages-of-each

MongoDB: Better querying, data storage in BSON (faster access), better data consistency, multiple collections

CouchDB: Better replication, with master to master replication and conflict resolution, data storage in JSON (human-readable, better access through REST services), querying through map-reduce.

So in conclusion, MongoDB is faster, CouchDB is safer.

Also: http://nosql.mypopescu.com/post/298557551/couchdb-vs-mongodb

How to use the pass statement?

You can say that pass means NOP (No Operation) operation. You will get a clear picture after this example :-

C Program

#include<stdio.h>

void main()
{
    int age = 12;

    if( age < 18 )
    {
         printf("You are not adult, so you can't do that task ");
    }
    else if( age >= 18 && age < 60)
    {
        // I will add more code later inside it 
    }
    else
    {
         printf("You are too old to do anything , sorry ");
    }
}

Now how you will write that in Python :-

age = 12

if age < 18:

    print "You are not adult, so you can't do that task"

elif age >= 18 and age < 60:

else:

    print "You are too old to do anything , sorry "

But your code will give error because it required an indented block after elif . Here is the role of pass keyword.

age = 12

if age < 18:

    print "You are not adult, so you can't do that task"

elif age >= 18 and age < 60:

    pass

else:

    print "You are too old to do anything , sorry "

Now I think its clear to you.

Find duplicates and delete all in notepad++

If it is possible to change the sequence of the lines you could do:

  1. sort line with Edit -> Line Operations -> Sort Lines Lexicographically ascending
  2. do a Find / Replace:
    • Find What: ^(.*\r?\n)\1+
    • Replace with: (Nothing, leave empty)
    • Check Regular Expression in the lower left
    • Click Replace All

How it works: The sorting puts the duplicates behind each other. The find matches a line ^(.*\r?\n) and captures the line in \1 then it continues and tries to find \1 one or more times (+) behind the first match. Such a block of duplicates (if it exists) is replaced with nothing.

The \r?\n should deal nicely with Windows and Unix lineendings.

iPhone App Development on Ubuntu

Not officially, no. It's just Objective-C though and the compiler's open source - you could probably get the headers and compile it and somehow get the binary on the device. Another option is compiling on the device. All these options will require jailbreaking though.
A Mac Mini is just $599...

How do you run a single test/spec file in RSpec?

The raw invocation:

rake spec SPEC=spec/controllers/sessions_controller_spec.rb \
          SPEC_OPTS="-e \"should log in with cookie\""

Now figure out how to embed this into your editor.

Uploading an Excel sheet and importing the data into SQL Server database

    public async Task<HttpResponseMessage> PostFormDataAsync()    //async is used for defining an asynchronous method
    {
        if (!Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }
        var fileLocation = "";
        string root = HttpContext.Current.Server.MapPath("~/App_Data");
        MultipartFormDataStreamProvider provider = new MultipartFormDataStreamProvider(root);  //Helps in HTML file uploads to write data to File Stream
        try
        {
            // Read the form data.
        await Request.Content.ReadAsMultipartAsync(provider);

            // This illustrates how to get the file names.
            foreach (MultipartFileData file in provider.FileData)
            {
                Trace.WriteLine(file.Headers.ContentDisposition.FileName); //Gets the file name
                var filePath = file.Headers.ContentDisposition.FileName.Substring(1, file.Headers.ContentDisposition.FileName.Length - 2); //File name without the path
                File.Copy(file.LocalFileName, file.LocalFileName + filePath); //Save a copy for reading it
                fileLocation = file.LocalFileName + filePath; //Complete file location
            }
    HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, recordStatus);
            return response;
}
catch (System.Exception e)
    {
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
    }
}
public void ReadFromExcel()
{
try
        {
            DataTable sheet1 = new DataTable();
            OleDbConnectionStringBuilder csbuilder = new OleDbConnectionStringBuilder();
            csbuilder.Provider = "Microsoft.ACE.OLEDB.12.0";
            csbuilder.DataSource = fileLocation;
            csbuilder.Add("Extended Properties", "Excel 12.0 Xml;HDR=YES");
            string selectSql = @"SELECT * FROM [Sheet1$]";
            using (OleDbConnection connection = new OleDbConnection(csbuilder.ConnectionString))
            using (OleDbDataAdapter adapter = new OleDbDataAdapter(selectSql, connection))
            {
                connection.Open();
                adapter.Fill(sheet1);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }          
}

Ternary operators in JavaScript without an "else"

More often, people use logical operators to shorten the statement syntax:

!defaults.slideshowWidth &&
  (defaults.slideshowWidth = obj.find('img').width() + 'px');

But in your particular case the syntax can be even simpler:

defaults.slideshowWidth = defaults.slideshowWidth || obj.find('img').width() + 'px';

This code will return the defaults.slideshowWidth value if the defaults.slideshowWidth is evaluated to true and obj.find('img').width() + 'px' value otherwise.

See Short-Circuit Evaluation of logical operators for details.

How Exactly Does @param Work - Java

@param won't affect the number. It's just for making javadocs.

More on javadoc: http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html

C# Set collection?

If you're using .NET 4.0 or later:

In the case where you need sorting then use SortedSet<T>. Otherwise if you don't, then use HashSet<T> since it's O(1) for search and manipulate operations. Whereas SortedSet<T> is O(log n) for search and manipulate operations.

Returning multiple objects in an R function

You could use for() with assign() to create many objects. See the example from assign():

for(i in 1:6) { #-- Create objects  'r.1', 'r.2', ... 'r.6' --
    nam <- paste("r", i, sep = ".")
    assign(nam, 1:i)

Looking the new objects

ls(pattern = "^r..$")

Javascript - sort array based on another array

Use intersection of two arrays.

Ex:

var sortArray = ['a', 'b', 'c',  'd', 'e'];

var arrayToBeSort = ['z', 's', 'b',  'e', 'a'];

_.intersection(sortArray, arrayToBeSort) 

=> ['a', 'b', 'e']

if 'z and 's' are out of range of first array, append it at the end of result

Why doesn't Python have multiline comments?

Triple-quoted text should NOT be considered multi-line comments; by convention, they are docstrings. They should describe what your code does and how to use it, but not for things like commenting out blocks of code.

According to Guido, multiline comments in Python are just contiguous single-line comments (search for "block comments").

To comment blocks of code, I sometimes use the following pattern:

if False:
    # A bunch of code

How do I compare two variables containing strings in JavaScript?

instead of using the == sign, more safer use the === sign when compare, the code that you post is work well

Non-static variable cannot be referenced from a static context

I will try to explain the static thing to you. First of all static variables do not belong to any particular instance of the class. They are recognized with the name of the class. Static methods again do not belong again to any particular instance. They can access only static variables. Imagine you call MyClass.myMethod() and myMethod is a static method. If you use non-static variables inside the method, how the hell on earth would it know which variables to use? That's why you can use from static methods only static variables. I repeat again they do NOT belong to any particular instance.

Execute a shell script in current shell with sudo permission

The answers here explain why it happens but I thought I'd add my simple way around the issue. First you can cat the file into a variable with sudo permissions. Then you can evaluate the variable to execute the code in the file in your current shell.

Here is an example of reading and executing an .env file (ex Docker)

 sensitive_stuff=$(sudo cat ".env")
 eval "${sensitive_stuff}"
 echo $ADMIN_PASSWORD 

What is the correct way to create a single-instance WPF application?

Here is my 2 cents

 static class Program
    {
        [STAThread]
        static void Main()
        {
            bool createdNew;
            using (new Mutex(true, "MyApp", out createdNew))
            {
                if (createdNew) {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    var mainClass = new SynGesturesLogic();
                    Application.ApplicationExit += mainClass.tray_exit;
                    Application.Run();
                }
                else
                {
                    var current = Process.GetCurrentProcess();
                    foreach (var process in Process.GetProcessesByName(current.ProcessName).Where(process => process.Id != current.Id))
                    {
                        NativeMethods.SetForegroundWindow(process.MainWindowHandle);
                        break;
                    }
                }
            }
        }
    }

How to get an HTML element's style values in javascript?

I believe you are now able to use Window.getComputedStyle()

Documentation MDN

var style = window.getComputedStyle(element[, pseudoElt]);

Example to get width of an element:

window.getComputedStyle(document.querySelector('#mainbar')).width

Sorting a list using Lambda/Linq to objects

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Linq.Expressions;

public static class EnumerableHelper
{

    static MethodInfo orderBy = typeof(Enumerable).GetMethods(BindingFlags.Static | BindingFlags.Public).Where(x => x.Name == "OrderBy" && x.GetParameters().Length == 2).First();

    public static IEnumerable<TSource> OrderBy<TSource>(this IEnumerable<TSource> source, string propertyName)
    {
        var pi = typeof(TSource).GetProperty(propertyName, BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.Instance);
        var selectorParam = Expression.Parameter(typeof(TSource), "keySelector");
        var sourceParam = Expression.Parameter(typeof(IEnumerable<TSource>), "source");
        return 
            Expression.Lambda<Func<IEnumerable<TSource>, IOrderedEnumerable<TSource>>>
            (
                Expression.Call
                (
                    orderBy.MakeGenericMethod(typeof(TSource), pi.PropertyType), 
                    sourceParam, 
                    Expression.Lambda
                    (
                        typeof(Func<,>).MakeGenericType(typeof(TSource), pi.PropertyType), 
                        Expression.Property(selectorParam, pi), 
                        selectorParam
                    )
                ), 
                sourceParam
            )
            .Compile()(source);
    }

    public static IEnumerable<TSource> OrderBy<TSource>(this IEnumerable<TSource> source, string propertyName, bool ascending)
    {
        return ascending ? source.OrderBy(propertyName) : source.OrderBy(propertyName).Reverse();
    }

}

Another one, this time for any IQueryable:

using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

public static class IQueryableHelper
{

    static MethodInfo orderBy = typeof(Queryable).GetMethods(BindingFlags.Static | BindingFlags.Public).Where(x => x.Name == "OrderBy" && x.GetParameters().Length == 2).First();
    static MethodInfo orderByDescending = typeof(Queryable).GetMethods(BindingFlags.Static | BindingFlags.Public).Where(x => x.Name == "OrderByDescending" && x.GetParameters().Length == 2).First();

    public static IQueryable<TSource> OrderBy<TSource>(this IQueryable<TSource> source, params string[] sortDescriptors)
    {
        return sortDescriptors.Length > 0 ? source.OrderBy(sortDescriptors, 0) : source;
    }

    static IQueryable<TSource> OrderBy<TSource>(this IQueryable<TSource> source, string[] sortDescriptors, int index)
    {
        if (index < sortDescriptors.Length - 1) source = source.OrderBy(sortDescriptors, index + 1);
        string[] splitted = sortDescriptors[index].Split(' ');
        var pi = typeof(TSource).GetProperty(splitted[0], BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.Instance | BindingFlags.IgnoreCase);
        var selectorParam = Expression.Parameter(typeof(TSource), "keySelector");
        return source.Provider.CreateQuery<TSource>(Expression.Call((splitted.Length > 1 && string.Compare(splitted[1], "desc", StringComparison.Ordinal) == 0 ? orderByDescending : orderBy).MakeGenericMethod(typeof(TSource), pi.PropertyType), source.Expression, Expression.Lambda(typeof(Func<,>).MakeGenericType(typeof(TSource), pi.PropertyType), Expression.Property(selectorParam, pi), selectorParam)));
    }

}

You can pass multiple sort criteria, like this:

var q = dc.Felhasznalos.OrderBy(new string[] { "Email", "FelhasznaloID desc" });

How can I compare two ordered lists in python?

If you want to just check if they are identical or not, a == b should give you true / false with ordering taken into account.

In case you want to compare elements, you can use numpy for comparison

c = (numpy.array(a) == numpy.array(b))

Here, c will contain an array with 3 elements all of which are true (for your example). In the event elements of a and b don't match, then the corresponding elements in c will be false.

Convert python datetime to timestamp in milliseconds

In Python 3 this can be done in 2 steps:

  1. Convert timestring to datetime object
  2. Multiply the timestamp of the datetime object by 1000 to convert it to milliseconds.

For example like this:

from datetime import datetime

dt_obj = datetime.strptime('20.12.2016 09:38:42,76',
                           '%d.%m.%Y %H:%M:%S,%f')
millisec = dt_obj.timestamp() * 1000

print(millisec)

Output:

1482223122760.0

strptime accepts your timestring and a format string as input. The timestring (first argument) specifies what you actually want to convert to a datetime object. The format string (second argument) specifies the actual format of the string that you have passed.

Here is the explanation of the format specifiers from the official documentation:

  • %d - Day of the month as a zero-padded decimal number.
  • %m - Month as a zero-padded decimal number.
  • %Y - Year with century as a decimal number
  • %H - Hour (24-hour clock) as a zero-padded decimal number.
  • %M - Minute as a zero-padded decimal number.
  • %S - Second as a zero-padded decimal number.
  • %f - Microsecond as a decimal number, zero-padded on the left.

how to drop database in sqlite?

SQLite database FAQ: How do I drop a SQLite database?

People used to working with other databases are used to having a "drop database" command, but in SQLite there is no similar command. The reason? In SQLite there is no "database server" -- SQLite is an embedded database, and your database is entirely contained in one file. So there is no need for a SQLite drop database command.

To "drop" a SQLite database, all you have to do is delete the SQLite database file you were accessing.

copy from http://alvinalexander.com/android/sqlite-drop-database-how

Getting error while sending email through Gmail SMTP - "Please log in via your web browser and then try again. 534-5.7.14"

I know this is an older issue, but I recently had the same problem and was having issues resolving it, despite attempting the DisplayUnlockCaptcha fix. This is how I got it alive.

Head over to Account Security Settings (https://www.google.com/settings/security/lesssecureapps) and enable "Access for less secure apps", this allows you to use the google smtp for clients other than the official ones.

Update

Google has been so kind as to list all the potential problems and fixes for us. Although I recommend trying the less secure apps setting. Be sure you are applying these to the correct account.

  • If you've turned on 2-Step Verification for your account, you might need to enter an App password instead of your regular password.
  • Sign in to your account from the web version of Gmail at https://mail.google.com. Once you’re signed in, try signing in
    to the mail app again.
  • Visit http://www.google.com/accounts/DisplayUnlockCaptcha and sign in with your Gmail username and password. If asked, enter the
    letters in the distorted picture.
  • Your app might not support the latest security standards. Try changing a few settings to allow less secure apps access to your account.
  • Make sure your mail app isn't set to check for new email too often. If your mail app checks for new messages more than once every 10
    minutes, the app’s access to your account could be blocked.

Emulating a do-while loop in Bash

This implementation:

  • Has no code duplication
  • Doesn't require extra functions()
  • Doesn't depend on the return value of code in the "while" section of the loop:
do=true
while $do || conditions; do
  do=false
  # your code ...
done

It works with a read loop, too, skipping the first read:

do=true
while $do || read foo; do
  do=false

  # your code ...
  echo $foo
done

Histogram using gnuplot?

We do not need to use recursive method, it may be slow. My solution is using a user-defined function rint instesd of instrinsic function int or floor.

rint(x)=(x-int(x)>0.9999)?int(x)+1:int(x)

This function will give rint(0.0003/0.0001)=3, while int(0.0003/0.0001)=floor(0.0003/0.0001)=2.

Why? Please look at Perl int function and padding zeros

Migration: Cannot add foreign key constraint

If none of the solutions above work for newbies check if both IDs have the same type: both are integer or both are bigInteger, ... You can have something like this:

Main Table (users for example)

$table->bigIncrements('id');

Child Table (priorities for example)

$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

This query will failed because users.id is a BIG INTEGER whereas priorities.user_id is an INTEGER.

The right query in this case would be the following:

$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

Error:Unable to locate adb within SDK in Android Studio

In my case I had no SDK selected for my project(not sure why). Simply went to Project Structure dialog (alt+ctrl+shift+s or button 1 on the screen) and then to project-> Project SDK's was selected <no SDK>. Just changed it to the latest

Project Structure dialog

java.io.IOException: Invalid Keystore format

You may corrupt the file during copy/transfer.

Are you using maven? If you are copying keystore file with "filter=true", you may corrupt the file.

Please check the file size.

Removing unwanted table cell borders with CSS

Set the cellspacing attribute of the table to 0.

You can also use the CSS style, border-spacing: 0, but only if you don't need to support older versions of IE.

What are the alternatives now that the Google web search API has been deprecated?

Yes, Google Custom Search has now replaced the old Search API, but you can still use Google Custom Search to search the entire web, although the steps are not obvious from the Custom Search setup.

To create a Google Custom Search engine that searches the entire web:

  1. From the Google Custom Search homepage ( http://www.google.com/cse/ ), click Create a Custom Search Engine.
  2. Type a name and description for your search engine.
  3. Under Define your search engine, in the Sites to Search box, enter at least one valid URL (For now, just put www.anyurl.com to get past this screen. More on this later ).
  4. Select the CSE edition you want and accept the Terms of Service, then click Next. Select the layout option you want, and then click Next.
  5. Click any of the links under the Next steps section to navigate to your Control panel.
  6. In the left-hand menu, under Control Panel, click Basics.
  7. In the Search Preferences section, select Search the entire web but emphasize included sites.
  8. Click Save Changes.
  9. In the left-hand menu, under Control Panel, click Sites.
  10. Delete the site you entered during the initial setup process.

Now your custom search engine will search the entire web.

Pricing

  • Google Custom Search gives you 100 queries per day for free.
  • After that you pay $5 per 1000 queries.
  • There is a maximum of 10,000 queries per day.

Source: https://developers.google.com/custom-search/json-api/v1/overview#Pricing


  • The search quality is much lower than normal Google search (no synonyms, "intelligence" etc.)
  • It seems that Google is even planning to shut down this service completely.

How do I convert between ISO-8859-1 and UTF-8 in Java?

If you have a String, you can do that:

String s = "test";
try {
    s.getBytes("UTF-8");
} catch(UnsupportedEncodingException uee) {
    uee.printStackTrace();
}

If you have a 'broken' String, you did something wrong, converting a String to a String in another encoding is defenetely not the way to go! You can convert a String to a byte[] and vice-versa (given an encoding). In Java Strings are AFAIK encoded with UTF-16 but that's an implementation detail.

Say you have a InputStream, you can read in a byte[] and then convert that to a String using

byte[] bs = ...;
String s;
try {
    s = new String(bs, encoding);
} catch(UnsupportedEncodingException uee) {
    uee.printStackTrace();
}

or even better (thanks to erickson) use InputStreamReader like that:

InputStreamReader isr;
try {
     isr = new InputStreamReader(inputStream, encoding);
} catch(UnsupportedEncodingException uee) {
    uee.printStackTrace();
}

Colorized grep -- viewing the entire file with highlighted matches

Here's something along the same lines. Chances are, you'll be using less anyway, so try this:

less -p pattern file

It will highlight the pattern and jump to the first occurrence of it in the file.

You can jump to the next occurence with n and to the previous occurence with p. Quit with q.

Bootstrap: add margin/padding space between columns

In the otherside if you like to remove double padding between columns just add class "nogap" inside row

<div class="row nogap">
    <div class="text-center col-md-6">Widget 1</div>
    <div class="text-center col-md-6">Widget 2</div>
</div>

and create additional css class for it

.nogap > .col{ padding-left:7.5px; padding-right: 7.5px}
.nogap > .col:first-child{ padding-left: 15px; }
.nogap > .col:last-child{ padding-right: 15px; }

Thats it, check here: https://codepen.io/michal-lukasik/pen/xXvoYJ

Insert auto increment primary key to existing table

I was facing the same problem so what I did I dropped the field for the primary key then I recreated it and made sure that it is auto incremental . That worked for me . I hope it helps others

How to add a title to a html select tag

<select>
    <option selected disabled>Choose one</option>
    <option value="sydney">Sydney</option>
    <option value="melbourne">Melbourne</option>
    <option value="cromwell">Cromwell</option>
    <option value="queenstown">Queenstown</option>
</select>

Using selected and disabled will make "Choose one" be the default selected value, but also make it impossible for the user to actually select the item, like so:

Dropdown menu

Powershell equivalent of bash ampersand (&) for forking/running background processes

I've used the solution described here http://jtruher.spaces.live.com/blog/cns!7143DA6E51A2628D!130.entry successfully in PowerShell v1.0. It definitely will be easier in PowerShell v2.0.

Maximum number of threads in a .NET app?

I would recommend running ThreadPool.GetMaxThreads method in debug

ThreadPool.GetMaxThreads(out int workerThreadsCount, out int ioThreadsCount);

Docs and examples: https://docs.microsoft.com/en-us/dotnet/api/system.threading.threadpool.getmaxthreads?view=netframework-4.8

How to get label text value form a html page?

The best way to get the text value from a <label> element is as follows.

if you will be getting element ids frequently it's best to have a function to return the ids:

function id(e){return document.getElementById(e)}

Assume the following structure: <label for='phone'>Phone number</label> <input type='text' id='phone' placeholder='Mobile or landline numbers...'>

This code will extract the text value 'Phone number' from the<label>: var text = id('phone').previousElementSibling.innerHTML;

This code works on all browsers, and you don't have to give each<label>element a unique id.

Base64 encoding and decoding in oracle

All the previous posts are correct. There's more than one way to skin a cat. Here is another way to do the same thing: (just replace "what_ever_you_want_to_convert" with your string and run it in Oracle:

    set serveroutput on;
    DECLARE
    v_str VARCHAR2(1000);
    BEGIN
    --Create encoded value
    v_str := utl_encode.text_encode
    ('what_ever_you_want_to_convert','WE8ISO8859P1', UTL_ENCODE.BASE64);
    dbms_output.put_line(v_str);
    --Decode the value..
    v_str := utl_encode.text_decode
    (v_str,'WE8ISO8859P1', UTL_ENCODE.BASE64);
    dbms_output.put_line(v_str);
    END;
    /

source

How to read response headers in angularjs?

Additionally to Eugene Retunsky's answer, quoting from $http documentation regarding the response:

The response object has these properties:

  • data{string|Object} – The response body transformed with the transform functions.

  • status{number} – HTTP status code of the response.

  • headers{function([headerName])} – Header getter function.

  • config{Object} – The configuration object that was used to generate the request.

  • statusText{string} – HTTP status text of the response.

Please note that the argument callback order for $resource (v1.6) is not the same as above:

Success callback is called with (value (Object|Array), responseHeaders (Function), status (number), statusText (string)) arguments, where the value is the populated resource instance or collection object. The error callback is called with (httpResponse) argument.

How is OAuth 2 different from OAuth 1?

From a security point of view, I'd go for OAuth 1. See OAuth 2.0 and the road to hell

quote from that link: "If you are currently using 1.0 successfully, ignore 2.0. It offers no real value over 1.0 (I’m guessing your client developers have already figured out 1.0 signatures by now).

If you are new to this space, and consider yourself a security expert, use 2.0 after careful examination of its features. If you are not an expert, either use 1.0 or copy the 2.0 implementation of a provider you trust to get it right (Facebook’s API documents are a good place to start). 2.0 is better for large scale, but if you are running a major operation, you probably have some security experts on site to figure it all out for you."

ng serve not detecting file changes automatically

ng serve --poll=2000

Working fine in linux and windows

Git push failed, "Non-fast forward updates were rejected"

I encountered the same error, just add "--force" to the command, it works

git push origin master --force

JPA Hibernate Persistence exception [PersistenceUnit: default] Unable to build Hibernate SessionFactory

The issue is that you are not able to get a connection to MYSQL database and hence it is throwing an error saying that cannot build a session factory.

Please see the error below:

 Caused by: java.sql.SQLException: Access denied for user ''@'localhost' (using password: NO) 

which points to username not getting populated.

Please recheck system properties

dataSource.setUsername(System.getProperty("root"));

some packages seems to be missing as well pointing to a dependency issue:

package org.gjt.mm.mysql does not exist

Please run a mvn dependency:tree command to check for dependencies

CodeIgniter - how to catch DB errors?

Disable debugging of errors.

    $data_user = $this->getDataUser();
    $id_user   = $this->getId_user();

    $this->db->db_debug = false;
    $this->db->where(['id' => $id_user]);
    $res = $this->db->update(self::$table, $data_user['user']);

    if(!$res)
    {
        $error = $this->db->error();
        return $error;
        //return array $error['code'] & $error['message']
    }
    else
    {
        return 1;
    }

How to convert map to url query string?

In Spring Util, there is a better way..,

import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;

MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
params.add("key", key);
params.add("storeId", storeId);
params.add("orderId", orderId);
UriComponents uriComponents =     UriComponentsBuilder.fromHttpUrl("http://spsenthil.com/order").queryParams(params).build();
ListenableFuture<ResponseEntity<String>> responseFuture =     restTemplate.getForEntity(uriComponents.toUriString(), String.class);

What are the main differences between JWT and OAuth authentication?

It looks like everybody who answered here missed the moot point of OAUTH

From Wikipedia

OAuth is an open standard for access delegation, commonly used as a way for Internet users to grant websites or applications access to their information on other websites but without giving them the passwords.[1] This mechanism is used by companies such as Google, Facebook, Microsoft and Twitter to permit the users to share information about their accounts with third party applications or websites.

The key point here is access delegation. Why would anyone create OAUTH when there is an id/pwd based authentication, backed by multifactored auth like OTPs and further can be secured by JWTs which are used to secure the access to the paths (like scopes in OAUTH) and set the expiry of the access

There's no point of using OAUTH if consumers access their resources(your end points) only through their trusted websites(or apps) which are your again hosted on your end points

You can go OAUTH authentication only if you are an OAUTH provider in the cases where the resource owners (users) want to access their(your) resources (end-points) via a third-party client(external app). And it is exactly created for the same purpose though you can abuse it in general

Another important note:
You're freely using the word authentication for JWT and OAUTH but neither provide the authentication mechanism. Yes one is a token mechanism and the other is protocol but once authenticated they are only used for authorization (access management). You've to back OAUTH either with OPENID type authentication or your own client credentials

Core dump file is not generated

Check:

$ sysctl kernel.core_pattern

to see how your dumps are created (%e will be the process name, and %t will be the system time).

If you've Ubuntu, your dumps are created by apport in /var/crash, but in different format (edit the file to see it).

You can test it by:

sleep 10 &
killall -SIGSEGV sleep

If core dumping is successful, you will see “(core dumped)” after the segmentation fault indication.

Read more:

How to generate core dump file in Ubuntu


Ubuntu

Please read more at:

https://wiki.ubuntu.com/Apport

how to convert integer to string?

If you really want to use String:

NSString *number = [[NSString alloc] initWithFormat:@"%d", 123];

But I would recommend using NSNumber:

NSNumber *number = [[NSNumber alloc] initWithInt:123];

Then just add it to the array.

[array addObject:number];

Don't forget to release it after that, since you created it above.

[number release];

How to use ArrayList's get() method

Would this help?

final List<String> l = new ArrayList<String>();
for (int i = 0; i < 10; i++) l.add("Number " + i);
for (int i = 0; i < 10; i++) System.out.println(l.get(i));

INSERT INTO a temp table, and have an IDENTITY field created, without first declaring the temp table?

To make things efficient, you need to do declare that one of the columns to be a primary key:

ALTER TABLE #mytable
ADD PRIMARY KEY(KeyColumn)

That won't take a variable for the column name.

Trust me, you are MUCH better off doing a: CREATE #myTable TABLE (or possibly a DECLARE TABLE @myTable) , which allows you to set IDENTITY and PRIMARY KEY directly.

Unable to compile simple Java 10 / Java 11 project with Maven

It might not exactly be the same error, but I had a similar one.

Check Maven Java Version

Since Maven is also runnig with Java, check first with which version your Maven is running on:

mvn --version | grep -i java 

It returns:

Java version 1.8.0_151, vendor: Oracle Corporation, runtime: C:\tools\jdk\openjdk1.8

Incompatible version

Here above my maven is running with Java Version 1.8.0_151. So even if I specify maven to compile with Java 11:

<properties>
    <java.version>11</java.version>
    <maven.compiler.source>${java.version}</maven.compiler.source>
    <maven.compiler.target>${java.version}</maven.compiler.target>
</properties>

It will logically print out this error:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.0:compile (default-compile) on project efa-example-commons-task: Fatal error compiling: invalid target release: 11 -> [Help 1]

How to set specific java version to Maven

The logical thing to do is to set a higher Java Version to Maven (e.g. Java version 11 instead 1.8).

Maven make use of the environment variable JAVA_HOME to find the Java Version to run. So change this variable to the JDK you want to compile against (e.g. OpenJDK 11).

Sanity check

Then run again mvn --version to make sure the configuration has been taken care of:

mvn --version | grep -i java

yields

Java version: 11.0.2, vendor: Oracle Corporation, runtime: C:\tools\jdk\openjdk11

Which is much better and correct to compile code written with the Java 11 specifications.

How does python numpy.where() work?

np.where returns a tuple of length equal to the dimension of the numpy ndarray on which it is called (in other words ndim) and each item of tuple is a numpy ndarray of indices of all those values in the initial ndarray for which the condition is True. (Please don't confuse dimension with shape)

For example:

x=np.arange(9).reshape(3,3)
print(x)
array([[0, 1, 2],
      [3, 4, 5],
      [6, 7, 8]])
y = np.where(x>4)
print(y)
array([1, 2, 2, 2], dtype=int64), array([2, 0, 1, 2], dtype=int64))


y is a tuple of length 2 because x.ndim is 2. The 1st item in tuple contains row numbers of all elements greater than 4 and the 2nd item contains column numbers of all items greater than 4. As you can see, [1,2,2,2] corresponds to row numbers of 5,6,7,8 and [2,0,1,2] corresponds to column numbers of 5,6,7,8 Note that the ndarray is traversed along first dimension(row-wise).

Similarly,

x=np.arange(27).reshape(3,3,3)
np.where(x>4)


will return a tuple of length 3 because x has 3 dimensions.

But wait, there's more to np.where!

when two additional arguments are added to np.where; it will do a replace operation for all those pairwise row-column combinations which are obtained by the above tuple.

x=np.arange(9).reshape(3,3)
y = np.where(x>4, 1, 0)
print(y)
array([[0, 0, 0],
   [0, 0, 1],
   [1, 1, 1]])

How to do a SUM() inside a case statement in SQL server

If you're using SQL Server 2005 or above, you can use the windowing function SUM() OVER ().

case 
when test1.TotalType = 'Average' then Test2.avgscore
when test1.TotalType = 'PercentOfTot' then (cnt/SUM(test1.qrank) over ())
else cnt
end as displayscore

But it'll be better if you show your full query to get context of what you actually need.

Java: Convert a String (representing an IP) to InetAddress

From the documentation of InetAddress.getByName(String host):

The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address. If a literal IP address is supplied, only the validity of the address format is checked.

So you can use it.

Using textures in THREE.js

Andrea solution is absolutely right, I will just write another implementation based on the same idea. If you took a look at the THREE.ImageUtils.loadTexture() source you will find it uses the javascript Image object. The $(window).load event is fired after all Images are loaded ! so at that event we can render our scene with the textures already loaded...

  • CoffeeScript

    $(document).ready ->
    
        material = new THREE.MeshLambertMaterial(map: THREE.ImageUtils.loadTexture("crate.gif"))
    
        sphere   = new THREE.Mesh(new THREE.SphereGeometry(radius, segments, rings), material)
    
        $(window).load ->
            renderer.render scene, camera
    
  • JavaScript

    $(document).ready(function() {
    
        material = new THREE.MeshLambertMaterial({ map: THREE.ImageUtils.loadTexture("crate.gif") });
    
        sphere = new THREE.Mesh(new THREE.SphereGeometry(radius, segments, rings), material);
    
        $(window).load(function() {
            renderer.render(scene, camera);
        });
    });
    

Thanks...

Why this "Implicit declaration of function 'X'"?

summation and your other functions are defined after they're used in main, and so the compiler has made a guess about it's signature; in other words, an implicit declaration has been assumed.

You should declare the function before it's used and get rid of the warning. In the C99 specification, this is an error.

Either move the function bodies before main, or include method signatures before main, e.g.:

#include <stdio.h>

int summation(int *, int *, int *);

int main()
{
    // ...

Python socket.error: [Errno 111] Connection refused

The problem obviously was (as you figured it out) that port 36250 wasn't open on the server side at the time you tried to connect (hence connection refused). I can see the server was supposed to open this socket after receiving SEND command on another connection, but it apparently was "not opening [it] up in sync with the client side".

Well, the main reason would be there was no synchronisation whatsoever. Calling:

cs.send("SEND " + FILE)
cs.close()

would just place the data into a OS buffer; close would probably flush the data and push into the network, but it would almost certainly return before the data would reach the server. Adding sleep after close might mitigate the problem, but this is not synchronisation.

The correct solution would be to make sure the server has opened the connection. This would require server sending you some message back (for example OK, or better PORT 36250 to indicate where to connect). This would make sure the server is already listening.

The other thing is you must check the return values of send to make sure how many bytes was taken from your buffer. Or use sendall.

(Sorry for disturbing with this late answer, but I found this to be a high traffic question and I really didn't like the sleep idea in the comments section.)

Git cli: get user info from username

git config --list

git config -l

will display your username and email together, along with other info

jQuery.animate() with css class only, without explicit styles

Check out James Padolsey's animateToSelector

Intro: This jQuery plugin will allow you to animate any element to styles specified in your stylesheet. All you have to do is pass a selector and the plugin will look for that selector in your StyleSheet and will then apply it as an animation.

log4j:WARN No appenders could be found for logger (running jar file, not web app)

I had moved my log4j.properties into the resources folder and it worked fine for me !

Difference between Method and Function?

well, in some programming languages they are called functions others call it methods, the fact is they are the same thing. It just represents an abstractized form of reffering to a mathematical function:

f -> f(N:N).

meaning its a function with values from natural numbers (just an example). So besides the name Its exactly the same thing, representing a block of code containing instructions in resolving your purpose.

How can I use jQuery in Greasemonkey?

@require is NOT only processed when the script is first installed! On my observations it is proccessed on the first execution time! So you can install a script via Greasemonkey's command for creating a brand-new script. The only thing you have to take care about is, that there is no page reload triggered, befor you add the @requirepart. (and save the new script...)

Auto detect mobile browser (via user-agent?)

You haven't said what language you're using. If it's Perl then it's trivial:

use CGI::Info;

my $info = CGI::Info->new();

if($info->is_mobile()) {
   # Add mobile stuff
}

unless($info->is_mobile()) {
   # Don't do some things on a mobile
}

How to save data in an android app

In onCreate:

SharedPreferences sharedPref = getSharedPreferences("mySettings", MODE_PRIVATE);

    String mySetting = sharedPref.getString("mySetting", null);

In onDestroy or equivalent:

SharedPreferences sharedPref = getSharedPreferences("mySettings", MODE_PRIVATE);

    SharedPreferences.Editor editor = sharedPref.edit();
    editor.putString("mySetting", "Hello Android");
    editor.commit();

Php $_POST method to get textarea value

Use htmlspecialchars():

echo htmlspecialchars($_POST['contact_list']);

You can even improve your form processing by stripping all tags with strip_tags() and remove all white spaces with trim():

function processText($text) {
    $text = strip_tags($text);
    $text = trim($text);
    $text = htmlspecialchars($text);
    return $text;
}

echo processText($_POST['contact_list']);

How to use log levels in java

Generally, you don't need all those levels, SEVERE, WARNING, INFO, FINE might be enough. We're using Log4J (not java.util.logging directly) and the following levels (which might differ in name from other logging frameworks):

  • ERROR: Any error/exception that is or might be critical. Our Logger automatically sends an email for each such message on our servers (usage: logger.error("message"); )

  • WARN: Any message that might warn us of potential problems, e.g. when a user tried to log in with wrong credentials - which might indicate an attack if that happens often or in short periods of time (usage: logger.warn("message"); )

  • INFO: Anything that we want to know when looking at the log files, e.g. when a scheduled job started/ended (usage: logger.info("message"); )

  • DEBUG: As the name says, debug messages that we only rarely turn on. (usage: logger.debug("message"); )

The beauty of this is that if you set the log level to WARN, info and debug messages have next to no performance impact. If you need to get additional information from a production system you just can lower the level to INFO or DEBUG for a short period of time (since you'd get much more log entries which make your log files bigger and harder to read). Adjusting log levels etc. can normally be done at runtime (our JBoss instance checks for changes in that config every minute or so).

How to compile for Windows on Linux with gcc/g++?

From: https://fedoraproject.org/wiki/MinGW/Tutorial

As of Fedora 17 it is possible to easily build (cross-compile) binaries for the win32 and win64 targets. This is realized using the mingw-w64 toolchain: http://mingw-w64.sf.net/. Using this toolchain allows you to build binaries for the following programming languages: C, C++, Objective-C, Objective-C++ and Fortran.

"Tips and tricks for using the Windows cross-compiler": https://fedoraproject.org/wiki/MinGW/Tips

REST API Authentication

Here's a guided approach.

Your authentication service issues a JWT token that is signed using a secret that is also available in your API service. The reason they need to be there too is that you will need to verify the tokens received to make sure you created them. The nice thing about JWTs is that their payload can hold claims as to what the user is authorised to access should different users have different access control levels.

That architecture renders authentication stateless: No need to store any tokens in a database unless you would like to handle token blacklisting (think banning users). Being stateless is crucial if you ever need to scale. That also frees up your API service from having to call the authentication server at all as the information they need for both authentication and authorisation are in the issued token.

Flow (no refresh tokens):

  1. User authenticates with the authentication server (eg: POST /auth/login) and receives a JWT token generated and signed by the auth server.
  2. User uses that token to talk to your API and assuming user is authorised), gets and posts the necessary resources.

There are a couple of issues here. Namely, that auth token in the wrong hands provides unlimited access to a malicious user to pretend they are the affected user and call your APIs indefinitely. To handle that, tokens have an expiry date and clients are forced to request new tokens whenever expiry happens. That expiry is part of the token's payload. But if tokens are short-lived, do we require users to authenticate with their usernames and password every time? No. We do not want to ask a user for their password every 30min to an hour, and we do not want to persist that password anywhere in the client. To get around that issue, we introduce the concept of refresh tokens. They are longer lived tokens that serve one purpose: act as a user's password, authenticate them to get a new token. Downside is that with this architecture your authentication server needs to persist these refresh token in a database.

New flow (with refresh tokens):

  1. User authenticates with the authentication server (eg: POST /auth/login) and receives a JWT token generated and signed by the auth server, alongside a long lived (eg: 6 months) refresh token that they store securely
  2. Whenever the user needs to make an API request, the token's expiry is checked. Assuming it has not yet expired, user uses that token to talk to your API and assuming user is authorised), gets and posts the necessary resources.
  3. If the token has indeed expired, there is a need to refresh your token, user calls authentication server (EG: POST / auth/token) and passes the securely stored refresh token. Response is a new access token issued.
  4. Use that new token to talk to your API image servers.

OPTIONAL (banning users)

How do we ban users? Using that model there is no easy way to do so. Enhancement: Every persisted refresh token includes a blacklisted field and only issue new tokens if the refresh token isn't black listed.

Things to consider:

  • You may want to rotate refresh token. To do so, blacklist the refresh token each time your user needs a new access token. That way refresh tokens can only be used once. Downside you will end up with a lot more refresh tokens but that can easily be solved with a job that clears blacklisted refresh tokens (eg: once a day)
  • You may want to consider setting a maximum number of allowed refresh tokens issued per user (say 10 or 20) as you issue a new one every time they login (with username and password). This number depends on your flow, how many clients a user may use (web, mobile, etc) and other factors.
  • Logout endpoint in your authentication service may or may not blacklist refresh tokens. Something to think about.

How to inject Javascript in WebBrowser control?

If you need to inject a whole file then you can use this:

With Browser.Document
   Dim Head As HtmlElement = .GetElementsByTagName("head")(0)
   Dim Script As HtmlElement = .CreateElement("script")
   Dim Streamer As New StreamReader(<Here goes path to file as String>)
   Using Streamer
       Script.SetAttribute("text", Streamer.ReadToEnd())
   End Using
   Head.AppendChild(Script)
   .InvokeScript(<Here goes a method name as String and without parentheses>)
End With

Remember to import System.IO in order to use the StreamReader. I hope this helps.

Sqlite convert string to date

I have a database where dates are stored in d F Y format (20 Nov 2017) and to convert it to a machine readable date(Y-m-d) I use this method to update the entire table to a proper format.

If you only want the date formatting look at the inner select how I formatted the date.

update TABLENAME as realTABLE set created_at = (
select 
    -- Get Year
    substr(tmpTABLE.created_at ,-4, 4)
     || '-' ||
     -- Get Month
      substr(
           replace (replace (replace (replace (replace (replace (replace (replace (replace (replace (replace (replace (tmpReis.szAanmaakDatum
           , ' Dec ', '-12-') , ' Nov ', '-11-') , ' Oct ', '-10-') , ' Sep ', '-09-') , ' Aug ', '-08-') , ' Jul ', '-07-') , ' Jun ', '-06-') , ' May ', '-05-') , ' Apr ', '-04-') , ' Mar ', '-03-') , ' Feb ', '-02-') , ' Jan ', '-01-')
           -- Get it from the original space location + 1, then get the two numbers.
           ,instr(tmpTABLE.created_at, ' ')+1, 2)
     || '-' ||
     -- Get day, prepend with a zero if there's a zero lacking.
     substr('00' || tmpTABLE.created_at, -2, 2) as foo
from TABLENAME as tmpTABLE 
where tmpTABLE.id = realTABLE.id    
-- Check for valid matching formats. don't do those that already were converted.
) where created_at like '_ ___ ____' 
or created_at like '__ ___ ____';

Convert an integer to a byte array

What's wrong with converting it to a string?

[]byte(fmt.Sprintf("%d", myint))

How to index an element of a list object in R

Indexing a list is done using double bracket, i.e. hypo_list[[1]] (e.g. have a look here: http://www.r-tutor.com/r-introduction/list). BTW: read.table does not return a table but a dataframe (see value section in ?read.table). So you will have a list of dataframes, rather than a list of table objects. The principal mechanism is identical for tables and dataframes though.

Note: In R, the index for the first entry is a 1 (not 0 like in some other languages).

Dataframes

l <- list(anscombe, iris)   # put dfs in list
l[[1]]             # returns anscombe dataframe

anscombe[1:2, 2]   # access first two rows and second column of dataset
[1] 10  8

l[[1]][1:2, 2]     # the same but selecting the dataframe from the list first
[1] 10  8

Table objects

tbl1 <- table(sample(1:5, 50, rep=T))
tbl2 <- table(sample(1:5, 50, rep=T))
l <- list(tbl1, tbl2)  # put tables in a list

tbl1[1:2]              # access first two elements of table 1 

Now with the list

l[[1]]                 # access first table from the list

1  2  3  4  5 
9 11 12  9  9 

l[[1]][1:2]            # access first two elements in first table

1  2 
9 11 

How to print to console when using Qt

If you are printing to stderr using the stdio library, a call to fflush(stderr) should flush the buffer and get you real-time logging.

How do I use Maven through a proxy?

if you are new to proxy setup for Maven In my case first go and check your Home Folder weather there is .m2 folder and in it there should be a file named settings.xml if not create it , and paste this and change host and port,then if needed change the nonProxyHosts

Home Folder - C:\Users\ {UserName}

<settings>
<proxies>
    <proxy>
        <id>httpproxy</id>
        <active>true</active>
        <protocol>http</protocol>
        <host>your-proxy-host</host>
        <port>your-proxy-port</port>
        <nonProxyHosts>localhost</nonProxyHosts>
    </proxy>
<proxy>
        <id>httpsproxy</id>
        <active>true</active>
        <protocol>https</protocol>
        <host>your-proxy-host</host>
        <port>your-proxy-port</port>
        <nonProxyHosts>localhost</nonProxyHosts>
    </proxy>

</proxies>
</settings>

If any case this does not success go and do the changes in this location of Home Folder

/conf/settings.xml

I am using Eclipse as my IDE
Hope this will help !!

Note: To remove the proxy just move settings.xml to some where else

In HTML5, can the <header> and <footer> tags appear outside of the <body> tag?

I see what you are trying to do, you are trying to use the <body> tag as the container for the main content of the page. Instead, use the <main> tag, as specified in the HTML5 spec. I use this layout:

    <!DOCTYPE html>
    <html>
        <head> *Metadata* </head>
        <body>
            <header>
                *<h1> and other important stuff </h1>*
                <nav> *Usually a formatted <Ul>* </nav>
            </header>
            <main> *All my content* </main>
            <footer> *Copyright, links, social media etc* </footer>
        </body>
    </html>

I'm not 100% sure but I think that anything outside the <body> tag is considered metadata and will not be rendered by the browser. I don't think that the DOM can access it either.

To conclude, use the <main> tag for your content and keep formatting your HTML the correct way as you have in your first code snippet. You used the <section> tag but I think that comes with some weird formatting issues when you try to apply CSS.

bootstrap.min.js:6 Uncaught Error: Bootstrap dropdown require Popper.js

I was facing this issue, then I put my dropdown in nav tag. Worked for me that way.

What is Ad Hoc Query?

Ad hoc queries are those that are not already defined that are not needed on a regular basis, so they're not included in the typical set of reports or queries

How to edit .csproj file

For JetBrains Rider:

First Option

  1. Unload Project
  2. Double click the unloaded project

Second option:

  1. Click on the project
  2. Press F4

That's it!

Which UUID version to use?

If you want a random number, use a random number library. If you want a unique identifier with effectively 0.00...many more 0s here...001% chance of collision, you should use UUIDv1. See Nick's post for UUIDv3 and v5.

UUIDv1 is NOT secure. It isn't meant to be. It is meant to be UNIQUE, not un-guessable. UUIDv1 uses the current timestamp, plus a machine identifier, plus some random-ish stuff to make a number that will never be generated by that algorithm again. This is appropriate for a transaction ID (even if everyone is doing millions of transactions/s).

To be honest, I don't understand why UUIDv4 exists... from reading RFC4122, it looks like that version does NOT eliminate possibility of collisions. It is just a random number generator. If that is true, than you have a very GOOD chance of two machines in the world eventually creating the same "UUID"v4 (quotes because there isn't a mechanism for guaranteeing U.niversal U.niqueness). In that situation, I don't think that algorithm belongs in a RFC describing methods for generating unique values. It would belong in a RFC about generating randomness. For a set of random numbers:

chance_of_collision = 1 - (set_size! / (set_size - tries)!) / (set_size ^ tries)

How does bitshifting work in Java?

00101011 = 43 in decimal

class test {    
    public static void main(String[] args){
       int a= 43;       
       String b= Integer.toBinaryString(a >> 2);        
       System.out.println(b);
    }   
}

Output:

101011 becomes 1010

How to capture a list of specific type with mockito

For an earlier version of junit, you can do

Class<Map<String, String>> mapClass = (Class) Map.class;
ArgumentCaptor<Map<String, String>> mapCaptor = ArgumentCaptor.forClass(mapClass);

Change the bullet color of list

I would recommend you to use background-image instead of default list.

.listStyle {
    list-style: none;
    background: url(image_path.jpg) no-repeat left center;
    padding-left: 30px;
    width: 20px;
    height: 20px;
}

Or, if you don't want to use background-image as bullet, there is an option to do it with pseudo element:

.liststyle{
    list-style: none;
    margin: 0;
    padding: 0;
}
.liststyle:before {
    content: "• ";
    color: red; /* or whatever color you prefer */
    font-size: 20px;/* or whatever the bullet size you prefer */
}

Save bitmap to file function

  1. You need an appropriate permission in manifest.xml:

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    
  2. out.flush() check the out is not null..

  3. String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() + 
                                "/PhysicsSketchpad";
    File dir = new File(file_path);
    if(!dir.exists())
        dir.mkdirs();
    File file = new File(dir, "sketchpad" + pad.t_id + ".png");
    FileOutputStream fOut = new FileOutputStream(file);
    
    bmp.compress(Bitmap.CompressFormat.PNG, 85, fOut);
    fOut.flush();
    fOut.close();
    

How to secure phpMyAdmin

The biggest threat is that an attacker could leverage a vulnerability such as; directory traversal, or using SQL Injection to call load_file() to read the plain text username/password in the configuration file and then Login using phpmyadmin or over tcp port 3306. As a pentester I have used this attack pattern to compromise a system.

Here is a great way to lock down phpmyadmin:

  • DO NOT ALLOW REMOTE ROOT LOGINS! Instead phpmyadmin can be configured to use "Cookie Auth" to limit what user can access the system. If you need some root privileges, create a custom account that can add/drop/create but doesn't have grant or file_priv.
  • Remove file_priv permissions from every account. file_priv is one of the most dangerous privileges in MySQL because it allows an attacker to read files or upload a backdoor.
  • Whitelist IP address who have access to the phpmyadmin interface. Here is an example .htaccess reulset:
Order deny,allow
Deny from all
allow from 199.166.210.1
  • Do not have a predictable file location like: http://127.0.0.1/phpmyadmin. Vulnerability scanners like Nessus/Nikto/Acunetix/w3af will scan for this.

  • Firewall off tcp port 3306 so that it cannot be accessed by an attacker.

  • Use HTTPS, otherwise data and passwords can be leaked to an attacker. If you don't want to fork out the $30 for a cert, then use a self-signed. You'll accept it once, and even if it was changed due to a MITM you'll be notified.

Pure css close button

Hi you can used this code in pure css

as like this

css

.arrow {
cursor: pointer;
color: white;
border: 1px solid #AEAEAE;
border-radius: 30px;
background: #605F61;
font-size: 31px;
font-weight: bold;
display: inline-block;
line-height: 0px;
padding: 11px 3px;
}
.arrow:before{
 content: "×";
}

HTML

<a href="#" class="arrow"> 
</a>

? Live demo http://jsfiddle.net/rohitazad/VzZhU/

Compare two dates in Java

public long compareDates(Date exp, Date today){

        long b = (exp.getTime()-86400000)/86400000;
        long c = (today.getTime()-86400000)/86400000;
        return b-c;
    }

This works for GregorianDates. 86400000 are the amount of milliseconds in a day, this will return the number of days between the two dates.

Resolving tree conflict

Basically, tree conflicts arise if there is some restructure in the folder structure on the branch. You need to delete the conflict folder and use svn clean once. Hope this solves your conflict.

gdb: "No symbol table is loaded"

I met this issue this morning because I used the same executable in DIFFERENT OSes: after compiling my program with gcc -ggdb -Wall test.c -o test in my Mac(10.15.2), I ran gdb with the executable in Ubuntu(16.04) in my VirtualBox.

Fix: recompile with the same command under Ubuntu, then you should be good.

JavaFX How to set scene background image

In addition to @Elltz answer, we can use both fill and image for background:

someNode.setBackground(
            new Background(
                    Collections.singletonList(new BackgroundFill(
                            Color.WHITE, 
                            new CornerRadii(500), 
                            new Insets(10))),
                    Collections.singletonList(new BackgroundImage(
                            new Image("image/logo.png", 100, 100, false, true),
                            BackgroundRepeat.NO_REPEAT,
                            BackgroundRepeat.NO_REPEAT,
                            BackgroundPosition.CENTER,
                            BackgroundSize.DEFAULT))));

Use

setBackground(
                new Background(
                        Collections.singletonList(new BackgroundFill(
                                Color.WHITE,
                                new CornerRadii(0),
                                new Insets(0))),
                        Collections.singletonList(new BackgroundImage(
                                new Image("file:clouds.jpg", 100, 100, false, true),
                                BackgroundRepeat.NO_REPEAT,
                                BackgroundRepeat.NO_REPEAT,
                                BackgroundPosition.DEFAULT,
                                new BackgroundSize(1.0, 1.0, true, true, false, false)
                        ))));

(different last argument) to make the image full-window size.

How to convert a set to a list in python?

[EDITED] It's seems you earlier have redefined "list", using it as a variable name, like this:

list = set([1,2,3,4]) # oops
#...
first_list = [1,2,3,4]
my_set=set(first_list)
my_list = list(my_set)

And you'l get

Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: 'set' object is not callable

Read file content from S3 bucket with boto3

When you want to read a file with a different configuration than the default one, feel free to use either mpu.aws.s3_read(s3path) directly or the copy-pasted code:

def s3_read(source, profile_name=None):
    """
    Read a file from an S3 source.

    Parameters
    ----------
    source : str
        Path starting with s3://, e.g. 's3://bucket-name/key/foo.bar'
    profile_name : str, optional
        AWS profile

    Returns
    -------
    content : bytes

    botocore.exceptions.NoCredentialsError
        Botocore is not able to find your credentials. Either specify
        profile_name or add the environment variables AWS_ACCESS_KEY_ID,
        AWS_SECRET_ACCESS_KEY and AWS_SESSION_TOKEN.
        See https://boto3.readthedocs.io/en/latest/guide/configuration.html
    """
    session = boto3.Session(profile_name=profile_name)
    s3 = session.client('s3')
    bucket_name, key = mpu.aws._s3_path_split(source)
    s3_object = s3.get_object(Bucket=bucket_name, Key=key)
    body = s3_object['Body']
    return body.read()

H2 database error: Database may be already in use: "Locked by another process"

If you are running same app into multiple ports where app uses single database (h2), then add AUTO_SERVER=TRUE in the url as follows:

jdbc:h2:file:C:/simple-commerce/price;DB_CLOSE_ON_EXIT=FALSE;AUTO_RECONNECT=TRUE;AUTO_SERVER=TRUE

Show/hide image with JavaScript

This is working code:

<html>
  <body bgcolor=cyan>
    <img src ="backgr1.JPG" id="my" width="310" height="392" style="position: absolute; top:92px; left:375px; visibility:hidden"/>
    <script type="text/javascript">
      function tend() {
        document.getElementById('my').style.visibility='visible';
      }
      function tn() {
        document.getElementById('my').style.visibility='hidden';
      }
    </script>
    <input type="button" onclick="tend()" value="back">
    <input type="button" onclick="tn()" value="close">
  </body>
</html>

What is the best IDE for C Development / Why use Emacs over an IDE?

I started off by using IDEs, Microsoft or not. Then, while working on QNX some long time ago, I was forced to do with a text editor + compiler/linker. Now I prefer this simple combination––a syntax highlighting editor + C compiler and linker cli + make––to any IDEs, even if environment allows for them.

The reasons are, for me:

  1. it's everywhere. If you program in C, you do have the compiler, and usually you can get yourself an editor. The first thing I do––I get myself nedit on Linux or Notepad++ on Windows. I would go with vi, but GUI editors provide for a better fonts, and that is important when you look at code all day

  2. you can program remotely, via ssh, when you need to. And it does help a lot sometimes to be able to ssh into the target and do some quick things there

  3. it keeps me close to CLI, preferably UNIX/Linux CLI. So all the commands are on my fingertips, and when I need them I don't have to go read a reference book. And UNIX CLI can do things IDEs often can't––because their developers didn't think you'd need them

  4. most importantly, it is very much like seeing the Matrix in raw code. I operate files, so I'm forced to keep them manageable. I'm finding things in my code manually, which makes me keep it simple and organized. I do Config Management explicitly, so I know when I'm synced and how. I know my Makefiles because I write them, and they only do what I tell them to

    (if you wonder if that works in "really big projects"––it does work, and the bigger the project the more performance it gains me)

  5. when people ask me to look at their code, I don't have to learn the IDE they use

Javascript querySelector vs. getElementById

"Better" is subjective.

querySelector is the newer feature.

getElementById is better supported than querySelector.

querySelector is better supported than getElementsByClassName.

querySelector lets you find elements with rules that can't be expressed with getElementById and getElementsByClassName

You need to pick the appropriate tool for any given task.

(In the above, for querySelector read querySelector / querySelectorAll).

What is the size of column of int(11) in mysql in bytes?

4294967295 is the answer, because int(11) shows maximum of 11 digits IMO

How to search for a string in cell array in MATLAB?

Since 2011a, the recommended way is:

booleanIndex = strcmp('KU', strs)

If you want to get the integer index (which you often don't need), you can use:

integerIndex = find(booleanIndex);

strfind is deprecated, so try not to use it.

How to clear Route Caching on server: Laravel 5.2.37

If you are uploading your files through GIT from your local machine then you can use the same command you are using in your local machine while you are connected to your live server using BASH or something like.You can use this as like you use locally.

php artisan cache:clear

php artisan route:cache

It should work.

Most efficient way to get table row count

SELECT id FROM table ORDER BY id DESC LIMIT 1 can returns max id not auto increment id. both are different in some conditions

Find nearest value in numpy array

IF your array is sorted and is very large, this is a much faster solution:

def find_nearest(array,value):
    idx = np.searchsorted(array, value, side="left")
    if idx > 0 and (idx == len(array) or math.fabs(value - array[idx-1]) < math.fabs(value - array[idx])):
        return array[idx-1]
    else:
        return array[idx]

This scales to very large arrays. You can easily modify the above to sort in the method if you can't assume that the array is already sorted. It’s overkill for small arrays, but once they get large this is much faster.

How to check whether java is installed on the computer

Check the installation directories (typically C:\Program Files (x86) or C:\Program Files) for the java folder. If it contains the JRE you have java installed.

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

Here is the best Maven-Environment Setup tutorial for Windows, Unix and Mac Operating systems.

But in the last you have to set value of PATH variable as ";%M2_HOME%\bin" instead of "%M2%", because PATH variable is not able to reduce the value using "%M2%"

Spring MVC - How to return simple String as JSON in Rest Controller

Make simple:

    @GetMapping("/health")
    public ResponseEntity<String> healthCheck() {
        LOG.info("REST request health check");
        return new ResponseEntity<>("{\"status\" : \"UP\"}", HttpStatus.OK);
    }

Downloading images with node.js

var fs = require('fs'),
http = require('http'),
https = require('https');

var Stream = require('stream').Transform;

var downloadImageToUrl = (url, filename, callback) => {

    var client = http;
    if (url.toString().indexOf("https") === 0){
      client = https;
     }

    client.request(url, function(response) {                                        
      var data = new Stream();                                                    

      response.on('data', function(chunk) {                                       
         data.push(chunk);                                                         
      });                                                                         

      response.on('end', function() {                                             
         fs.writeFileSync(filename, data.read());                               
      });                                                                         
   }).end();
};

downloadImageToUrl('https://www.google.com/images/srpr/logo11w.png', 'public/uploads/users/abc.jpg');

How to reset Jenkins security settings from the command line?

A lot of times you wont be having permissions to edit the config.xml file.

The simplest thing would be to take a back of config.xml and delete using sudo command.

Restart the jenkins using the command sudo /etc/init.d/jenkins restart

This will disable all the security in the Jenkins and the login option would disappear

Remove duplicates in the list using linq

Another workaround, not beautiful buy workable.

I have an XML file with an element called "MEMDES" with two attribute as "GRADE" and "SPD" to record the RAM module information. There are lot of dupelicate items in SPD.

So here is the code I use to remove the dupelicated items:

        IEnumerable<XElement> MList =
            from RAMList in PREF.Descendants("MEMDES")
            where (string)RAMList.Attribute("GRADE") == "DDR4"
            select RAMList;

        List<string> sellist = new List<string>();

        foreach (var MEMList in MList)
        {
            sellist.Add((string)MEMList.Attribute("SPD").Value);
        }

        foreach (string slist in sellist.Distinct())
        {
            comboBox1.Items.Add(slist);
        }

JavaScript Form Submit - Confirm or Cancel Submission Dialog Box

A simple inline JavaScript confirm would suffice:

<form onsubmit="return confirm('Do you really want to submit the form?');">

No need for an external function unless you are doing validation, which you can do something like this:

<script>
function validate(form) {

    // validation code here ...


    if(!valid) {
        alert('Please correct the errors in the form!');
        return false;
    }
    else {
        return confirm('Do you really want to submit the form?');
    }
}
</script>
<form onsubmit="return validate(this);">

How to rotate a 3D object on axis three.js?

Just in case...in r52 the method is called setEulerFromRotationMatrix instead of getRotationFromMatrix

Manually type in a value in a "Select" / Drop-down HTML list?

Telerik also has a combo box control. Essentially, it's a textbox with images that when you click on them reveal a panel with a list of predefined options.

http://demos.telerik.com/aspnet-ajax/combobox/examples/overview/defaultcs.aspx

But this is AJAX, so it may have a larger footprint than you want on your website (since you say it's "HTML").

In java how to get substring from a string till a character c?

If your project already uses commons-lang, StringUtils provide a nice method for this purpose:

String filename = "abc.def.ghi";

String start = StringUtils.substringBefore(filename, "."); // returns "abc"

see javadoc [2.6] [3.1]

android edittext onchange listener

 myTextBox.addTextChangedListener(new TextWatcher() {  

    public void afterTextChanged(Editable s) {}  

    public void beforeTextChanged(CharSequence s, int start, int count, int after) {} 

    public void onTextChanged(CharSequence s, int start, int before, int count) {  

    TextView myOutputBox = (TextView) findViewById(R.id.myOutputBox);  
    myOutputBox.setText(s);  

    }  
});  

What is the syntax meaning of RAISERROR()

It is the severity level of the error. The levels are from 11 - 20 which throw an error in SQL. The higher the level, the more severe the level and the transaction should be aborted.

You will get the syntax error when you do:

RAISERROR('Cannot Insert where salary > 1000').

Because you have not specified the correct parameters (severity level or state).

If you wish to issue a warning and not an exception, use levels 0 - 10.

From MSDN:

severity

Is the user-defined severity level associated with this message. When using msg_id to raise a user-defined message created using sp_addmessage, the severity specified on RAISERROR overrides the severity specified in sp_addmessage. Severity levels from 0 through 18 can be specified by any user. Severity levels from 19 through 25 can only be specified by members of the sysadmin fixed server role or users with ALTER TRACE permissions. For severity levels from 19 through 25, the WITH LOG option is required.

state

Is an integer from 0 through 255. Negative values or values larger than 255 generate an error. If the same user-defined error is raised at multiple locations, using a unique state number for each location can help find which section of code is raising the errors. For detailed description here

Unknown version of Tomcat was specified in Eclipse

You are pointing to the source directory. You can run a build by running ant from that same directory, then add '\output\build' to the end of the installation directory path.

Typing the Enter/Return key using Python and Selenium

For everyone using JavaScript / Node.js, this worked for me:

driver.findElement(By.xpath('xpath')).sendKeys('ENTER');

Adding a line break in MySQL INSERT INTO text

You can simply replace all \n with <br/> tag so that when page is displayed then it breaks line.

UPDATE table SET field = REPLACE(field, '\n', '<br/>')

How can I resolve the error: "The command [...] exited with code 1"?

I know this is too late for sure, but, this could help someone as well.

In my case, i found that the source file is being used by another process which was restricting from copying to the destination. I found that by using command prompt ( just copy paste the post build command to the command prompt and executed gave me the error info).

Make sure that you can copy from the command prompt,

How do I load a file from resource folder?

Import the following:

import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.util.ArrayList;

The following method returns a file in an ArrayList of Strings:

public ArrayList<String> loadFile(String filename){

  ArrayList<String> lines = new ArrayList<String>();

  try{

    ClassLoader classloader = Thread.currentThread().getContextClassLoader();
    InputStream inputStream = classloader.getResourceAsStream(filename);
    InputStreamReader streamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
    BufferedReader reader = new BufferedReader(streamReader);
    for (String line; (line = reader.readLine()) != null;) {
      lines.add(line);
    }

  }catch(FileNotFoundException fnfe){
    // process errors
  }catch(IOException ioe){
    // process errors
  }
  return lines;
}

How do I get a list of files in a directory in C++?

You can use the following code for getting all files in a directory.A simple modification in the Andreas Bonini answer to remove the occurance of "." and ".."

CString dirpath="d:\\mydir"
DWORD errVal = ERROR_SUCCESS;
HANDLE dir;
WIN32_FIND_DATA file_data;
CString  file_name,full_file_name;
if ((dir = FindFirstFile((dirname+ "/*"), &file_data)) == INVALID_HANDLE_VALUE)
{
    errVal=ERROR_INVALID_ACCEL_HANDLE;
    return errVal;
}

while (FindNextFile(dir, &file_data)) {
    file_name = file_data.cFileName;
    full_file_name = dirname+ file_name;
    if (strcmp(file_data.cFileName, ".") != 0 && strcmp(file_data.cFileName, "..") != 0)
    {
        m_List.AddTail(full_file_name);
    }
}

How to group dataframe rows into list in pandas groupby

Building upon @B.M answer, here is a more general version and updated to work with newer library version: (numpy version 1.19.2, pandas version 1.2.1) And this solution can also deal with multi-indices:

However this is not heavily tested, use with caution.

If performance is important go down to numpy level:

import pandas as pd
import numpy as np

np.random.seed(0)
df = pd.DataFrame({'a': np.random.randint(0, 10, 90), 'b': [1,2,3]*30, 'c':list('abcefghij')*10, 'd': list('hij')*30})


def f_multi(df,col_names):
    if not isinstance(col_names,list):
        col_names = [col_names]
        
    values = df.sort_values(col_names).values.T

    col_idcs = [df.columns.get_loc(cn) for cn in col_names]
    other_col_names = [name for idx, name in enumerate(df.columns) if idx not in col_idcs]
    other_col_idcs = [df.columns.get_loc(cn) for cn in other_col_names]

    # split df into indexing colums(=keys) and data colums(=vals)
    keys = values[col_idcs,:]
    vals = values[other_col_idcs,:]
    
    # list of tuple of key pairs
    multikeys = list(zip(*keys))
    
    # remember unique key pairs and ther indices
    ukeys, index = np.unique(multikeys, return_index=True, axis=0)
    
    # split data columns according to those indices
    arrays = np.split(vals, index[1:], axis=1)

    # resulting list of subarrays has same number of subarrays as unique key pairs
    # each subarray has the following shape:
    #    rows = number of non-grouped data columns
    #    cols = number of data points grouped into that unique key pair
    
    # prepare multi index
    idx = pd.MultiIndex.from_arrays(ukeys.T, names=col_names) 

    list_agg_vals = dict()
    for tup in zip(*arrays, other_col_names):
        col_vals = tup[:-1] # first entries are the subarrays from above 
        col_name = tup[-1]  # last entry is data-column name
        
        list_agg_vals[col_name] = col_vals

    df2 = pd.DataFrame(data=list_agg_vals, index=idx)
    return df2

Tests:

In [227]: %timeit f_multi(df, ['a','d'])

2.54 ms ± 64.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [228]: %timeit df.groupby(['a','d']).agg(list)

4.56 ms ± 61.5 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)


Results:

for the random seed 0 one would get:

enter image description here

How do I instantiate a JAXBElement<String> object?

Other alternative:

JAXBElement<String> element = new JAXBElement<>(new QName("Your localPart"),
                                                String.class, "Your message");

Then:

System.out.println(element.getValue()); // Result: Your message

What does '--set-upstream' do?

git branch --set-upstream <remote-branch>

sets the default remote branch for the current local branch.

Any future git pull command (with the current local branch checked-out),
will attempt to bring in commits from the <remote-branch> into the current local branch.


One way to avoid having to explicitly type --set-upstream is to use its shorthand flag -u as follows:

git push -u origin local-branch

This sets the upstream association for any future push/pull attempts automatically.
For more details, checkout this detailed explanation about upstream branches and tracking.


To avoid confusion, recent versions of git deprecate this somewhat ambiguous --set-upstream option in favour of a more verbose --set-upstream-to option with identical syntax and behaviour

git branch --set-upstream-to <origin/remote-branch>

How do I add a border to an image in HTML?

Jack,

You can learn a great deal about borders, and how to use them at http://www.w3schools.com/css/css_border.asp. That being said, there are a couple different ways you could accomplish this.

Below is how I generally do it, but reading the documentation on w3schools you may come upon your own desired method.

.addBorder {
  /* Thickness, Style, and Color */
  border: 1px solid #000000;
}

<img src="mypicture.jpg" alt="My Picture" class="addBorder" />

Edit:

I noticed the original question was not "How to add a border to an image," but instead it was "how to add in a box around an image using html?" The question was re-written by others, so I'm not 100% sure you wanted a border on your image.

If you just wanted a box around your images, you could use a DIV, with it's own styles:

.imageBox {
  background-color:#f1f1f1;
  padding:10px;
  border:1px solid #000000;
}

<div class="imageBox">
  <img src="picture.jpg" alt="My Picture" />
</div>