Programs & Examples On #Shaml

Image library for Python 3

Depending on what is needed, scikit-image may be the best choice, with manipulations going way beyond PIL and the current version of Pillow. Very well-maintained, at least as much as Pillow. Also, the underlying data structures are from Numpy and Scipy, which makes its code incredibly interoperable. Examples that pillow can't handle:

Region Adjacency Graph Merging

Radon Transform

Histogram of oriented gradients

Approximate and subdivide polygons

You can see its power in the gallery. This paper provides a great intro to it. Good luck!

How to show a dialog to confirm that the user wishes to exit an Android Activity?

Another alternative would be to show a Toast/Snackbar on the first back press asking to press back again to Exit, which is a lot less intrusive than showing an AlertDialog to confirm if user wants to exit the app.

You can use the DoubleBackPress Android Library to achieve this with a few lines of code. Example GIF showing similar behaviour.

To begin with, add the dependency to your application :

dependencies {
    implementation 'com.github.kaushikthedeveloper:double-back-press:0.0.1'
}

Next, in your Activity, implement the required behaviour.

// set the Toast to be shown on FirstBackPress (ToastDisplay - builtin template)
// can be replaced by custom action (new FirstBackPressAction{...})
FirstBackPressAction firstBackPressAction = new ToastDisplay().standard(this);

// set the Action on DoubleBackPress
DoubleBackPressAction doubleBackPressAction = new DoubleBackPressAction() {
    @Override
    public void actionCall() {
        // TODO : Exit the application
        finish();
        System.exit(0);
    }
};

// setup DoubleBackPress behaviour : close the current Activity
DoubleBackPress doubleBackPress = new DoubleBackPress()
        .withDoublePressDuration(3000)     // msec - wait for second back press
        .withFirstBackPressAction(firstBackPressAction)
        .withDoubleBackPressAction(doubleBackPressAction);

Finally, set this as the behaviour on back press.

@Override
public void onBackPressed() {
    doubleBackPress.onBackPressed();
}

When to use in vs ref vs out

why do you ever want to use out?

To let others know that the variable will be initialized when it returns from the called method!

As mentioned above: "for an out parameter, the calling method is required to assign a value before the method returns."

example:

Car car;
SetUpCar(out car);
car.drive();  // You know car is initialized.

Can you require two form fields to match with HTML5?

The answers that use pattern and a regex write the user's password into the input properties as plain text pattern='mypassword'. This will only be visible if developer tools are open but it still doesn't seem like a good idea.

Another issue with using pattern to check for a match is that you are likely to want to use pattern to check that the password is of the right form, e.g. mixed letters and numbers.

I also think these methods won't work well if the user switches between inputs.

Here's my solution which uses a bit more JavaScript but performs a simple equality check when either input is updated and then sets a custom HTML validity. Both inputs can still be tested for a pattern such as email format or password complexity.

For a real page you would change the input types to 'password'.

<form>
    <input type="text" id="password1" oninput="setPasswordConfirmValidity();">
    <input type="text" id="password2" oninput="setPasswordConfirmValidity();">
</form>
<script>
    function setPasswordConfirmValidity(str) {
        const password1 = document.getElementById('password1');
        const password2 = document.getElementById('password2');

        if (password1.value === password2.value) {
             password2.setCustomValidity('');
        } else {
            password2.setCustomValidity('Passwords must match');
        }
        console.log('password2 customError ', document.getElementById('password2').validity.customError);
        console.log('password2 validationMessage ', document.getElementById('password2').validationMessage);
    }
</script>

How to import JsonConvert in C# application?

If you are developing a .Net Core WebApi or WebSite you dont not need to install newtownsoft.json to perform json serialization/deserealization

Just make sure that your controller method returns a JsonResult and call return Json(<objectoToSerialize>); like this example

namespace WebApi.Controllers
{
    [Produces("application/json")]
    [Route("api/Accounts")]
    public class AccountsController : Controller
    {
        // GET: api/Transaction
        [HttpGet]
        public JsonResult Get()
        {
            List<Account> lstAccounts;

            lstAccounts = AccountsFacade.GetAll();

            return Json(lstAccounts);
        }
    }
}

If you are developing a .Net Framework WebApi or WebSite you need to use NuGet to download and install the newtonsoft json package

"Project" -> "Manage NuGet packages" -> "Search for "newtonsoft json". -> click "install".

namespace WebApi.Controllers
{
    [Produces("application/json")]
    [Route("api/Accounts")]
    public class AccountsController : Controller
    {
        // GET: api/Transaction
        [HttpGet]
        public JsonResult Get()
        {
            List<Account> lstAccounts;

            lstAccounts = AccountsFacade.GetAll();

            //This line is different !! 
            return new JsonConvert.SerializeObject(lstAccounts);
        }
    }
}

More details can be found here - https://docs.microsoft.com/en-us/aspnet/core/web-api/advanced/formatting?view=aspnetcore-2.1

Import and Export Excel - What is the best library?

Check the ExcelPackage project, it uses the Office Open XML file format of Excel 2007, it's lightweight and open source...

C++ Get name of type in template

typeid(T).name() is implementation defined and doesn't guarantee human readable string.

Reading cppreference.com :

Returns an implementation defined null-terminated character string containing the name of the type. No guarantees are given, in particular, the returned string can be identical for several types and change between invocations of the same program.

...

With compilers such as gcc and clang, the returned string can be piped through c++filt -t to be converted to human-readable form.

But in some cases gcc doesn't return right string. For example on my machine I have gcc whith -std=c++11 and inside template function typeid(T).name() returns "j" for "unsigned int". It's so called mangled name. To get real type name, use abi::__cxa_demangle() function (gcc only):

#include <string>
#include <cstdlib>
#include <cxxabi.h>

template<typename T>
std::string type_name()
{
    int status;
    std::string tname = typeid(T).name();
    char *demangled_name = abi::__cxa_demangle(tname.c_str(), NULL, NULL, &status);
    if(status == 0) {
        tname = demangled_name;
        std::free(demangled_name);
    }   
    return tname;
}

What is the best way to ensure only one instance of a Bash script is running?

first test example

[[ $(lsof -t $0| wc -l) > 1 ]] && echo "At least one of $0 is running"

second test example

currsh=$0
currpid=$$
runpid=$(lsof -t $currsh| paste -s -d " ")
if [[ $runpid == $currpid ]]
then
  sleep 11111111111111111
else
  echo -e "\nPID($runpid)($currpid) ::: At least one of \"$currsh\" is running !!!\n"
  false
  exit 1
fi

explanation

"lsof -t" to list all pids of current running scripts named "$0".

Command "lsof" will do two advantages.

  1. Ignore pids which is editing by editor such as vim, because vim edit its mapping file such as ".file.swp".
  2. Ignore pids forked by current running shell scripts, which most "grep" derivative command can't achieve it. Use "pstree -pH pidnum" command to see details about current process forking status.

Node.js heap out of memory

fwiw, finding and fixing a memory hog with something like memwatch might help.

Could not commit JPA transaction: Transaction marked as rollbackOnly

For those who can't (or don't want to) setup a debugger to track down the original exception which was causing the rollback-flag to get set, you can just add a bunch of debug statements throughout your code to find the lines of code which trigger the rollback-only flag:

logger.debug("Is rollbackOnly: " + TransactionAspectSupport.currentTransactionStatus().isRollbackOnly());

Adding this throughout the code allowed me to narrow down the root cause, by numbering the debug statements and looking to see where the above method goes from returning "false" to "true".

Why do I get permission denied when I try use "make" to install something?

The problem is frequently with 'secure' setup of mountpoints, such as /tmp

If they are mounted noexec (check with cat /etc/mtab and or sudo mount) then there is no permission to execute any binaries or build scripts from within the (temporary) folder.

E.g. to remount temporarily:

 sudo mount -o remount,exec /tmp

Or to change permanently, remove noexec in /etc/fstab

How to unpack an .asar file?

From the asar documentation

(the use of npx here is to avoid to install the asar tool globally with npm install -g asar)

Extract the whole archive:

npx asar extract app.asar destfolder 

Extract a particular file:

npx asar extract-file app.asar main.js

PHP Warning: include_once() Failed opening '' for inclusion (include_path='.;C:\xampp\php\PEAR')

It is because you use a relative path.

The easy way to fix this is by using the __DIR__ magic constant, like:

require_once(__DIR__."/initcontrols/config.php");

From the PHP doc:

The directory of the file. If used inside an include, the directory of the included file is returned

git rm - fatal: pathspec did not match any files

using this worked for me

git rm -f --cached <filename>

Using Powershell to stop a service remotely without WMI or remoting

This worked for me, but I used it as start. powershell outputs, waiting for service to finshing starting a few times then finishes and then a get-service on the remote server shows the service started.

**start**-service -inputobject $(get-service -ComputerName remotePC -Name Spooler)

Undefined symbols for architecture i386: _OBJC_CLASS_$_SKPSMTPMessage", referenced from: error

Remember That you can put some macro in any view controller which is calling the files you've already deleted.

The app will not show any errors until you build your app, it will throw the error in compilation phase in .o files.

Remember to delete any MACRO that's calling to files you've already deleted.

Thanks :)

How to implement a Keyword Search in MySQL?

I will explain the method i usally prefer:

First of all you need to take into consideration that for this method you will sacrifice memory with the aim of gaining computation speed. Second you need to have a the right to edit the table structure.

1) Add a field (i usually call it "digest") where you store all the data from the table.

The field will look like:

"n-n1-n2-n3-n4-n5-n6-n7-n8-n9" etc.. where n is a single word

I achieve this using a regular expression thar replaces " " with "-". This field is the result of all the table data "digested" in one sigle string.

2) Use the LIKE statement %keyword% on the digest field:

SELECT * FROM table WHERE digest LIKE %keyword%

you can even build a qUery with a little loop so you can search for multiple keywords at the same time looking like:

SELECT * FROM table WHERE 
 digest LIKE %keyword1% AND 
 digest LIKE %keyword2% AND 
 digest LIKE %keyword3% ... 

Ideal way to cancel an executing AsyncTask

The only way to do it is by checking the value of the isCancelled() method and stopping playback when it returns true.

Matplotlib legends in subplot

This should work:

ax1.plot(xtr, color='r', label='HHZ 1')
ax1.legend(loc="upper right")
ax2.plot(xtr, color='r', label='HHN')
ax2.legend(loc="upper right")
ax3.plot(xtr, color='r', label='HHE')
ax3.legend(loc="upper right")

Check if inputs are empty using jQuery

Consider using the jQuery validation plugin instead. It may be slightly overkill for simple required fields, but it mature enough that it handles edge cases you haven't even thought of yet (nor would any of us until we ran into them).

You can tag the required fields with a class of "required", run a $('form').validate() in $(document).ready() and that's all it takes.

It's even hosted on the Microsoft CDN too, for speedy delivery: http://www.asp.net/ajaxlibrary/CDN.ashx

How to automatically select all text on focus in WPF TextBox?

Don't know why it loses the selection in the GotFocus event.

But one solution is to do the selection on the GotKeyboardFocus and the GotMouseCapture events. That way it will always work.

How do I convert NSInteger to NSString datatype?

The answer is given but think that for some situation this will be also interesting way to get string from NSInteger

NSInteger value = 12;
NSString * string = [NSString stringWithFormat:@"%0.0f", (float)value];

Multiple try codes in one block

Extract (refactor) your statements. And use the magic of and and or to decide when to short-circuit.

def a():
    try: # a code
    except: pass # or raise
    else: return True

def b():
    try: # b code
    except: pass # or raise
    else: return True

def c():
    try: # c code
    except: pass # or raise
    else: return True

def d():
    try: # d code
    except: pass # or raise
    else: return True

def main():   
    try:
        a() and b() or c() or d()
    except:
        pass

Create directories using make file

In my opinion, directories should not be considered targets of your makefile, either in technical or in design sense. You should create files and if a file creation needs a new directory then quietly create the directory within the rule for the relevant file.

If you're targeting a usual or "patterned" file, just use make's internal variable $(@D), that means "the directory the current target resides in" (cmp. with $@ for the target). For example,

$(OUT_O_DIR)/%.o: %.cpp
        @mkdir -p $(@D)
        @$(CC) -c $< -o $@

title: $(OBJS)

Then, you're effectively doing the same: create directories for all $(OBJS), but you'll do it in a less complicated way.

The same policy (files are targets, directories never are) is used in various applications. For example, git revision control system doesn't store directories.


Note: If you're going to use it, it might be useful to introduce a convenience variable and utilize make's expansion rules.

dir_guard=@mkdir -p $(@D)

$(OUT_O_DIR)/%.o: %.cpp
        $(dir_guard)
        @$(CC) -c $< -o $@

$(OUT_O_DIR_DEBUG)/%.o: %.cpp
        $(dir_guard)
        @$(CC) -g -c $< -o $@

title: $(OBJS)

The server response was: 5.7.0 Must issue a STARTTLS command first. i16sm1806350pag.18 - gsmtp

"https://www.google.com/settings/security/lesssecureapps" use this link after log in your gmail account and click turn on.Then run your application,it will work surely.

How do I add a library (android-support-v7-appcompat) in IntelliJ IDEA

Using Gradle

If you are using Gradle, you can add it as a compile dependency.

Instructions

  1. Make sure you have the Android Support Repository SDK package installed. Android Studio automatically recognizes this repository during the build process (not sure about plain IntelliJ).

    Android Support Repository

  2. Add the dependency to {project}/build.gradle

    dependencies {
        compile 'com.android.support:appcompat-v7:+'
    }
    
  3. Click the Sync Project with Gradle Files button.

EDIT: Looks like these same instructions are on the documentation under Adding libraries with resources -> Using Android Studio.

How to zoom in/out an UIImage object when user pinches screen?

As others described, the easiest solution is to put your UIImageView into a UIScrollView. I did this in the Interface Builder .xib file.

In viewDidLoad, set the following variables. Set your controller to be a UIScrollViewDelegate.

- (void)viewDidLoad {
    [super viewDidLoad];
    self.scrollView.minimumZoomScale = 0.5;
    self.scrollView.maximumZoomScale = 6.0;
    self.scrollView.contentSize = self.imageView.frame.size;
    self.scrollView.delegate = self;
}

You are required to implement the following method to return the imageView you want to zoom.

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return self.imageView;
}

In versions prior to iOS9, you may also need to add this empty delegate method:

- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale
{
}

The Apple Documentation does a good job of describing how to do this:

SQL Server: how to create a stored procedure

Try this:

 create procedure dept_count(@dept_name varchar(20),@d_count int)
       begin
         set @d_count=(select count(*)
                       from instructor
                        where instructor.dept_name=dept_count.dept_name)
         Select @d_count as count
       end

Or

create procedure dept_count(@dept_name varchar(20))
           begin
            select count(*)
                           from instructor
                            where instructor.dept_name=dept_count.dept_name
           end

Why does JPA have a @Transient annotation?

If you just want a field won't get persisted, both transient and @Transient work. But the question is why @Transient since transient already exists.

Because @Transient field will still get serialized!

Suppose you create a entity, doing some CPU-consuming calculation to get a result and this result will not save in database. But you want to sent the entity to other Java applications to use by JMS, then you should use @Transient, not the JavaSE keyword transient. So the receivers running on other VMs can save their time to re-calculate again.

java.util.regex - importance of Pattern.compile()?

Pattern.compile() allow to reuse a regex multiple times (it is threadsafe). The performance benefit can be quite significant.

I did a quick benchmark:

    @Test
    public void recompile() {
        var before = Instant.now();
        for (int i = 0; i < 1_000_000; i++) {
            Pattern.compile("ab").matcher("abcde").matches();
        }
        System.out.println("recompile " + Duration.between(before, Instant.now()));
    }

    @Test
    public void compileOnce() {
        var pattern = Pattern.compile("ab");
        var before = Instant.now();
        for (int i = 0; i < 1_000_000; i++) {
            pattern.matcher("abcde").matches();
        }
        System.out.println("compile once " + Duration.between(before, Instant.now()));
    }

compileOnce was between 3x and 4x faster. I guess it highly depends on the regex itself but for a regex that is often used, I go for a static Pattern pattern = Pattern.compile(...)

ConnectionTimeout versus SocketTimeout

A connection timeout occurs only upon starting the TCP connection. This usually happens if the remote machine does not answer. This means that the server has been shut down, you used the wrong IP/DNS name, wrong port or the network connection to the server is down.

A socket timeout is dedicated to monitor the continuous incoming data flow. If the data flow is interrupted for the specified timeout the connection is regarded as stalled/broken. Of course this only works with connections where data is received all the time.

By setting socket timeout to 1 this would require that every millisecond new data is received (assuming that you read the data block wise and the block is large enough)!

If only the incoming stream stalls for more than a millisecond you are running into a timeout.

Can constructors be async?

if you make constructor asynchronous, after creating an object, you may fall into problems like null values instead of instance objects. For instance;

MyClass instance = new MyClass();
instance.Foo(); // null exception here

That's why they don't allow this i guess.

Convert tabs to spaces in Notepad++

Follow this procedure to convert spaces to tabs or vice-versa:

Space - Tab

urlencode vs rawurlencode?

urlencode: This differs from the » RFC 1738 encoding (see rawurlencode()) in that for historical reasons, spaces are encoded as plus (+) signs.

Best practice for storing and protecting private API keys in applications

Keep the secret in firebase database and get from it when app starts , It is far better than calling a web service .

Python function overloading

The @overload decorator was added with type hints (PEP 484).

While this doesn't change the behaviour of Python, it does make it easier to understand what is going on, and for mypy to detect errors.

See: Type hints and PEP 484

Convert a String to a byte array and then back to the original String

import java.io.FileInputStream; import java.io.ByteArrayOutputStream;

public class FileHashStream { // write a new method that will provide a new Byte array, and where this generally reads from an input stream

public static byte[] read(InputStream is) throws Exception
{
    String path = /* type in the absolute path for the 'commons-codec-1.10-bin.zip' */;

    // must need a Byte buffer

    byte[] buf = new byte[1024 * 16]

    // we will use 16 kilobytes

    int len = 0;

    // we need a new input stream

    FileInputStream is = new FileInputStream(path);

    // use the buffer to update our "MessageDigest" instance

    while(true)
    {
        len = is.read(buf);
        if(len < 0) break;
        md.update(buf, 0, len);
    }

    // close the input stream

    is.close();

    // call the "digest" method for obtaining the final hash-result

    byte[] ret = md.digest();

    System.out.println("Length of Hash: " + ret.length);

    for(byte b : ret)
    {
        System.out.println(b + ", ");
    }

    String compare = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d";

    String verification = Hex.encodeHexString(ret);

    System.out.println();

    System.out.println("===")

    System.out.println(verification);

    System.out.println("Equals? " + verification.equals(compare));

}

}

Jenkins fails when running "service start jenkins"

In my case, the port 8080 was taken by some other service (Apache Airflow).

So I edit the HTTP port in this file:

sudo vi /etc/default/jenkins

And then started the service and it worked:

sudo service jenkins start

I was on Ubuntu 18.04 and installed openjdk-8

Filtering JSON array using jQuery grep()

var data = {
    "items": [{
        "id": 1,
        "category": "cat1"
    }, {
        "id": 2,
        "category": "cat2"
    }, {
        "id": 3,
        "category": "cat1"
    }]
};

var returnedData = $.grep(data.items, function (element, index) {
    return element.id == 1;
});


alert(returnedData[0].id + "  " + returnedData[0].category);

The returnedData is returning an array of objects, so you can access it by array index.

http://jsfiddle.net/wyfr8/913/

JSON find in JavaScript

Zapping - you can use this javascript lib; DefiantJS. There is no need to restructure JSON data into objects to ease searching. Instead, you can search the JSON structure with an XPath expression like this:

    var data = [
   {
      "id": "one",
      "pId": "foo1",
      "cId": "bar1"
   },
   {
      "id": "two",
      "pId": "foo2",
      "cId": "bar2"
   },
   {
      "id": "three",
      "pId": "foo3",
      "cId": "bar3"
   }
],
res = JSON.search( data, '//*[id="one"]' );

console.log( res[0].cId );
// 'bar1'

DefiantJS extends the global object JSON with a new method; "search" which returns array with the matches (empty array if none were found). You can try it out yourself by pasting your JSON data and testing different XPath queries here:

http://www.defiantjs.com/#xpath_evaluator

XPath is, as you know, a standardised query language.

How to create an HTTPS server in Node.js?

Found this question while googling "node https" but the example in the accepted answer is very old - taken from the docs of the current (v0.10) version of node, it should look like this:

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

var options = {
  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
};

https.createServer(options, function (req, res) {
  res.writeHead(200);
  res.end("hello world\n");
}).listen(8000);

Getting path relative to the current working directory?

Thanks to the other answers here and after some experimentation I've created some very useful extension methods:

public static string GetRelativePathFrom(this FileSystemInfo to, FileSystemInfo from)
{
    return from.GetRelativePathTo(to);
}

public static string GetRelativePathTo(this FileSystemInfo from, FileSystemInfo to)
{
    Func<FileSystemInfo, string> getPath = fsi =>
    {
        var d = fsi as DirectoryInfo;
        return d == null ? fsi.FullName : d.FullName.TrimEnd('\\') + "\\";
    };

    var fromPath = getPath(from);
    var toPath = getPath(to);

    var fromUri = new Uri(fromPath);
    var toUri = new Uri(toPath);

    var relativeUri = fromUri.MakeRelativeUri(toUri);
    var relativePath = Uri.UnescapeDataString(relativeUri.ToString());

    return relativePath.Replace('/', Path.DirectorySeparatorChar);
}

Important points:

  • Use FileInfo and DirectoryInfo as method parameters so there is no ambiguity as to what is being worked with. Uri.MakeRelativeUri expects directories to end with a trailing slash.
  • DirectoryInfo.FullName doesn't normalize the trailing slash. It outputs whatever path was used in the constructor. This extension method takes care of that for you.

How to have the formatter wrap code with IntelliJ?

Do you mean that the formatter does not break long lines? Check Settings / Project Settings / Code Style / Wrapping.

Update: in later versions of IntelliJ, the option is under Settings / Editor / Code Style. And select Wrap when typing reaches right margin.

Python Math - TypeError: 'NoneType' object is not subscriptable

lista = list.sort(lista)

This should be

lista.sort()

The .sort() method is in-place, and returns None. If you want something not in-place, which returns a value, you could use

sorted_list = sorted(lista)

Aside #1: please don't call your lists list. That clobbers the builtin list type.

Aside #2: I'm not sure what this line is meant to do:

print str("value 1a")+str(" + ")+str("value 2")+str(" = ")+str("value 3a ")+str("value 4")+str("\n")

is it simply

print "value 1a + value 2 = value 3a value 4"

? In other words, I don't know why you're calling str on things which are already str.

Aside #3: sometimes you use print("something") (Python 3 syntax) and sometimes you use print "something" (Python 2). The latter would give you a SyntaxError in py3, so you must be running 2.*, in which case you probably don't want to get in the habit or you'll wind up printing tuples, with extra parentheses. I admit that it'll work well enough here, because if there's only one element in the parentheses it's not interpreted as a tuple, but it looks strange to the pythonic eye..


The exception TypeError: 'NoneType' object is not subscriptable happens because the value of lista is actually None. You can reproduce TypeError that you get in your code if you try this at the Python command line:

None[0]

The reason that lista gets set to None is because the return value of list.sort() is None... it does not return a sorted copy of the original list. Instead, as the documentation points out, the list gets sorted in-place instead of a copy being made (this is for efficiency reasons).

If you do not want to alter the original version you can use

other_list = sorted(lista)

How do I fix maven error The JAVA_HOME environment variable is not defined correctly?

Following steps solved the issue for me..

  • Copied the zip file into the Program Files folder and extracted to "apache-maven-3.6.3-bin".

  • Then copied the path, C:\Program Files\apache-maven-3.6.3-bin\apache-maven-3.6.3

  • Then created the new MAVEN_HOME variable within environmental variables with the above path.

Also added,

C:\Program Files\apache-maven-3.6.3-bin\apache-maven-3.6.3\bin

address to the "PATH" variable

Bootstrap col-md-offset-* not working

For now, If you want to move a column over just 4 column units for instance, I would suggest to use just a dummy placeholder like in my example below

<div class="row">
      <div class="col-md-4">Offset 4 column</div>
      <div class="col-md-8">
            //content
      </div>
</div>

Is there Unicode glyph Symbol to represent "Search"

Use the ? symbol (encoded as &#9906; or &#x26B2;), and rotate it to achieve the desired effect:

<div style="-webkit-transform: rotate(45deg); 
               -moz-transform: rotate(45deg); 
                 -o-transform: rotate(45deg);
                    transform: rotate(45deg);">
    &#9906;
</div>

It rotates a symbol :)

Form Validation With Bootstrap (jQuery)

I had your code setup on jsFiddle to try diagnose the problem.

http://jsfiddle.net/5WMff/

However, I don't seem to encounter your issue. Could you take a look and let us know?

HTML

<div class="hero-unit">
 <h1>Contact Form</h1> 
</br>
<form method="POST" action="contact-form-submission.php" class="form-horizontal" id="contact-form">
    <div class="control-group">
        <label class="control-label" for="name">Name</label>
        <div class="controls">
            <input type="text" name="name" id="name" placeholder="Your name">
        </div>
    </div>
    <div class="control-group">
        <label class="control-label" for="email">Email Address</label>
        <div class="controls">
            <input type="text" name="email" id="email" placeholder="Your email address">
        </div>
    </div>
    <div class="control-group">
        <label class="control-label" for="subject">Subject</label>
        <div class="controls">
            <select id="subject" name="subject">
                <option value="na" selected="">Choose One:</option>
                <option value="service">Feedback</option>
                <option value="suggestions">Suggestion</option>
                <option value="support">Question</option>
                <option value="other">Other</option>
            </select>
        </div>
    </div>
    <div class="control-group">
        <label class="control-label" for="message">Message</label>
        <div class="controls">
            <textarea name="message" id="message" rows="8" class="span5" placeholder="The message you want to send to us."></textarea>
        </div>
    </div>
    <div class="form-actions">
        <input type="hidden" name="save" value="contact">
        <button type="submit" class="btn btn-success">Submit Message</button>
        <button type="reset" class="btn">Cancel</button>
    </div>
</form>

Javascript

$(document).ready(function () {

$('#contact-form').validate({
    rules: {
        name: {
            minlength: 2,
            required: true
        },
        email: {
            required: true,
            email: true
        },
        message: {
            minlength: 2,
            required: true
        }
    },
    highlight: function (element) {
        $(element).closest('.control-group').removeClass('success').addClass('error');
    },
    success: function (element) {
        element.text('OK!').addClass('valid')
            .closest('.control-group').removeClass('error').addClass('success');
    }
});
});

What is the difference between DAO and Repository patterns?

The key difference is that a repository handles the access to the aggregate roots in a an aggregate, while DAO handles the access to entities. Therefore, it's common that a repository delegates the actual persistence of the aggregate roots to a DAO. Additionally, as the aggregate root must handle the access of the other entities, then it may need to delegate this access to other DAOs.

No content to map due to end-of-input jackson parser

In my case the problem was caused by my passing a null InputStream to the ObjectMapper.readValue call:

ObjectMapper objectMapper = ...
InputStream is = null; // The code here was returning null.
Foo foo = objectMapper.readValue(is, Foo.class)

I am guessing that this is the most common reason for this exception.

Android Bitmap to Base64 String

use following method to convert bitmap to byte array:

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();  
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream .toByteArray();

to encode base64 from byte array use following method

String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);

Import Maven dependencies in IntelliJ IDEA

When you create a new project you simply need to choose the option:

...
Import project from external model
Create IDEA project structure over existing external model (Eclipse, Maven...)
...

You'll find it pretty straight forward from there.
And in your case you can close your project and simply create a new one. Choose your project's directory, which will override it, making it a Maven project.

Java: How to access methods from another class

You either need to create an object of type Beta in the Alpha class or its method

Like you do here in the Main Beta cBeta = new Beta();

If you want to use the variable you create in your Main then you have to parse it to cAlpha as a parameter by making the Alpha constructor look like

public class Alpha 
{

    Beta localInstance;

    public Alpha(Beta _beta)
    {
        localInstance = _beta;
    }


     public void DoSomethingAlpha() 
     {
          localInstance.DoSomethingAlpha();     
     }
}

Efficient way to Handle ResultSet in Java

  1. Iterate over the ResultSet
  2. Create a new Object for each row, to store the fields you need
  3. Add this new object to ArrayList or Hashmap or whatever you fancy
  4. Close the ResultSet, Statement and the DB connection

Done

EDIT: now that you have posted code, I have made a few changes to it.

public List resultSetToArrayList(ResultSet rs) throws SQLException{
  ResultSetMetaData md = rs.getMetaData();
  int columns = md.getColumnCount();
  ArrayList list = new ArrayList(50);
  while (rs.next()){
     HashMap row = new HashMap(columns);
     for(int i=1; i<=columns; ++i){           
      row.put(md.getColumnName(i),rs.getObject(i));
     }
      list.add(row);
  }

 return list;
}

How to make a input field readonly with JavaScript?

The above answers did not work for me. The below does: document.getElementById("input_field_id").setAttribute("readonly", true);

And to remove the readonly attribute: document.getElementById("input_field_id").removeAttribute("readonly");

And for running when the page is loaded, it is worth referring to here.

Import CSV into SQL Server (including automatic table creation)

SQL Server Management Studio provides an Import/Export wizard tool which have an option to automatically create tables.

You can access it by right clicking on the Database in Object Explorer and selecting Tasks->Import Data...

From there wizard should be self-explanatory and easy to navigate. You choose your CSV as source, desired destination, configure columns and run the package.

If you need detailed guidance, there are plenty of guides online, here is a nice one: http://www.mssqltips.com/sqlservertutorial/203/simple-way-to-import-data-into-sql-server/

How to stop VBA code running?

Add another button called "CancelButton" that sets a flag, and then check for that flag.

If you have long loops in the "stuff" then check for it there too and exit if it's set. Use DoEvents inside long loops to ensure that the UI works.

Bool Cancel
Private Sub CancelButton_OnClick()
    Cancel=True
End Sub
...
Private Sub SomeVBASub
    Cancel=False
    DoStuff
    If Cancel Then Exit Sub
    DoAnotherStuff
    If Cancel Then Exit Sub
    AndFinallyDothis
End Sub

pandas create new column based on values from other columns / apply a function of multiple columns, row-wise

try this,

df.loc[df['eri_white']==1,'race_label'] = 'White'
df.loc[df['eri_hawaiian']==1,'race_label'] = 'Haw/Pac Isl.'
df.loc[df['eri_afr_amer']==1,'race_label'] = 'Black/AA'
df.loc[df['eri_asian']==1,'race_label'] = 'Asian'
df.loc[df['eri_nat_amer']==1,'race_label'] = 'A/I AK Native'
df.loc[(df['eri_afr_amer'] + df['eri_asian'] + df['eri_hawaiian'] + df['eri_nat_amer'] + df['eri_white']) > 1,'race_label'] = 'Two Or More'
df.loc[df['eri_hispanic']==1,'race_label'] = 'Hispanic'
df['race_label'].fillna('Other', inplace=True)

O/P:

     lname   fname rno_cd  eri_afr_amer  eri_asian  eri_hawaiian  \
0      MOST    JEFF      E             0          0             0   
1    CRUISE     TOM      E             0          0             0   
2      DEPP  JOHNNY    NaN             0          0             0   
3     DICAP     LEO    NaN             0          0             0   
4    BRANDO  MARLON      E             0          0             0   
5     HANKS     TOM    NaN             0          0             0   
6    DENIRO  ROBERT      E             0          1             0   
7    PACINO      AL      E             0          0             0   
8  WILLIAMS   ROBIN      E             0          0             1   
9  EASTWOOD   CLINT      E             0          0             0   

   eri_hispanic  eri_nat_amer  eri_white rno_defined    race_label  
0             0             0          1       White         White  
1             1             0          0       White      Hispanic  
2             0             0          1     Unknown         White  
3             0             0          1     Unknown         White  
4             0             0          0       White         Other  
5             0             0          1     Unknown         White  
6             0             0          1       White   Two Or More  
7             0             0          1       White         White  
8             0             0          0       White  Haw/Pac Isl.  
9             0             0          1       White         White 

use .loc instead of apply.

it improves vectorization.

.loc works in simple manner, mask rows based on the condition, apply values to the freeze rows.

for more details visit, .loc docs

Performance metrics:

Accepted Answer:

def label_race (row):
   if row['eri_hispanic'] == 1 :
      return 'Hispanic'
   if row['eri_afr_amer'] + row['eri_asian'] + row['eri_hawaiian'] + row['eri_nat_amer'] + row['eri_white'] > 1 :
      return 'Two Or More'
   if row['eri_nat_amer'] == 1 :
      return 'A/I AK Native'
   if row['eri_asian'] == 1:
      return 'Asian'
   if row['eri_afr_amer']  == 1:
      return 'Black/AA'
   if row['eri_hawaiian'] == 1:
      return 'Haw/Pac Isl.'
   if row['eri_white'] == 1:
      return 'White'
   return 'Other'

df=pd.read_csv('dataser.csv')
df = pd.concat([df]*1000)

%timeit df.apply(lambda row: label_race(row), axis=1)

1.15 s ± 46.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

My Proposed Answer:

def label_race(df):
    df.loc[df['eri_white']==1,'race_label'] = 'White'
    df.loc[df['eri_hawaiian']==1,'race_label'] = 'Haw/Pac Isl.'
    df.loc[df['eri_afr_amer']==1,'race_label'] = 'Black/AA'
    df.loc[df['eri_asian']==1,'race_label'] = 'Asian'
    df.loc[df['eri_nat_amer']==1,'race_label'] = 'A/I AK Native'
    df.loc[(df['eri_afr_amer'] + df['eri_asian'] + df['eri_hawaiian'] + df['eri_nat_amer'] + df['eri_white']) > 1,'race_label'] = 'Two Or More'
    df.loc[df['eri_hispanic']==1,'race_label'] = 'Hispanic'
    df['race_label'].fillna('Other', inplace=True)
df=pd.read_csv('s22.csv')
df = pd.concat([df]*1000)

%timeit label_race(df)

24.7 ms ± 1.7 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

Is there an opposite of include? for Ruby Arrays?

Try something like this:

@players.include?(p.name) ? false : true

How can I find the number of arguments of a Python function?

As other answers suggest, getargspec works well as long as the thing being queried is actually a function. It does not work for built-in functions such as open, len, etc, and will throw an exception in such cases:

TypeError: <built-in function open> is not a Python function

The below function (inspired by this answer) demonstrates a workaround. It returns the number of args expected by f:

from inspect import isfunction, getargspec
def num_args(f):
  if isfunction(f):
    return len(getargspec(f).args)
  else:
    spec = f.__doc__.split('\n')[0]
    args = spec[spec.find('(')+1:spec.find(')')]
    return args.count(',')+1 if args else 0

The idea is to parse the function spec out of the __doc__ string. Obviously this relies on the format of said string so is hardly robust!

How do I render a shadow?

All About margins

this works in Android, but did not test it in ios

import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import { View, Platform } from 'react-native'
import EStyleSheet from 'react-native-extended-stylesheet'

const styles = EStyleSheet.create({
    wrapper: {
        margin: '-1.4rem'
    },
    shadow: {
        padding: '1.4rem',
        margin: '1.4rem',
        borderRadius: 4,
        borderWidth: 0,
        borderColor: 'transparent',
        ...Platform.select({
            ios: {
                shadowColor: 'rgba(0,0,0, 0.4)',
                shadowOffset: { height: 1, width: 1 },
                shadowOpacity: 0.7,
                shadowRadius: '1.4rem'
            },
            android: {
                elevation: '1.4rem'
            }
        })
    },
    container: {
        padding: 10,
        margin: '-1.4rem',
        borderRadius: 4,
        borderWidth: 0,
        borderColor: '#Fff',
        backgroundColor: '#fff'
    }
})

class ShadowWrapper extends PureComponent {
    static propTypes = {
        children: PropTypes.oneOfType([
            PropTypes.element,
            PropTypes.node,
            PropTypes.arrayOf(PropTypes.element)
        ]).isRequired
    }

    render () {
        return (
            View style={styles.wrapper}
                View style={styles.shadow}
                    View style={styles.container}
                        {this.props.children}
                    View
                View
            View
        )
    }
}

export default ShadowWrapper

How a thread should close itself in Java?

If you're at the top level - or able to cleanly get to the top level - of the thread, then just returning is nice. Throwing an exception isn't as clean, as you need to be able to check that nothing's going to catch the exception and ignore it.

The reason you need to use Thread.currentThread() in order to call interrupt() is that interrupt() is an instance method - you need to call it on the thread you want to interrupt, which in your case happens to be the current thread. Note that the interruption will only be noticed the next time the thread would block (e.g. for IO or for a monitor) anyway - it doesn't mean the exception is thrown immediately.

How to delete the first row of a dataframe in R?

I am not expert, but this may work as well,

dat <- dat[2:nrow(dat), ]

Calling a stored procedure in Oracle with IN and OUT parameters

If you set the server output in ON mode before the entire code, it works, otherwise put_line() will not work. Try it!

The code is,

set serveroutput on;
CREATE OR REPLACE PROCEDURE PROC1(invoicenr IN NUMBER, amnt OUT NUMBER)
AS BEGIN
SELECT AMOUNT INTO amnt FROM INVOICE WHERE INVOICE_NR = invoicenr;
END;

And then call the function as it is:

DECLARE
amount NUMBER;
BEGIN
PROC1(1000001, amount);
dbms_output.put_line(amount);
END;

What difference does .AsNoTracking() make?

AsNoTracking() allows the "unique key per record" requirement in EF to be bypassed (not mentioned explicitly by other answers).

This is extremely helpful when reading a View that does not support a unique key because perhaps some fields are nullable or the nature of the view is not logically indexable.

For these cases the "key" can be set to any non-nullable column but then AsNoTracking() must be used with every query else records (duplicate by key) will be skipped.

How to empty a redis database?

Be careful here.

FlushDB deletes all keys in the current database while FlushALL deletes all keys in all databases on the current host.

App.Config file in console application C#

For .NET Core, add System.Configuration.ConfigurationManager from NuGet manager.
And read appSetting from App.config

<appSettings>
  <add key="appSetting1" value="1000" />
</appSettings>

Add System.Configuration.ConfigurationManager from NuGet Manager

enter image description here

ConfigurationManager.AppSettings.Get("appSetting1")

No connection could be made because the target machine actively refused it 127.0.0.1:3446

You don't have to restart the PC. Restart IIS instead.

Run -> 'cmd'(as admin) and type "iisreset"

How to display .svg image using swift

In case you want to use a WKWebView to load a .svg image that is coming from a URLRequest, you can simply achieve it like this:

Swift 4

if let request = URLRequest(url: urlString), let svgString = try? String(contentsOf: request) {
  wkWebView.loadHTMLString(svgString, baseURL: request)
}

It's much simpler than the other ways of doing it, and you can also persist your .svg string somewhere to load it later, even offline if you need to.

Common MySQL fields and their appropriate data types

Since you're going to be dealing with data of a variable length (names, email addresses), then you'd be wanting to use VARCHAR. The amount of space taken up by a VARCHAR field is [field length] + 1 bytes, up to max length 255, so I wouldn't worry too much about trying to find a perfect size. Take a look at what you'd imagine might be the longest length might be, then double it and set that as your VARCHAR limit. That said...:

I generally set email fields to be VARCHAR(100) - i haven't come up with a problem from that yet. Names I set to VARCHAR(50).

As the others have said, phone numbers and zip/postal codes are not actually numeric values, they're strings containing the digits 0-9 (and sometimes more!), and therefore you should treat them as a string. VARCHAR(20) should be well sufficient.

Note that if you were to store phone numbers as integers, many systems will assume that a number starting with 0 is an octal (base 8) number! Therefore, the perfectly valid phone number "0731602412" would get put into your database as the decimal number "124192010"!!

Google Maps API v3 adding an InfoWindow to each marker

I had a similar problem. If all you want is for some info to be displayed when you hover over a marker, instead of clicking it, then I found that a good alternative to using an info Window was to set a title on the marker. That way whenever you hover the mouse over the marker the title displays like an ALT tag. 'marker.setTitle('Marker '+id);' It removes the need to create a listener for the marker too

Intellij idea subversion checkout error: `Cannot run program "svn"`

For me, on Debian GNU / Linux, installing the subversion package was the solution

# aptitude install subversion subversion-tool

Redirect from an HTML page

I found a problem while working with a jQuery Mobile application, where in some cases my Meta header tag wouldn't achieve a redirection properly (jQuery Mobile doesn't read headers automatically for each page so putting JavaScript there is also ineffective unless wrapping it in complexity). I found the easiest solution in this case was to put the JavaScript redirection directly into the body of the document, as follows:

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta http-equiv="refresh" content="0;url=myURL" />
    </head>

    <body>
        <p>You are not logged in!</p>
        <script language="javascript">
            window.location = "myURL";
        </script>
    </body>
</html>

This seems to work in every case for me.

Ways to implement data versioning in MongoDB

The first big question when diving in to this is "how do you want to store changesets"?

  1. Diffs?
  2. Whole record copies?

My personal approach would be to store diffs. Because the display of these diffs is really a special action, I would put the diffs in a different "history" collection.

I would use the different collection to save memory space. You generally don't want a full history for a simple query. So by keeping the history out of the object you can also keep it out of the commonly accessed memory when that data is queried.

To make my life easy, I would make a history document contain a dictionary of time-stamped diffs. Something like this:

{
    _id : "id of address book record",
    changes : { 
                1234567 : { "city" : "Omaha", "state" : "Nebraska" },
                1234568 : { "city" : "Kansas City", "state" : "Missouri" }
               }
}

To make my life really easy, I would make this part of my DataObjects (EntityWrapper, whatever) that I use to access my data. Generally these objects have some form of history, so that you can easily override the save() method to make this change at the same time.

UPDATE: 2015-10

It looks like there is now a spec for handling JSON diffs. This seems like a more robust way to store the diffs / changes.

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

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

Declare variable in table valued function

There are two flavors of table valued functions. One that is just a select statement and one that can have more rows than just a select statement.

This can not have a variable:

create function Func() returns table
as
return
select 10 as ColName

You have to do like this instead:

create function Func()
returns @T table(ColName int)
as
begin
  declare @Var int
  set @Var = 10
  insert into @T(ColName) values (@Var)
  return
end

Select entries between dates in doctrine 2

You can do either…

$qb->where('e.fecha BETWEEN :monday AND :sunday')
   ->setParameter('monday', $monday->format('Y-m-d'))
   ->setParameter('sunday', $sunday->format('Y-m-d'));

or…

$qb->where('e.fecha > :monday')
   ->andWhere('e.fecha < :sunday')
   ->setParameter('monday', $monday->format('Y-m-d'))
   ->setParameter('sunday', $sunday->format('Y-m-d'));

Types in Objective-C on iOS

This is a good overview:

http://reference.jumpingmonkey.org/programming_languages/objective-c/types.html

or run this code:

32 bit process:

  NSLog(@"Primitive sizes:");
  NSLog(@"The size of a char is: %d.", sizeof(char));
  NSLog(@"The size of short is: %d.", sizeof(short));
  NSLog(@"The size of int is: %d.", sizeof(int));
  NSLog(@"The size of long is: %d.", sizeof(long));
  NSLog(@"The size of long long is: %d.", sizeof(long long));
  NSLog(@"The size of a unsigned char is: %d.", sizeof(unsigned char));
  NSLog(@"The size of unsigned short is: %d.", sizeof(unsigned short));
  NSLog(@"The size of unsigned int is: %d.", sizeof(unsigned int));
  NSLog(@"The size of unsigned long is: %d.", sizeof(unsigned long));
  NSLog(@"The size of unsigned long long is: %d.", sizeof(unsigned long long));
  NSLog(@"The size of a float is: %d.", sizeof(float));
  NSLog(@"The size of a double is %d.", sizeof(double));

  NSLog(@"Ranges:");
  NSLog(@"CHAR_MIN:   %c",   CHAR_MIN);
  NSLog(@"CHAR_MAX:   %c",   CHAR_MAX);
  NSLog(@"SHRT_MIN:   %hi",  SHRT_MIN);    // signed short int
  NSLog(@"SHRT_MAX:   %hi",  SHRT_MAX);
  NSLog(@"INT_MIN:    %i",   INT_MIN);
  NSLog(@"INT_MAX:    %i",   INT_MAX);
  NSLog(@"LONG_MIN:   %li",  LONG_MIN);    // signed long int
  NSLog(@"LONG_MAX:   %li",  LONG_MAX);
  NSLog(@"ULONG_MAX:  %lu",  ULONG_MAX);   // unsigned long int
  NSLog(@"LLONG_MIN:  %lli", LLONG_MIN);   // signed long long int
  NSLog(@"LLONG_MAX:  %lli", LLONG_MAX);
  NSLog(@"ULLONG_MAX: %llu", ULLONG_MAX);  // unsigned long long int

When run on an iPhone 3GS (iPod Touch and older iPhones should yield the same result) you get:

Primitive sizes:
The size of a char is: 1.                
The size of short is: 2.                 
The size of int is: 4.                   
The size of long is: 4.                  
The size of long long is: 8.             
The size of a unsigned char is: 1.       
The size of unsigned short is: 2.        
The size of unsigned int is: 4.          
The size of unsigned long is: 4.         
The size of unsigned long long is: 8.    
The size of a float is: 4.               
The size of a double is 8.               
Ranges:                                  
CHAR_MIN:   -128                         
CHAR_MAX:   127                          
SHRT_MIN:   -32768                       
SHRT_MAX:   32767                        
INT_MIN:    -2147483648                  
INT_MAX:    2147483647                   
LONG_MIN:   -2147483648                  
LONG_MAX:   2147483647                   
ULONG_MAX:  4294967295                   
LLONG_MIN:  -9223372036854775808         
LLONG_MAX:  9223372036854775807          
ULLONG_MAX: 18446744073709551615 

64 bit process:

The size of a char is: 1.
The size of short is: 2.
The size of int is: 4.
The size of long is: 8.
The size of long long is: 8.
The size of a unsigned char is: 1.
The size of unsigned short is: 2.
The size of unsigned int is: 4.
The size of unsigned long is: 8.
The size of unsigned long long is: 8.
The size of a float is: 4.
The size of a double is 8.
Ranges:
CHAR_MIN:   -128
CHAR_MAX:   127
SHRT_MIN:   -32768
SHRT_MAX:   32767
INT_MIN:    -2147483648
INT_MAX:    2147483647
LONG_MIN:   -9223372036854775808
LONG_MAX:   9223372036854775807
ULONG_MAX:  18446744073709551615
LLONG_MIN:  -9223372036854775808
LLONG_MAX:  9223372036854775807
ULLONG_MAX: 18446744073709551615

User GETDATE() to put current date into SQL variable

SELECT @LastChangeDate = GETDATE()

Magento - How to add/remove links on my account navigation?

The answer to your question is ultimately, it depends. The links in that navigation are added via different layout XML files. Here's the code that first defines the block in layout/customer.xml. Notice that it also defines some links to add to the menu:

<block type="customer/account_navigation" name="customer_account_navigation" before="-" template="customer/account/navigation.phtml">
    <action method="addLink" translate="label" module="customer"><name>account</name><path>customer/account/</path><label>Account Dashboard</label></action>
    <action method="addLink" translate="label" module="customer"><name>account_edit</name><path>customer/account/edit/</path><label>Account Information</label></action>
    <action method="addLink" translate="label" module="customer"><name>address_book</name><path>customer/address/</path><label>Address Book</label></action>
</block>

Other menu items are defined in other layout files. For example, the Reviews module uses layout/review.xml to define its layout, and contains the following:

<customer_account>
    <!-- Mage_Review -->
    <reference name="customer_account_navigation">
        <action method="addLink" translate="label" module="review"><name>reviews</name><path>review/customer</path><label>My Product Reviews</label></action>
    </reference>
</customer_account>

To remove this link, just comment out or remove the <action method=...> tag and the menu item will disappear. If you want to find all menu items at once, use your favorite file search and find any instances of name="customer_account_navigation", which is the handle that Magento uses for that navigation block.

SELECT only rows that contain only alphanumeric characters in MySQL

There is also this:

select m from table where not regexp_like(m, '^[0-9]\d+$')

which selects the rows that contains characters from the column you want (which is m in the example but you can change).

Most of the combinations don't work properly in Oracle platforms but this does. Sharing for future reference.

Import an existing git project into GitLab?

You create an empty project in gitlab then on your local terminal follow one of these:

Push an existing folder

cd existing_folder
git init
git remote add origin [email protected]:GITLABUSERNAME/YOURGITPROJECTNAME.git
git add .
git commit -m "Initial commit"
git push -u origin master

Push an existing Git repository

cd existing_repo
git remote rename origin old-origin
git remote add origin [email protected]:GITLABUSERNAME/YOURGITPROJECTNAME.git
git push -u origin --all
git push -u origin --tags

How do I download a file from the internet to my linux server with Bash

I guess you could use curl and wget, but since Oracle requires you to check of some checkmarks this will be painfull to emulate with the tools mentioned. You would have to download the page with the license agreement and from looking at it figure out what request is needed to get to the actual download.

Of course you could simply start a browser, but this might not qualify as 'from the command line'. So you might want to look into lynx, a text based browser.

How to change button color with tkinter

Another way to change color of a button if you want to do multiple operations along with color change. Using the Tk().after method and binding a change method allows you to change color and do other operations.

Label.destroy is another example of the after method.

    def export_win():
        //Some Operation
        orig_color = export_finding_graph.cget("background")
        export_finding_graph.configure(background = "green")

        tt = "Exported"
        label = Label(tab1_closed_observations, text=tt, font=("Helvetica", 12))
        label.grid(row=0,column=0,padx=10,pady=5,columnspan=3)

        def change(orig_color):
            export_finding_graph.configure(background = orig_color)

        tab1_closed_observations.after(1000, lambda: change(orig_color))
        tab1_closed_observations.after(500, label.destroy)


    export_finding_graph = Button(tab1_closed_observations, text='Export', command=export_win)
    export_finding_graph.grid(row=6,column=4,padx=70,pady=20,sticky='we',columnspan=3)

You can also revert to the original color.

'Missing contentDescription attribute on image' in XML

Going forward, for graphical elements that are purely decorative, the best solution is to use:

android:importantForAccessibility="no"

This makes sense if your min SDK version is at least 16, since devices running lower versions will ignore this attribute.

If you're stuck supporting older versions, you should use (like others pointed out already):

android:contentDescription="@null"

Source: https://developer.android.com/guide/topics/ui/accessibility/apps#label-elements

'sudo gem install' or 'gem install' and gem locations

You can also install gems in your local environment (without sudo) with

gem install --user-install <gemname>

I recommend that so you don't mess with your system-level configuration even if it's a single-user computer.

You can check where the gems go by looking at gempaths with gem environment. In my case it's "~/.gem/ruby/1.8".

If you need some binaries from local installs added to your path, you can add something to your bashrc like:

if which ruby >/dev/null && which gem >/dev/null; then
    PATH="$(ruby -r rubygems -e 'puts Gem.user_dir')/bin:$PATH"
fi

(from http://guides.rubygems.org/faqs/#user-install)

css width: calc(100% -100px); alternative using jquery

Try jQuery animate() method, ex.

$("#divid").animate({'width':perc+'%'});

Spring Security redirect to previous page after successful login

You can use a Custom SuccessHandler extending SimpleUrlAuthenticationSuccessHandler for redirecting users to different URLs when login according to their assigned roles.

CustomSuccessHandler class provides custom redirect functionality:

package com.mycompany.uomrmsweb.configuration;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

@Component
public class CustomSuccessHandler extends SimpleUrlAuthenticationSuccessHandler{

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Override
    protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        String targetUrl = determineTargetUrl(authentication);

        if (response.isCommitted()) {
            System.out.println("Can't redirect");
            return;
        }

        redirectStrategy.sendRedirect(request, response, targetUrl);
    }

    protected String determineTargetUrl(Authentication authentication) {
        String url="";

        Collection<? extends GrantedAuthority> authorities =  authentication.getAuthorities();

        List<String> roles = new ArrayList<String>();

        for (GrantedAuthority a : authorities) {
            roles.add(a.getAuthority());
        }

        if (isStaff(roles)) {
            url = "/staff";
        } else if (isAdmin(roles)) {
            url = "/admin";
        } else if (isStudent(roles)) {
            url = "/student";
        }else if (isUser(roles)) {
            url = "/home";
        } else {
            url="/Access_Denied";
        }

        return url;
    }

    public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
        this.redirectStrategy = redirectStrategy;
    }
    protected RedirectStrategy getRedirectStrategy() {
        return redirectStrategy;
    }

    private boolean isUser(List<String> roles) {
        if (roles.contains("ROLE_USER")) {
            return true;
        }
        return false;
    }

    private boolean isStudent(List<String> roles) {
        if (roles.contains("ROLE_Student")) {
            return true;
        }
        return false;
    }

    private boolean isAdmin(List<String> roles) {
        if (roles.contains("ROLE_SystemAdmin") || roles.contains("ROLE_ExaminationsStaff")) {
            return true;
        }
        return false;
    }

    private boolean isStaff(List<String> roles) {
        if (roles.contains("ROLE_AcademicStaff") || roles.contains("ROLE_UniversityAdmin")) {
            return true;
        }
        return false;
    }
}

Extending Spring SimpleUrlAuthenticationSuccessHandler class and overriding handle() method which simply invokes a redirect using configured RedirectStrategy [default in this case] with the URL returned by the user defined determineTargetUrl() method. This method extracts the Roles of currently logged in user from Authentication object and then construct appropriate URL based on there roles. Finally RedirectStrategy , which is responsible for all redirections within Spring Security framework , redirects the request to specified URL.

Registering CustomSuccessHandler using SecurityConfiguration class:

package com.mycompany.uomrmsweb.configuration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    @Qualifier("customUserDetailsService")
    UserDetailsService userDetailsService;

    @Autowired
    CustomSuccessHandler customSuccessHandler;

    @Autowired
    public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(userDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
        .antMatchers("/", "/home").access("hasRole('USER')")
        .antMatchers("/admin/**").access("hasRole('SystemAdmin') or hasRole('ExaminationsStaff')")
        .antMatchers("/staff/**").access("hasRole('AcademicStaff') or hasRole('UniversityAdmin')")
        .antMatchers("/student/**").access("hasRole('Student')")  
                    .and().formLogin().loginPage("/login").successHandler(customSuccessHandler)
        .usernameParameter("username").passwordParameter("password")
        .and().csrf()
        .and().exceptionHandling().accessDeniedPage("/Access_Denied");
    }
}

successHandler is the class responsible for eventual redirection based on any custom logic, which in this case will be to redirect the user [to student/admin/staff ] based on his role [USER/Student/SystemAdmin/UniversityAdmin/ExaminationsStaff/AcademicStaff].

pyplot axes labels for subplots

Here is a solution where you set the ylabel of one of the plots and adjust the position of it so it is centered vertically. This way you avoid problems mentioned by KYC.

import numpy as np
import matplotlib.pyplot as plt

def set_shared_ylabel(a, ylabel, labelpad = 0.01):
    """Set a y label shared by multiple axes
    Parameters
    ----------
    a: list of axes
    ylabel: string
    labelpad: float
        Sets the padding between ticklabels and axis label"""

    f = a[0].get_figure()
    f.canvas.draw() #sets f.canvas.renderer needed below

    # get the center position for all plots
    top = a[0].get_position().y1
    bottom = a[-1].get_position().y0

    # get the coordinates of the left side of the tick labels 
    x0 = 1
    for at in a:
        at.set_ylabel('') # just to make sure we don't and up with multiple labels
        bboxes, _ = at.yaxis.get_ticklabel_extents(f.canvas.renderer)
        bboxes = bboxes.inverse_transformed(f.transFigure)
        xt = bboxes.x0
        if xt < x0:
            x0 = xt
    tick_label_left = x0

    # set position of label
    a[-1].set_ylabel(ylabel)
    a[-1].yaxis.set_label_coords(tick_label_left - labelpad,(bottom + top)/2, transform=f.transFigure)

length = 100
x = np.linspace(0,100, length)
y1 = np.random.random(length) * 1000
y2 = np.random.random(length)

f,a = plt.subplots(2, sharex=True, gridspec_kw={'hspace':0})
a[0].plot(x, y1)
a[1].plot(x, y2)
set_shared_ylabel(a, 'shared y label (a. u.)')

enter image description here

Bigger Glyphicons

In my case, I had an input-group-btn with a button, and this button was a little bigger than its container. So I just gave font-size:95% for my glyphicon and it was solved.

<div class="input-group">
    <input type="text" class="form-control" id="pesquisarinbox" placeholder="Pesquisar na Caixa de Entrada">
    <div class="input-group-btn">
        <button class="btn btn-default" type="button">
            <span class="glyphicon glyphicon-search" style="font-size:95%;"></span>
        </button>
    </div>  
</div>

How to convert a byte array to Stream

In your case:

MemoryStream ms = new MemoryStream(buffer);

Combining a class selector and an attribute selector with jQuery

This will also work:

$(".myclass[reference='12345']").css('border', '#000 solid 1px');

Reasons for using the set.seed function

Just adding some addition aspects. Need for setting seed: In the academic world, if one claims that his algorithm achieves, say 98.05% performance in one simulation, others need to be able to reproduce it.

?set.seed

Going through the help file of this function, these are some interesting facts:

(1) set.seed() returns NULL, invisible

(2) "Initially, there is no seed; a new one is created from the current time and the process ID when one is required. Hence different sessions will give different simulation results, by default. However, the seed might be restored from a previous session if a previously saved workspace is restored.", this is why you would want to call set.seed() with same integer values the next time you want a same sequence of random sequence.

error: expected primary-expression before ')' token (C)

You're passing a type as an argument, not an object. You need to do characterSelection(screen, test); where test is of type SelectionneNonSelectionne.

Git push error: Unable to unlink old (Permission denied)

Pulling may have created local change.

Add your untracked file:

git add .

Stash changes.

git stash

Drop local changes.

git stash drop

Pull with sudo permission

sudo git pull remote branch

Where are static variables stored in C and C++?

I tried it with objdump and gdb, here is the result what I get:

(gdb) disas fooTest
Dump of assembler code for function fooTest:
   0x000000000040052d <+0>: push   %rbp
   0x000000000040052e <+1>: mov    %rsp,%rbp
   0x0000000000400531 <+4>: mov    0x200b09(%rip),%eax        # 0x601040 <foo>
   0x0000000000400537 <+10>:    add    $0x1,%eax
   0x000000000040053a <+13>:    mov    %eax,0x200b00(%rip)        # 0x601040 <foo>
   0x0000000000400540 <+19>:    mov    0x200afe(%rip),%eax        # 0x601044 <bar.2180>
   0x0000000000400546 <+25>:    add    $0x1,%eax
   0x0000000000400549 <+28>:    mov    %eax,0x200af5(%rip)        # 0x601044 <bar.2180>
   0x000000000040054f <+34>:    mov    0x200aef(%rip),%edx        # 0x601044 <bar.2180>
   0x0000000000400555 <+40>:    mov    0x200ae5(%rip),%eax        # 0x601040 <foo>
   0x000000000040055b <+46>:    mov    %eax,%esi
   0x000000000040055d <+48>:    mov    $0x400654,%edi
   0x0000000000400562 <+53>:    mov    $0x0,%eax
   0x0000000000400567 <+58>:    callq  0x400410 <printf@plt>
   0x000000000040056c <+63>:    pop    %rbp
   0x000000000040056d <+64>:    retq   
End of assembler dump.

(gdb) disas barTest
Dump of assembler code for function barTest:
   0x000000000040056e <+0>: push   %rbp
   0x000000000040056f <+1>: mov    %rsp,%rbp
   0x0000000000400572 <+4>: mov    0x200ad0(%rip),%eax        # 0x601048 <foo>
   0x0000000000400578 <+10>:    add    $0x1,%eax
   0x000000000040057b <+13>:    mov    %eax,0x200ac7(%rip)        # 0x601048 <foo>
   0x0000000000400581 <+19>:    mov    0x200ac5(%rip),%eax        # 0x60104c <bar.2180>
   0x0000000000400587 <+25>:    add    $0x1,%eax
   0x000000000040058a <+28>:    mov    %eax,0x200abc(%rip)        # 0x60104c <bar.2180>
   0x0000000000400590 <+34>:    mov    0x200ab6(%rip),%edx        # 0x60104c <bar.2180>
   0x0000000000400596 <+40>:    mov    0x200aac(%rip),%eax        # 0x601048 <foo>
   0x000000000040059c <+46>:    mov    %eax,%esi
   0x000000000040059e <+48>:    mov    $0x40065c,%edi
   0x00000000004005a3 <+53>:    mov    $0x0,%eax
   0x00000000004005a8 <+58>:    callq  0x400410 <printf@plt>
   0x00000000004005ad <+63>:    pop    %rbp
   0x00000000004005ae <+64>:    retq   
End of assembler dump.

here is the objdump result

Disassembly of section .data:

0000000000601030 <__data_start>:
    ...

0000000000601038 <__dso_handle>:
    ...

0000000000601040 <foo>:
  601040:   01 00                   add    %eax,(%rax)
    ...

0000000000601044 <bar.2180>:
  601044:   02 00                   add    (%rax),%al
    ...

0000000000601048 <foo>:
  601048:   0a 00                   or     (%rax),%al
    ...

000000000060104c <bar.2180>:
  60104c:   14 00                   adc    $0x0,%al

So, that's to say, your four variables are located in data section event the the same name, but with different offset.

How to install Visual C++ Build tools?

I just stumbled onto this issue accessing some Python libraries: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools". The latest link to that is actually here: https://visualstudio.microsoft.com/downloads/#build-tools-for-visual-studio-2019

When you begin the installer, it will have several "options" enabled which will balloon the install size to 5gb. If you have Windows 10, you'll need to leave selected the "Windows 10 SDK" option as mentioned here.

enter image description here

I hope it helps save others time!

Opening new window in HTML for target="_blank"

You don't have that kind of control with a bare a tag. But you can hook up the tag's onclick handler to call window.open(...) with the right parameters. See here for examples: https://developer.mozilla.org/En/DOM/Window.open

I still don't think you can force window over tab directly though-- that depends on the browser and the user's settings.

Set Date in a single line

tl;dr

LocalDate.of( 2015 , Month.JUNE , 7 )  // Using handy `Month` enum. 

…or…

LocalDate.of( 2015 , 6 , 7 )  // Sensible numbering, 1-12 for January to December. 

java.time

The java.time framework built into Java 8 and later supplants the troublesome old classes, java.util.Date/.Calendar.

The java.time classes use immutable objects. So they are inherently thread-safe. You will have none of the thread-safety problems mentioned on the other answers.

LocalDate

This framework included a class for date-only objects without any time-of-day or time zone, LocalDate. Note that a time zone (ZoneId) is necessary to determine a date.

LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) );

You can instantiate for a specific date. Note that month number is a sensible range of 1-12 unlike the old classes.

LocalDate localDate = LocalDate.of( 2015 , 6 , 7 );

Or use the enum, Month.

LocalDate localDate = LocalDate.of( 2015 , Month.JUNE , 7 );

Convert

Best to avoid the old date-time classes. But if you must, you can convert. Call new methods added to the old classes to facilitate conversions.

In this case we need to specify a time-of-day to go along with our date-only value, to be combined for a java.util.Date object. First moment of the day likely makes sense. Let java.time determine the time of that first moment as it is not always 00:00:00.0.

We also need to specify a time zone, as the date varies by time zone.

ZoneId zoneId = zoneId.of( "America/Montreal" );
ZonedDateTime zdt = localDate.atStartOfDay( zoneId );

An Instant is a basic class in java.time, representing a moment on the timeline in UTC. Feed an Instant to static method on Date to convert.

Instant instant = zdt.toInstant();
java.util.Date utilDate = java.util.Date.from( instant );

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

When is the @JsonProperty property used and what is it used for?

From JsonProperty javadoc,

Defines name of the logical property, i.e. JSON object field name to use for the property. If value is empty String (which is the default), will try to use name of the field that is annotated.

How to upgrade docker container after its image changed

Similar answer to above

docker images | awk '{print $1}' | grep -v 'none' | grep -iv 'repo' | xargs -n1 docker pull

Remove duplicates from a List<T> in C#

Might be easier to simply make sure that duplicates are not added to the list.

if(items.IndexOf(new_item) < 0) 
    items.add(new_item)

insert datetime value in sql database with c#

 DateTime time = DateTime.Now;              // Use current time
 string format = "yyyy-MM-dd HH:mm:ss";    // modify the format depending upon input required in the column in database 
 string insert = @" insert into Table(DateTime Column) values ('" + time.ToString(format) + "')"; 

and execute the query. DateTime.Now is to insert current Datetime..

What is the difference between encrypting and signing in asymmetric encryption?

Functionally, you use public/private key encryption to make certain only the receiver can read your message. The message is encrypted using the public key of the receiver and decrypted using the private key of the receiver.

Signing you can use to let the receiver know you created the message and it has not changed during transfer. Message signing is done using your own private key. The receiver can use your public key to check the message has not been tampered.

As for the algorithm used: that involves a one-way function see for example wikipedia. One of the first of such algorithms use large prime-numbers but more one-way functions have been invented since.

Search for 'Bob', 'Alice' and 'Mallory' to find introduction articles on the internet.

Return datetime object of previous month

For most use cases, what about

from datetime import date

current_date =date.today()
current_month = current_date.month
last_month = current_month - 1 if current_month != 1 else 12  
today_a_month_ago = date(current_date.year, last_month, current_date.day)

That seems the simplest to me.

Note: I've added the second to last line so that it would work if the current month is January as per @Nick's comment

Note 2: In most cases, if the current date is the 31st of a given month the result will be an invalid date as the previous month would not have 31 days (Except for July & August), as noted by @OneCricketeer

fetch gives an empty response body

Try to use response.json():

fetch('http://example.com/api/node', {
  mode: "no-cors",
  method: "GET",
  headers: {
    "Accept": "application/json"
  }
}).then((response) => {
  console.log(response.json()); // null
  return dispatch({
    type: "GET_CALL",
    response: response.json()
  });
})
.catch(error => { console.log('request failed', error); });

Error in if/while (condition) {: missing Value where TRUE/FALSE needed

this works with "NA" not for NA

comments = c("no","yes","NA")
  for (l in 1:length(comments)) {
    #if (!is.na(comments[l])) print(comments[l])
    if (comments[l] != "NA") print(comments[l])
  }

How to add one day to a date?

This will increase any date by exactly one

String untildate="2011-10-08";//can take any date in current format    
SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd" );   
Calendar cal = Calendar.getInstance();    
cal.setTime( dateFormat.parse(untildate));    
cal.add( Calendar.DATE, 1 );    
String convertedDate=dateFormat.format(cal.getTime());    
System.out.println("Date increase by one.."+convertedDate);

Display a loading bar before the entire page is loaded

I've recently made a page loader in vanilla .js for a project, just wanted to share it as all the other answers are jQuery based. It's a plug and play, one-liner.

It automatically creates a <div> tag prepended to the <body>, with a <svg> loader. If you want to customize the color you just have to update the t variable at the beginning of the script.

var t="#106CF6",u=document.querySelector("*"),s=document.createElement("style"),a=document.createElement("aside"),m="http://www.w3.org/2000/svg",g=document.createElementNS(m,"svg"),c=document.createElementNS(m,"circle");document.head.appendChild(s),(s.innerHTML="#sailor {background:"+t+";color:"+t+";display:flex;align-items:center;justify-content:center;position:fixed;top:0;height:100vh;width:100vw;z-index:2147483647}@keyframes swell{to{transform:rotate(360deg)}}#sailor svg{animation:.3s swell infinite linear}"),a.setAttribute("id","sailor"),document.body.prepend(a),g.setAttribute("height","50"),g.setAttribute("filter","brightness(175%)"),g.setAttribute("viewBox","0 0 100 100"),a.prepend(g),c.setAttribute("cx","50"),c.setAttribute("cy","50"),c.setAttribute("r","35"),c.setAttribute("fill","none"),c.setAttribute("stroke","currentColor"),c.setAttribute("stroke-dasharray","165 57"),c.setAttribute("stroke-width","10"),g.prepend(c),(u.style.pointerEvents="none"),(u.style.userSelect="none"),(u.style.cursor="wait"),window.addEventListener("load",function(){setTimeout(function(){(u.style.pointerEvents=""),(u.style.userSelect=""),(u.style.cursor="");a.remove()},100)})

You can see the full project and documentation on the GitHub

How to read request body in an asp.net core webapi controller?

for read of Body , you can to read asynchronously.

use the async method like follow:

public async Task<IActionResult> GetBody()
{
      string body="";
      using (StreamReader stream = new StreamReader(Request.Body))
      {
           body = await stream.ReadToEndAsync();
      }
    return Json(body);
}

Test with postman:

enter image description here

It's working well and tested in Asp.net core version 2.0 , 2.1 , 2.2, 3.0.

I hope is useful.

Get all mysql selected rows into an array

you can call mysql_fetch_array() for no_of_row time

HTML/Javascript Button Click Counter

Use var instead of int for your clicks variable generation and onClick instead of click as your function name:

_x000D_
_x000D_
var clicks = 0;

function onClick() {
  clicks += 1;
  document.getElementById("clicks").innerHTML = clicks;
};
_x000D_
<button type="button" onClick="onClick()">Click me</button>
<p>Clicks: <a id="clicks">0</a></p>
_x000D_
_x000D_
_x000D_

In JavaScript variables are declared with the var keyword. There are no tags like int, bool, string... to declare variables. You can get the type of a variable with 'typeof(yourvariable)', more support about this you find on Google.

And the name 'click' is reserved by JavaScript for function names so you have to use something else.

How can I access "static" class variables within class methods in Python?

As with all good examples, you've simplified what you're actually trying to do. This is good, but it is worth noting that python has a lot of flexibility when it comes to class versus instance variables. The same can be said of methods. For a good list of possibilities, I recommend reading Michael Fötsch' new-style classes introduction, especially sections 2 through 6.

One thing that takes a lot of work to remember when getting started is that python is not java. More than just a cliche. In java, an entire class is compiled, making the namespace resolution real simple: any variables declared outside a method (anywhere) are instance (or, if static, class) variables and are implicitly accessible within methods.

With python, the grand rule of thumb is that there are three namespaces that are searched, in order, for variables:

  1. The function/method
  2. The current module
  3. Builtins

{begin pedagogy}

There are limited exceptions to this. The main one that occurs to me is that, when a class definition is being loaded, the class definition is its own implicit namespace. But this lasts only as long as the module is being loaded, and is entirely bypassed when within a method. Thus:

>>> class A(object):
        foo = 'foo'
        bar = foo


>>> A.foo
'foo'
>>> A.bar
'foo'

but:

>>> class B(object):
        foo = 'foo'
        def get_foo():
            return foo
        bar = get_foo()



Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    class B(object):
  File "<pyshell#11>", line 5, in B
    bar = get_foo()
  File "<pyshell#11>", line 4, in get_foo
    return foo
NameError: global name 'foo' is not defined

{end pedagogy}

In the end, the thing to remember is that you do have access to any of the variables you want to access, but probably not implicitly. If your goals are simple and straightforward, then going for Foo.bar or self.bar will probably be sufficient. If your example is getting more complicated, or you want to do fancy things like inheritance (you can inherit static/class methods!), or the idea of referring to the name of your class within the class itself seems wrong to you, check out the intro I linked.

LF will be replaced by CRLF in git - What is that and is it important?

In Unix systems the end of a line is represented with a line feed (LF). In windows a line is represented with a carriage return (CR) and a line feed (LF) thus (CRLF). when you get code from git that was uploaded from a unix system they will only have an LF.

If you are a single developer working on a windows machine, and you don't care that git automatically replaces LFs to CRLFs, you can turn this warning off by typing the following in the git command line

git config core.autocrlf true

If you want to make an intelligent decision how git should handle this, read the documentation

Here is a snippet

Formatting and Whitespace

Formatting and whitespace issues are some of the more frustrating and subtle problems that many developers encounter when collaborating, especially cross-platform. It’s very easy for patches or other collaborated work to introduce subtle whitespace changes because editors silently introduce them, and if your files ever touch a Windows system, their line endings might be replaced. Git has a few configuration options to help with these issues.

core.autocrlf

If you’re programming on Windows and working with people who are not (or vice-versa), you’ll probably run into line-ending issues at some point. This is because Windows uses both a carriage-return character and a linefeed character for newlines in its files, whereas Mac and Linux systems use only the linefeed character. This is a subtle but incredibly annoying fact of cross-platform work; many editors on Windows silently replace existing LF-style line endings with CRLF, or insert both line-ending characters when the user hits the enter key.

Git can handle this by auto-converting CRLF line endings into LF when you add a file to the index, and vice versa when it checks out code onto your filesystem. You can turn on this functionality with the core.autocrlf setting. If you’re on a Windows machine, set it to true – this converts LF endings into CRLF when you check out code:

$ git config --global core.autocrlf true

If you’re on a Linux or Mac system that uses LF line endings, then you don’t want Git to automatically convert them when you check out files; however, if a file with CRLF endings accidentally gets introduced, then you may want Git to fix it. You can tell Git to convert CRLF to LF on commit but not the other way around by setting core.autocrlf to input:

$ git config --global core.autocrlf input

This setup should leave you with CRLF endings in Windows checkouts, but LF endings on Mac and Linux systems and in the repository.

If you’re a Windows programmer doing a Windows-only project, then you can turn off this functionality, recording the carriage returns in the repository by setting the config value to false:

$ git config --global core.autocrlf false

I can pass a variable from a JSP scriptlet to JSTL but not from JSTL to a JSP scriptlet without an error

@skaffman nailed it down. They live each in its own context. However, I wouldn't consider using scriptlets as the solution. You'd like to avoid them. If all you want is to concatenate strings in EL and you discovered that the + operator fails for strings in EL (which is correct), then just do:

<c:out value="abc${test}" />

Or if abc is to obtained from another scoped variable named ${resp}, then do:

<c:out value="${resp}${test}" />

HTML display result in text (input) field?

Do you really want the result to come up in an input box? If not, consider a table with borders set to other than transparent and use

document.getElementById('sum').innerHTML = sum;

Cycles in an Undirected Graph

I believe using DFS correctly also depends on how are you going to represent your graph in the code. For example suppose you are using adjacent lists to keep track of neighbor nodes and your graph has 2 vertices and only one edge: V={1,2} and E={(1,2)}. In this case starting from vertex 1, DFS will mark it as VISITED and will put 2 in the queue. After that it will pop vertex 2 and since 1 is adjacent to 2, and 1 is VISITED, DFS will conclude that there is a cycle (which is wrong). In other words in Undirected graphs (1,2) and (2,1) are the same edge and you should code in a way for DFS not to consider them different edges. Keeping parent node for each visited node will help to handle this situation.

How to update column with null value

Remember to look if your column can be null. You can do that using

mysql> desc my_table;

If your column cannot be null, when you set the value to null it will be the cast value to it.

Here a example

mysql> create table example ( age int not null, name varchar(100) not null );
mysql> insert into example values ( null, "without num" ), ( 2 , null );
mysql> select * from example;
+-----+-------------+
| age | name        |
+-----+-------------+
|   0 | without num |
|   2 |             |
+-----+-------------+
2 rows in set (0.00 sec)

mysql> select * from example where age is null or name is null;
Empty set (0.00 sec)

Detect viewport orientation, if orientation is Portrait display alert message advising user of instructions

Some devices don't provide the orientationchange event, but do fire the window's resize event:

// Listen for resize changes
window.addEventListener("resize", function() {
    // Get screen size (inner/outerWidth, inner/outerHeight)

}, false);

A bit less obvious than the orientationchange event, but works very well. Please check here

How can I check if a string only contains letters in Python?

Simple:

if string.isalpha():
    print("It's all letters")

str.isalpha() is only true if all characters in the string are letters:

Return true if all characters in the string are alphabetic and there is at least one character, false otherwise.

Demo:

>>> 'hello'.isalpha()
True
>>> '42hello'.isalpha()
False
>>> 'hel lo'.isalpha()
False

T-SQL How to create tables dynamically in stored procedures?

You will need to build that CREATE TABLE statement from the inputs and then execute it.

A simple example:

declare @cmd nvarchar(1000), @TableName nvarchar(100);

set @TableName = 'NewTable';

set @cmd = 'CREATE TABLE dbo.' + quotename(@TableName, '[') + '(newCol int not null);';

print @cmd;

--exec(@cmd);

What is the proper way to check and uncheck a checkbox in HTML5?

<input type="checkbox" checked />

HTML5 does not require attributes to have values

String Concatenation in EL

Since Expression Language 3.0, it is valid to use += operator for string concatenation.

${(empty value)? "none" : value += " enabled"}  // valid as of EL 3.0

Quoting EL 3.0 Specification.

String Concatenation Operator

To evaluate

A += B 
  • Coerce A and B to String.
  • Return the concatenated string of A and B.

Add border-bottom to table row <tr>

Add border-collapse:collapse to your table rule:

table { 
    border-collapse: collapse; 
}

Example

_x000D_
_x000D_
table {
  border-collapse: collapse;
}

tr {
  border-bottom: 1pt solid black;
}
_x000D_
<table>
  <tr><td>A1</td><td>B1</td><td>C1</td></tr>
  <tr><td>A2</td><td>B2</td><td>C2</td></tr>
  <tr><td>A2</td><td>B2</td><td>C2</td></tr>
</table>
_x000D_
_x000D_
_x000D_

Link

What's the best visual merge tool for Git?

Meld is a free, open-source, and cross-platform (UNIX/Linux, OSX, Windows) diff/merge tool.

Here's how to install it on:

Deserialize from string instead TextReader

1-liner, takes a XML string text and YourType as the expected object type. not very different from other answers, just compressed to 1 line:

var result =  (YourType)new XmlSerializer(typeof(YourType)).Deserialize(new StringReader(text));

DateTime to javascript date

Another late answer, but this is missing here. If you want to handle conversion of serialized /Date(1425408717000)/ in javascript, you can simply call:

var cSharpDate = "/Date(1425408717000)/"
var jsDate = new Date(parseInt(cSharpDate.replace(/[^0-9 +]/g, '')));

Source: amirsahib

R * not meaningful for factors ERROR

new[,2] is a factor, not a numeric vector. Transform it first

new$MY_NEW_COLUMN <-as.numeric(as.character(new[,2])) * 5

Program to find largest and smallest among 5 numbers without using array

Here's my implementation: Simple and short

#include <iostream>
#include <cstdio>
using namespace std;


int max_of_five(int a, int b, int c, int d,int e){
    int large= max(max(a, b), max(c,d));
    return max(large,e);

}

int min_of_five(int a,int b,int c, int d,int e){
    int small=min(min(a,b),min(c,d));
    return min(small,e);
}


int main() {
    int a, b, c, d,e;

    scanf("%d %d %d %d %d", &a, &b, &c, &d,&e);
    int ans = max_of_five(a, b, c, d, e);
    int ans1=min_of_five(a,b,c,d,e);
    printf("Max:\t%d\n", ans);
    printf("Min:\t%d", ans1);

    return 0;
}

Get array elements from index to end

The [:-1] removes the last element. Instead of

a[3:-1]

write

a[3:]

You can read up on Python slicing notation here: Explain Python's slice notation

NumPy slicing is an extension of that. The NumPy tutorial has some coverage: Indexing, Slicing and Iterating.

Razor HtmlHelper Extensions (or other namespaces for views) Not Found

This error tells you that you do not have the razor engine properly associated with your project.

Solution: In the Solution Explorer window right click on your web project and select "Manage Nuget Packages..." then install "Microsoft ASP.NET Razor". This will make sure that the properly package is installed and it will add the necessary entries into your web.config file.

How to get WooCommerce order details

Accessing direct properties and related are explained

// Get an instance of the WC_Order object
            $order = wc_get_order($order_id);
            $order_data = array(
                    'order_id' => $order->get_id(),
                    'order_number' => $order->get_order_number(),
                    'order_date' => date('Y-m-d H:i:s', strtotime(get_post($order->get_id())->post_date)),
                    'status' => $order->get_status(),
                    'shipping_total' => $order->get_total_shipping(),
                    'shipping_tax_total' => wc_format_decimal($order->get_shipping_tax(), 2),
                    'fee_total' => wc_format_decimal($fee_total, 2),
                    'fee_tax_total' => wc_format_decimal($fee_tax_total, 2),
                    'tax_total' => wc_format_decimal($order->get_total_tax(), 2),
                    'cart_discount' => (defined('WC_VERSION') && (WC_VERSION >= 2.3)) ? wc_format_decimal($order->get_total_discount(), 2) : wc_format_decimal($order->get_cart_discount(), 2),
                    'order_discount' => (defined('WC_VERSION') && (WC_VERSION >= 2.3)) ? wc_format_decimal($order->get_total_discount(), 2) : wc_format_decimal($order->get_order_discount(), 2),
                    'discount_total' => wc_format_decimal($order->get_total_discount(), 2),
                    'order_total' => wc_format_decimal($order->get_total(), 2),
                    'order_currency' => $order->get_currency(),
                    'payment_method' => $order->get_payment_method(),
                    'shipping_method' => $order->get_shipping_method(),
                    'customer_id' => $order->get_user_id(),
                    'customer_user' => $order->get_user_id(),
                    'customer_email' => ($a = get_userdata($order->get_user_id() )) ? $a->user_email : '',
                    'billing_first_name' => $order->get_billing_first_name(),
                    'billing_last_name' => $order->get_billing_last_name(),
                    'billing_company' => $order->get_billing_company(),
                    'billing_email' => $order->get_billing_email(),
                    'billing_phone' => $order->get_billing_phone(),
                    'billing_address_1' => $order->get_billing_address_1(),
                    'billing_address_2' => $order->get_billing_address_2(),
                    'billing_postcode' => $order->get_billing_postcode(),
                    'billing_city' => $order->get_billing_city(),
                    'billing_state' => $order->get_billing_state(),
                    'billing_country' => $order->get_billing_country(),
                    'shipping_first_name' => $order->get_shipping_first_name(),
                    'shipping_last_name' => $order->get_shipping_last_name(),
                    'shipping_company' => $order->get_shipping_company(),
                    'shipping_address_1' => $order->get_shipping_address_1(),
                    'shipping_address_2' => $order->get_shipping_address_2(),
                    'shipping_postcode' => $order->get_shipping_postcode(),
                    'shipping_city' => $order->get_shipping_city(),
                    'shipping_state' => $order->get_shipping_state(),
                    'shipping_country' => $order->get_shipping_country(),
                    'customer_note' => $order->get_customer_note(),
                    'download_permissions' => $order->is_download_permitted() ? $order->is_download_permitted() : 0,
            );

Additional details

  $line_items_shipping = $order->get_items('shipping');
            foreach ($line_items_shipping as $item_id => $item) {
                if (is_object($item)) {
                    if ($meta_data = $item->get_formatted_meta_data('')) :
                        foreach ($meta_data as $meta_id => $meta) :
                            if (in_array($meta->key, $line_items_shipping)) {
                                continue;
                            }
                            // html entity decode is not working preoperly
                            $shipping_items[] = implode('|', array('item:' . wp_kses_post($meta->display_key), 'value:' . str_replace('&times;', 'X', strip_tags($meta->display_value))));
                        endforeach;
                    endif;
                }
            }

            //get fee and total
            $fee_total = 0;
            $fee_tax_total = 0;

            foreach ($order->get_fees() as $fee_id => $fee) {

                $fee_items[] = implode('|', array(
                        'name:' .  html_entity_decode($fee['name'], ENT_NOQUOTES, 'UTF-8'),
                        'total:' . wc_format_decimal($fee['line_total'], 2),
                        'tax:' . wc_format_decimal($fee['line_tax'], 2),
                ));

                $fee_total += $fee['line_total'];
                $fee_tax_total += $fee['line_tax'];
            }

            // get tax items
            foreach ($order->get_tax_totals() as $tax_code => $tax) {            
                $tax_items[] = implode('|', array(
                    'rate_id:'.$tax->id,
                    'code:' . $tax_code,
                    'total:' . wc_format_decimal($tax->amount, 2),
                    'label:'.$tax->label,                
                    'tax_rate_compound:'.$tax->is_compound,
                ));
            }

            // add coupons
            foreach ($order->get_items('coupon') as $_ => $coupon_item) {

                $coupon = new WC_Coupon($coupon_item['name']);

                $coupon_post = get_post((WC()->version < '2.7.0') ? $coupon->id : $coupon->get_id());
                $discount_amount = !empty($coupon_item['discount_amount']) ? $coupon_item['discount_amount'] : 0;
                $coupon_items[] = implode('|', array(
                        'code:' . $coupon_item['name'],
                        'description:' . ( is_object($coupon_post) ? $coupon_post->post_excerpt : '' ),
                        'amount:' . wc_format_decimal($discount_amount, 2),
                ));
            }

            foreach ($order->get_refunds() as $refunded_items){
                $refund_items[] = implode('|', array(
                    'amount:' . $refunded_items->get_amount(),
            'reason:' . $refunded_items->get_reason(),
                    'date:'. date('Y-m-d H-i-s',strtotime((WC()->version < '2.7.0') ? $refunded_items->date_created : $refunded_items->get_date_created())),
                ));
            }

How to implement a read only property

The second way is the preferred option.

private readonly int MyVal = 5;

public int MyProp { get { return MyVal;}  }

This will ensure that MyVal can only be assigned at initialization (it can also be set in a constructor).

As you had noted - this way you are not exposing an internal member, allowing you to change the internal implementation in the future.

Bootstrap 3 and Youtube in Modal

I have one tip for you!

I would use:

$('#myModal').on('hidden.bs.modal', function () {
    $('#myModal iframe').removeAttr('src');
})

instead of:

$('#myModal button').click(function () {
    $('#myModal iframe').removeAttr('src');
});

Because you can also close the modal without the button, so there for with this code it will remove the video every time the modal will hide.

Python: Adding element to list while iterating

well, according to http://docs.python.org/tutorial/controlflow.html

It is not safe to modify the sequence being iterated over in the loop (this can only happen for mutable sequence types, such as lists). If you need to modify the list you are iterating over (for example, to duplicate selected items) you must iterate over a copy.

How to run Maven from another directory (without cd to project dir)?

You can try this:

pushd ../
maven install [...]
popd

How to get a jqGrid selected row cells value

Use "selrow" to get the selected row Id

var myGrid = $('#myGridId');

var selectedRowId = myGrid.jqGrid("getGridParam", 'selrow');

and then use getRowData to get the selected row at index selectedRowId.

var selectedRowData = myGrid.getRowData(selectedRowId);

If the multiselect is set to true on jqGrid, then use "selarrrow" to get list of selected rows:

var selectedRowIds = myGrid.jqGrid("getGridParam", 'selarrrow');

Use loop to iterate the list of selected rows:

var selectedRowData;

for(selectedRowIndex = 0; selectedRowIndex < selectedRowIds .length; selectedRowIds ++) {

   selectedRowData = myGrid.getRowData(selectedRowIds[selectedRowIndex]);

}

How to check if a list is empty in Python?

Empty lists evaluate to False in boolean contexts (such as if some_list:).

Using CSS to affect div style inside iframe

Yes, it's possible although cumbersome. You would need to print/echo the HTML of the page into the body of your page then apply a CSS rule change function. Using the same examples given above, you would essentially be using a parsing method of finding the divs in the page, and then applying the CSS to it and then reprinting/echoing it out to the end user. I don't need this so I don't want to code that function into every item in the CSS of another webpage just to aphtply.

References:

Python if not == vs if !=

An additional note, since the other answers answered your question mostly correctly, is that if a class only defines __eq__() and not __ne__(), then your COMPARE_OP (!=) will run __eq__() and negate it. At that time, your third option is likely to be a tiny bit more efficient, but should only be considered if you NEED the speed, since it's difficult to understand quickly.

Creating a segue programmatically

You have to link your code to the UIStoryboard that you're using. Make sure you go into YourViewController in your UIStoryboard, click on the border around it, and then set its identifier field to a NSString that you call in your code.

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" 
                                                     bundle:nil];
YourViewController *yourViewController = 
 (YourViewController *)
  [storyboard instantiateViewControllerWithIdentifier:@"yourViewControllerID"];
[self.navigationController pushViewController:yourViewController animated:YES];

Room - Schema export directory is not provided to the annotation processor so we cannot export the schema

In the build.gradle file for your app module, add this to the defaultConfig section (under the android section). This will write out the schema to a schemas subfolder of your project folder.

javaCompileOptions {
    annotationProcessorOptions {
        arguments += ["room.schemaLocation": "$projectDir/schemas".toString()]
    }
}

Like this:

// ...

android {
    
    // ... (compileSdkVersion, buildToolsVersion, etc)

    defaultConfig {

        // ... (applicationId, miSdkVersion, etc)
        
        javaCompileOptions {
            annotationProcessorOptions {
                arguments += ["room.schemaLocation": "$projectDir/schemas".toString()]
            }
        }
    }
   
    // ... (buildTypes, compileOptions, etc)

}

// ...

Java URLConnection Timeout

You can set timeouts for all connections made from the jvm by changing the following System-properties:

System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
System.setProperty("sun.net.client.defaultReadTimeout", "10000");

Every connection will time out after 10 seconds.

Setting 'defaultReadTimeout' is not needed, but shown as an example if you need to control reading.

How to execute a remote command over ssh with arguments?

This is an example that works on the AWS Cloud. The scenario is that some machine that booted from autoscaling needs to perform some action on another server, passing the newly spawned instance DNS via SSH

# Get the public DNS of the current machine (AWS specific)
MY_DNS=`curl -s http://169.254.169.254/latest/meta-data/public-hostname`


ssh \
    -o StrictHostKeyChecking=no \
    -i ~/.ssh/id_rsa \
    [email protected] \
<< EOF
cd ~/
echo "Hey I was just SSHed by ${MY_DNS}"
run_other_commands
# Newline is important before final EOF!

EOF

jQuery Ajax calls and the Html.AntiForgeryToken()

Slight improvement to 360Airwalk solution. This imbeds the Anti Forgery Token within the javascript function, so @Html.AntiForgeryToken() no longer needs to be included on every view.

$(document).ready(function () {
    var securityToken = $('@Html.AntiForgeryToken()').attr('value');
    $('body').bind('ajaxSend', function (elm, xhr, s) {
        if (s.type == 'POST' && typeof securityToken != 'undefined') {
            if (s.data.length > 0) {
                s.data += "&__RequestVerificationToken=" + encodeURIComponent(securityToken);
            }
            else {
                s.data = "__RequestVerificationToken=" + encodeURIComponent(securityToken);
            }
        }
    });
});

How do I get the old value of a changed cell in Excel VBA?

try this, it will not work for the first selection, then it will work nice :)

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    On Error GoTo 10
    If Target.Count > 1 Then GoTo 10
    Target.Value = lastcel(Target.Value)
    10
End Sub


Function lastcel(lC_vAl As String) As String
    Static vlu
    lastcel = vlu
    vlu = lC_vAl
End Function

Permission to write to the SD card

You're right that the SD Card directory is /sdcard but you shouldn't be hard coding it. Instead, make a call to Environment.getExternalStorageDirectory() to get the directory:

File sdDir = Environment.getExternalStorageDirectory();

If you haven't done so already, you will need to give your app the correct permission to write to the SD Card by adding the line below to your Manifest:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

How to attach a file using mail command on Linux?

mailx might help as well. From the mailx man page:

-a file
     Attach the given file to the message.

Pretty easy, right?

Renaming a directory in C#

You should move it:

Directory.Move(source, destination);

React-router v4 this.props.history.push(...) not working

Don't use with Router.

handleSubmit(e){
   e.preventDefault();
   this.props.form.validateFieldsAndScroll((err,values)=>{
      if(!err){
        this.setState({
            visible:false
        });
        this.props.form.resetFields();
        console.log(values.username);
        const path = '/list/';
        this.props.history.push(path);
      }
   })
}

It works well.

Configuring diff tool with .gitconfig

In Windows we need to run $git difftool --tool-help command to see the various options like:

    'git difftool --tool=<tool>' may be set to one of the following:
                    vimdiff
                    vimdiff2
                    vimdiff3

    The following tools are valid, but not currently available:
                    araxis
                    bc
                    bc3
                    codecompare
                    deltawalker
                    diffmerge
                    diffuse
                    ecmerge
                    emerge
                    examdiff
                    gvimdiff
                    gvimdiff2
                    gvimdiff3
                    kdiff3
                    kompare
                    meld
                    opendiff
                    p4merge
                    tkdiff
                    winmerge
                    xxdiff
Some of the tools listed above only work in a windowed
environment. If run in a terminal-only session, they will fail.

and we can add any of them(for example winmerge) like

$  git difftool --tool=winmerge

For configuring notepad++ to see files before committing:

 git config --global core.editor "'C:/Program Files/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin"

and using $ git commit will open the commit information in notepad++

ActiveRecord: size vs count

As the other answers state:

  • count will perform an SQL COUNT query
  • length will calculate the length of the resulting array
  • size will try to pick the most appropriate of the two to avoid excessive queries

But there is one more thing. We noticed a case where size acts differently to count/lengthaltogether, and I thought I'd share it since it is rare enough to be overlooked.

  • If you use a :counter_cache on a has_many association, size will use the cached count directly, and not make an extra query at all.

    class Image < ActiveRecord::Base
      belongs_to :product, counter_cache: true
    end
    
    class Product < ActiveRecord::Base
      has_many :images
    end
    
    > product = Product.first  # query, load product into memory
    > product.images.size      # no query, reads the :images_count column
    > product.images.count     # query, SQL COUNT
    > product.images.length    # query, loads images into memory
    

This behaviour is documented in the Rails Guides, but I either missed it the first time or forgot about it.

How do I compare two string variables in an 'if' statement in Bash?

For string equality comparison, use:

if [[ "$s1" == "$s2" ]]

For string does NOT equal comparison, use:

if [[ "$s1" != "$s2" ]]

For the a contains b, use:

if [[ $s1 == *"$s2"* ]]

(and make sure to add spaces between the symbols):

Bad:

if [["$s1" == "$s2"]]

Good:

if [[ "$s1" == "$s2" ]]

How to decrypt hash stored by bcrypt

You simply can't.

bcrypt uses salting, of different rounds, I use 10 usually.

bcrypt.hash(req.body.password,10,function(error,response){ }

This 10 is salting random string into your password.

How to find children of nodes using BeautifulSoup

Yet another method - create a filter function that returns True for all desired tags:

def my_filter(tag):
    return (tag.name == 'a' and
        tag.parent.name == 'li' and
        'test' in tag.parent['class'])

Then just call find_all with the argument:

for a in soup(my_filter): # or soup.find_all(my_filter)
    print a

text-align: right; not working for <label>

Label is an inline element - so, unless a width is defined, its width is exact the same which the letters span. Your div element is a block element so its width is by default 100%.

You will have to place the text-align: right; on the div element in your case, or applying display: block; to your label

Another option is to set a width for each label and then use text-align. The display: block method will not be necessary using this.

TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app

Just need to remove and re-install react-scripts

To Remove yarn remove react-scripts To Add yarn add react-scripts

and then rm -rf node_modules/ yarn.lock && yarn

  • Remember don't update the react-scripts version maually

jQuery limit to 2 decimal places

You could use a variable to make the calculation and use toFixed when you set the #diskamountUnit element value:

var amount = $("#disk").slider("value") * 1.60;
$("#diskamountUnit").val('$' + amount.toFixed(2));

You can also do that in one step, in the val method call but IMO the first way is more readable:

$("#diskamountUnit").val('$' + ($("#disk").slider("value") * 1.60).toFixed(2));

How to use if statements in LESS

There is a way to use guards for individual (or multiple) attributes.

@debug: true;

header {
    /* guard for attribute */
    & when (@debug = true) {
        background-color: yellow;
    }
    /* guard for nested class */
    #title when (@debug = true) {
        background-color: orange;
    }
}

/* guard for class */
article when (@debug = true) {
    background-color: red;
}

/* and when debug is off: */
article when not (@debug = true) {
    background-color: green;
}

...and with Less 1.7; compiles to:

header {
    background-color: yellow;
}
header #title {
    background-color: orange;
}
article {
    background-color: red;
}

React JS - Uncaught TypeError: this.props.data.map is not a function

what worked for me is converting the props.data to an array using data = Array.from(props.data); then I could use the data.map() function

How to refresh table contents in div using jquery/ajax

You can load HTML page partial, in your case is everything inside div#mytable.

setTimeout(function(){
   $( "#mytable" ).load( "your-current-page.html #mytable" );
}, 2000); //refresh every 2 seconds

more information read this http://api.jquery.com/load/

Update Code (if you don't want it auto-refresh)

<button id="refresh-btn">Refresh Table</button>

<script>
$(document).ready(function() {

   function RefreshTable() {
       $( "#mytable" ).load( "your-current-page.html #mytable" );
   }

   $("#refresh-btn").on("click", RefreshTable);

   // OR CAN THIS WAY
   //
   // $("#refresh-btn").on("click", function() {
   //    $( "#mytable" ).load( "your-current-page.html #mytable" );
   // });


});
</script>

Clear image on picturebox

private void ClearBtn_Click(object sender, EventArgs e)
{
    Studentpicture.Image = null;
}

Checking Bash exit status of several commands efficiently

Personally I much prefer to use a lightweight approach, as seen here;

yell() { echo "$0: $*" >&2; }
die() { yell "$*"; exit 111; }
try() { "$@" || die "cannot $*"; }
asuser() { sudo su - "$1" -c "${*:2}"; }

Example usage:

try apt-fast upgrade -y
try asuser vagrant "echo 'uname -a' >> ~/.profile"

Rails get index of "each" loop

The two answers are good. And I also suggest you a similar method:

<% @images.each.with_index do |page, index| %>
<% end %>

You might not see the difference between this and the accepted answer. Let me direct your eyes to these method calls: .each.with_index see how it's .each and then .with_index.

Merge or combine by rownames

Using merge and renaming your t vector as tt (see the PS of Andrie) :

merge(tt,z,by="row.names",all.x=TRUE)[,-(5:8)]

Now if you would work with dataframes instead of matrices, this would even become a whole lot easier :

z <- as.data.frame(z)
tt <- as.data.frame(tt)
merge(tt,z["symbol"],by="row.names",all.x=TRUE)

Meaning of Choreographer messages in Logcat

This if an Info message that could pop in your LogCat on many situations.

In my case, it happened when I was inflating several views from XML layout files programmatically. The message is harmless by itself, but could be the sign of a later problem that would use all the RAM your App is allowed to use and cause the mega-evil Force Close to happen. I have grown to be the kind of Developer that likes to see his Log WARN/INFO/ERROR Free. ;)

So, this is my own experience:

I got the message:

10-09 01:25:08.373: I/Choreographer(11134): Skipped XXX frames!  The application may be doing too much work on its main thread.

... when I was creating my own custom "super-complex multi-section list" by inflating a view from XML and populating its fields (images, text, etc...) with the data coming from the response of a REST/JSON web service (without paging capabilities) this views would act as rows, sub-section headers and section headers by adding all of them in the correct order to a LinearLayout (with vertical orientation inside a ScrollView). All of that to simulate a listView with clickable elements... but well, that's for another question.

As a responsible Developer you want to make the App really efficient with the system resources, so the best practice for lists (when your lists are not so complex) is to use a ListActivity or ListFragment with a Loader and fill the ListView with an Adapter, this is supposedly more efficient, in fact it is and you should do it all the time, again... if your list is not so complex.

Solution: I implemented paging on my REST/JSON web service to prevent "big response sizes" and I wrapped the code that added the "rows", "section headers" and "sub-section headers" views on an AsyncTask to keep the Main Thread cool.

So... I hope my experience helps someone else that is cracking their heads open with this Info message.

Happy hacking!

What is the single most influential book every programmer should read?

Design Concepts in Programming Languages by FA Turbak produces detailed implementations of many programming concepts and is very useful for understanding what's going on underneath the hood.

Python str vs unicode types

unicode is meant to handle text. Text is a sequence of code points which may be bigger than a single byte. Text can be encoded in a specific encoding to represent the text as raw bytes(e.g. utf-8, latin-1...).

Note that unicode is not encoded! The internal representation used by python is an implementation detail, and you shouldn't care about it as long as it is able to represent the code points you want.

On the contrary str in Python 2 is a plain sequence of bytes. It does not represent text!

You can think of unicode as a general representation of some text, which can be encoded in many different ways into a sequence of binary data represented via str.

Note: In Python 3, unicode was renamed to str and there is a new bytes type for a plain sequence of bytes.

Some differences that you can see:

>>> len(u'à')  # a single code point
1
>>> len('à')   # by default utf-8 -> takes two bytes
2
>>> len(u'à'.encode('utf-8'))
2
>>> len(u'à'.encode('latin1'))  # in latin1 it takes one byte
1
>>> print u'à'.encode('utf-8')  # terminal encoding is utf-8
à
>>> print u'à'.encode('latin1') # it cannot understand the latin1 byte
?

Note that using str you have a lower-level control on the single bytes of a specific encoding representation, while using unicode you can only control at the code-point level. For example you can do:

>>> 'àèìòù'
'\xc3\xa0\xc3\xa8\xc3\xac\xc3\xb2\xc3\xb9'
>>> print 'àèìòù'.replace('\xa8', '')
à?ìòù

What before was valid UTF-8, isn't anymore. Using a unicode string you cannot operate in such a way that the resulting string isn't valid unicode text. You can remove a code point, replace a code point with a different code point etc. but you cannot mess with the internal representation.

How to get absolute path to file in /resources folder of your project

You need to specifie path started from /

URL resource = YourClass.class.getResource("/abc");
Paths.get(resource.toURI()).toFile();

How to get the first item from an associative PHP array?

PHP < 7.3

If you don't know enough about the array (you're not sure whether the first key is foo or bar) then the array might well also be, maybe, empty.

So it would be best to check, especially if there is the chance that the returned value might be the boolean FALSE:

$value = empty($arr) ? $default : reset($arr);

The above code uses reset and so has side effects (it resets the internal pointer of the array), so you might prefer using array_slice to quickly access a copy of the first element of the array:

$value = $default;
foreach(array_slice($arr, 0, 1) as $value);

Assuming you want to get both the key and the value separately, you need to add the fourth parameter to array_slice:

foreach(array_slice($arr, 0, 1, true) as $key => $value);

To get the first item as a pair (key => value):

$item = array_slice($arr, 0, 1, true);

Simple modification to get the last item, key and value separately:

foreach(array_slice($arr, -1, 1, true) as $key => $value);

performance

If the array is not really big, you don't actually need array_slice and can rather get a copy of the whole keys array, then get the first item:

$key = count($arr) ? array_keys($arr)[0] : null;

If you have a very big array, though, the call to array_keys will require significant time and memory more than array_slice (both functions walk the array, but the latter terminates as soon as it has gathered the required number of items - which is one).

A notable exception is when you have the first key which points to a very large and convoluted object. In that case array_slice will duplicate that first large object, while array_keys will only grab the keys.

PHP 7.3+

PHP 7.3 onwards implements array_key_first() as well as array_key_last(). These are explicitly provided to access first and last keys efficiently without resetting the array's internal state as a side effect.

So since PHP 7.3 the first value of $array may be accessed with

$array[array_key_first($array)];

You still had better check that the array is not empty though, or you will get an error:

$firstKey = array_key_first($array);
if (null === $firstKey) {
    $value = "Array is empty"; // An error should be handled here
} else {
    $value = $array[$firstKey];
}

submit the form using ajax

You can catch form input values using FormData and send them by fetch

fetch(form.action,{method:'post', body: new FormData(form)});

_x000D_
_x000D_
function send(e,form) {_x000D_
  fetch(form.action,{method:'post', body: new FormData(form)});_x000D_
_x000D_
  console.log('We send post asynchronously (AJAX)');_x000D_
  e.preventDefault();_x000D_
}
_x000D_
<form method="POST" action="myapi/send" onsubmit="send(event,this)">_x000D_
    <input hidden name="crsfToken" value="a1e24s1">_x000D_
    <input name="email" value="[email protected]">_x000D_
    <input name="phone" value="123-456-789">_x000D_
    <input type="submit">    _x000D_
</form>_x000D_
_x000D_
Look on chrome console>network before 'submit'
_x000D_
_x000D_
_x000D_

ldap query for group members

The good way to get all the members from a group is to, make the DN of the group as the searchDN and pass the "member" as attribute to get in the search function. All of the members of the group can now be found by going through the attribute values returned by the search. The filter can be made generic like (objectclass=*).

How to set default font family for entire Android app

With the release of Android Oreo you can use the support library to reach this goal.

  1. Check in your app build.gradle if you have the support library >= 26.0.0
  2. Add "font" folder to your resources folder and add your fonts there
  3. Reference your default font family in your app main style:

    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
       <item name="android:fontFamily">@font/your_font</item>
       <item name="fontFamily">@font/your_font</item> <!-- target android sdk versions < 26 and > 14 if theme other than AppCompat -->
    </style>
    

Check https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml.html for more detailed information.

android EditText - finished typing event

I had the same issue and did not want to rely on the user pressing Done or Enter.

My first attempt was to use the onFocusChange listener, but it occurred that my EditText got the focus by default. When user pressed some other view, the onFocusChange was triggered without the user ever having assigned it the focus.

Next solution did it for me, where the onFocusChange is attached if the user touched the EditText:

final myEditText = new EditText(myContext); //make final to refer in onTouch
myEditText.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            myEditText.setOnFocusChangeListener(new OnFocusChangeListener() {

                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    if(!hasFocus){
                        // user is done editing
                    }
                }
            }
        }
}

In my case, when the user was done editing the screen was rerendered, thereby renewing the myEditText object. If the same object is kept, you should probably remove the onFocusChange listener in onFocusChange to prevent the onFocusChange issue described at the start of this post.

How can I do time/hours arithmetic in Google Spreadsheet?

In the case you want to format it within a formula (for example, if you are concatenating strings and values), the aforementioned format option of Google is not available, but you can use the TEXT formula:

=TEXT(B1-C1,"HH:MM:SS")

Therefore, for the questioned example, with concatenation:

="The number of " & TEXT(B1,"HH") & " hour slots in " & TEXT(C1,"HH") _
& " is " & TEXT(C1/B1,"HH")

Cheers

Compare data of two Excel Columns A & B, and show data of Column A that do not exist in B

Suppose you have data in A1:A10 and B1:B10 and you want to highlight which values in A1:A10 do not appear in B1:B10.

Try as follows:

  1. Format > Conditional Formating...
  2. Select 'Formula Is' from drop down menu
  3. Enter the following formula:

    =ISERROR(MATCH(A1,$B$1:$B$10,0))

  4. Now select the format you want to highlight the values in col A that do not appear in col B

This will highlight any value in Col A that does not appear in Col B.

How to read a HttpOnly cookie using JavaScript

Different Browsers enable different security measures when the HTTPOnly flag is set. For instance Opera and Safari do not prevent javascript from writing to the cookie. However, reading is always forbidden on the latest version of all major browsers.

But more importantly why do you want to read an HTTPOnly cookie? If you are a developer, just disable the flag and make sure you test your code for xss. I recommend that you avoid disabling this flag if at all possible. The HTTPOnly flag and "secure flag" (which forces the cookie to be sent over https) should always be set.

If you are an attacker, then you want to hijack a session. But there is an easy way to hijack a session despite the HTTPOnly flag. You can still ride on the session without knowing the session id. The MySpace Samy worm did just that. It used an XHR to read a CSRF token and then perform an authorized task. Therefore, the attacker could do almost anything that the logged user could do.

People have too much faith in the HTTPOnly flag, XSS can still be exploitable. You should setup barriers around sensitive features. Such as the change password filed should require the current password. An admin's ability to create a new account should require a captcha, which is a CSRF prevention technique that cannot be easily bypassed with an XHR.

How is using OnClickListener interface different via XML and Java code?

These are exactly the same. android:onClick was added in API level 4 to make it easier, more Javascript-web-like, and drive everything from the XML. What it does internally is add an OnClickListener on the Button, which calls your DoIt method.

Here is what using a android:onClick="DoIt" does internally:

Button button= (Button) findViewById(R.id.buttonId);
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        DoIt(v);
    }
});

The only thing you trade off by using android:onClick, as usual with XML configuration, is that it becomes a bit more difficult to add dynamic content (programatically, you could decide to add one listener or another depending on your variables). But this is easily defeated by adding your test within the DoIt method.

How do I fix the error 'Named Pipes Provider, error 40 - Could not open a connection to' SQL Server'?

in my case, i had a standalone server, i changed the sql server port default port 1433 in configuration manager to some number and restarted the sql serve service to take effect,i was able to connect to the sql server through management studio if i login to the server. but i was not able to connect from my local machine through sql server, i was getting the error:

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and

that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) (Microsoft SQL Server, Error: 5)

I checked and verified all the below

-Named pipes/TCP is enabled. -Remote connections are allowed. -Windows Firewall is off -Created an exception for portin Windows Firewall( this was not necessary in my case as the server is in same subnet network). -Enabled everything in SQL Server Configuration Manager.

then i chnaged back the port number to default 1433 and restarted the sql server service, and the issue got resolved and i am able to connect the sql server from my local management studio.

How to get element value in jQuery

To get value of li we should use $("#list li").click(function() { var selected = $(this).html();

or

var selected = $(this).text();

alert(selected);

})

Split List into Sublists with LINQ

Can work with infinite generators:

a.Zip(a.Skip(1), (x, y) => Enumerable.Repeat(x, 1).Concat(Enumerable.Repeat(y, 1)))
 .Zip(a.Skip(2), (xy, z) => xy.Concat(Enumerable.Repeat(z, 1)))
 .Where((x, i) => i % 3 == 0)

Demo code: https://ideone.com/GKmL7M

using System;
using System.Collections.Generic;
using System.Linq;

public class Test
{
  private static void DoIt(IEnumerable<int> a)
  {
    Console.WriteLine(String.Join(" ", a));

    foreach (var x in a.Zip(a.Skip(1), (x, y) => Enumerable.Repeat(x, 1).Concat(Enumerable.Repeat(y, 1))).Zip(a.Skip(2), (xy, z) => xy.Concat(Enumerable.Repeat(z, 1))).Where((x, i) => i % 3 == 0))
      Console.WriteLine(String.Join(" ", x));

    Console.WriteLine();
  }

  public static void Main()
  {
    DoIt(new int[] {1});
    DoIt(new int[] {1, 2});
    DoIt(new int[] {1, 2, 3});
    DoIt(new int[] {1, 2, 3, 4});
    DoIt(new int[] {1, 2, 3, 4, 5});
    DoIt(new int[] {1, 2, 3, 4, 5, 6});
  }
}
1

1 2

1 2 3
1 2 3

1 2 3 4
1 2 3

1 2 3 4 5
1 2 3

1 2 3 4 5 6
1 2 3
4 5 6

But actually I would prefer to write corresponding method without linq.

NVIDIA NVML Driver/library version mismatch

Had the issue too. (I'm running ubuntu 18.04)

What I did:

dpkg -l | grep -i nvidia

Then sudo apt-get remove --purge nvidia-381 (and every duplicate version, in my case I had 381, 384 and 387)

Then sudo ubuntu-drivers devices to list what's available

And I choose sudo apt install nvidia-driver-430

After that, nvidia-smi gave the correct output (no need to reboot). But I suppose you can reboot when in doubt.

I also followed this installation to reinstall cuda+cudnn.

What's the idiomatic syntax for prepending to a short python list?

If you can go the functional way, the following is pretty clear

new_list = [x] + your_list

Of course you haven't inserted x into your_list, rather you have created a new list with x preprended to it.

ExpressJS How to structure an application?

This may be of interest:

https://github.com/flatiron/nconf

Hierarchical node.js configuration with files, environment variables, command-line arguments, and atomic object merging.

How to combine two lists in R

I was looking to do the same thing, but to preserve the list as a just an array of strings so I wrote a new code, which from what I've been reading may not be the most efficient but worked for what i needed to do:

combineListsAsOne <-function(list1, list2){
  n <- c()
  for(x in list1){
    n<-c(n, x)
  }
  for(y in list2){
    n<-c(n, y)
  }
  return(n)
}

It just creates a new list and adds items from two supplied lists to create one.

Init array of structs in Go

It looks like you are trying to use (almost) straight up C code here. Go has a few differences.

  • First off, you can't initialize arrays and slices as const. The term const has a different meaning in Go, as it does in C. The list should be defined as var instead.
  • Secondly, as a style rule, Go prefers basenameOpts as opposed to basename_opts.
  • There is no char type in Go. You probably want byte (or rune if you intend to allow unicode codepoints).
  • The declaration of the list must have the assignment operator in this case. E.g.: var x = foo.
  • Go's parser requires that each element in a list declaration ends with a comma. This includes the last element. The reason for this is because Go automatically inserts semi-colons where needed. And this requires somewhat stricter syntax in order to work.

For example:

type opt struct {
    shortnm      byte
    longnm, help string
    needArg      bool
}

var basenameOpts = []opt { 
    opt {
        shortnm: 'a', 
        longnm: "multiple", 
        needArg: false, 
        help: "Usage for a",
    },
    opt {
        shortnm: 'b', 
        longnm: "b-option", 
        needArg: false, 
        help: "Usage for b",
    },
}

An alternative is to declare the list with its type and then use an init function to fill it up. This is mostly useful if you intend to use values returned by functions in the data structure. init functions are run when the program is being initialized and are guaranteed to finish before main is executed. You can have multiple init functions in a package, or even in the same source file.

    type opt struct {
        shortnm      byte
        longnm, help string
        needArg      bool
    }

    var basenameOpts []opt

    func init() { 
        basenameOpts = []opt{
            opt {
                shortnm: 'a', 
                longnm: "multiple", 
                needArg: false, 
                help: "Usage for a",
            },
            opt {
                shortnm: 'b', 
                longnm: "b-option", 
                needArg: false, 
               help: "Usage for b",
            },
        }
    }

Since you are new to Go, I strongly recommend reading through the language specification. It is pretty short and very clearly written. It will clear a lot of these little idiosyncrasies up for you.

Minimum Hardware requirements for Android development

Firstly, there is an issue with the ADT plugin and Helios which causes lag with looking up Android classes - use Galileo instead (v3.5).

Secondly, the emulators become more resource hungry depending on the version of Android you're developing for. Example, I have a P4 2.4GHz, 1GB RAM PC with Win XP 32-bit and an Android v2.2 emulator takes at least 4-5 minutes to load up. An Android v1.6 emulator on the other hand loads up in less than 1 minute. Remember though that once the emulator is up and running, you can leave it loaded and it will be more responsive than first use.

Also bear in mind that if you give your emulator a 2GB SD card (for example) it will try to create that through virtual memory if there isn't enough physical memory.

How do you find out the caller function in JavaScript?

I wanted to add my fiddle here for this:

http://jsfiddle.net/bladnman/EhUm3/

I tested this is chrome, safari and IE (10 and 8). Works fine. There is only 1 function that matters, so if you get scared by the big fiddle, read below.

Note: There is a fair amount of my own "boilerplate" in this fiddle. You can remove all of that and use split's if you like. It's just an ultra-safe" set of functions I've come to rely on.

There is also a "JSFiddle" template in there that I use for many fiddles to simply quick fiddling.

MySQL - length() vs char_length()

LENGTH() returns the length of the string measured in bytes.
CHAR_LENGTH() returns the length of the string measured in characters.

This is especially relevant for Unicode, in which most characters are encoded in two bytes. Or UTF-8, where the number of bytes varies. For example:

select length(_utf8 '€'), char_length(_utf8 '€')
--> 3, 1

As you can see the Euro sign occupies 3 bytes (it's encoded as 0xE282AC in UTF-8) even though it's only one character.

Global variables in c#.net

Just declare the variable at the starting of a class.

e.g. for string variable:

public partial class Login : System.Web.UI.Page
{
    public string sError;

    protected void Page_Load(object sender, EventArgs e)
    {
         //Page Load Code
    }

Count character occurrences in a string in C++

I would have done something like that :)

const char* str = "bla_bla_blabla_bla";
char* p = str;    
unsigned int count = 0;
while (*p != '\0')
    if (*p++ == '_')
        count++;

Check if table exists and if it doesn't exist, create it in SQL Server 2008

Try the following statement to check for existence of a table in the database:

If not exists (select name from sysobjects where name = 'tablename')

You may create the table inside the if block.

Set SSH connection timeout

The problem may be that ssh is trying to connect to all the different IPs that www.google.com resolves to. For example on my machine:

# ssh -v -o ConnectTimeout=1 -o ConnectionAttempts=1 www.google.com
OpenSSH_5.9p1, OpenSSL 0.9.8t 18 Jan 2012
debug1: Connecting to www.google.com [173.194.43.20] port 22.
debug1: connect to address 173.194.43.20 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.19] port 22.
debug1: connect to address 173.194.43.19 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.18] port 22.
debug1: connect to address 173.194.43.18 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.17] port 22.
debug1: connect to address 173.194.43.17 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.16] port 22.
debug1: connect to address 173.194.43.16 port 22: Connection timed out
ssh: connect to host www.google.com port 22: Connection timed out

If I run it with a specific IP, it returns much faster.

EDIT: I've timed it (with time) and the results are:

  • www.google.com - 5.086 seconds
  • 173.94.43.16 - 1.054 seconds

How to connect SQLite with Java?

You have to download and add the SQLite JDBC driver to your classpath.
You can download from here https://bitbucket.org/xerial/sqlite-jdbc/downloads

If you use Gradle, you will only have to add the SQLite dependency:

dependencies {
    compile 'org.xerial:sqlite-jdbc:3.8.11.2'
} 

Next thing you have to do is to initialize the driver:

try {
    Class.forName("org.sqlite.JDBC");
} catch (ClassNotFoundException eString) {
    System.err.println("Could not init JDBC driver - driver not found");
}

How to import a module in Python with importlib.import_module

I think it's better to use importlib.import_module('.c', __name__) since you don't need to know about a and b.

I'm also wondering that, if you have to use importlib.import_module('a.b.c'), why not just use import a.b.c?