Programs & Examples On #Mlabwrap

How to overlay images

I just got done doing this exact thing in a project. The HTML side looked a bit like this:

<a href="[fullsize]" class="gallerypic" title="">
  <img src="[thumbnail pic]" height="90" width="140" alt="[Gallery Photo]" class="pic" />
  <span class="zoom-icon">
      <img src="/images/misc/zoom.gif" width="32" height="32" alt="Zoom">
  </span>
</a>

Then using CSS:

a.gallerypic{
  width:140px;
  text-decoration:none;
  position:relative;
  display:block;
  border:1px solid #666;
  padding:3px;
  margin-right:5px;
  float:left;
}

a.gallerypic span.zoom-icon{
  visibility:hidden;
  position:absolute;
  left:40%;
  top:35%;
  filter:alpha(opacity=50);
  -moz-opacity:0.5;
  -khtml-opacity: 0.5;
  opacity: 0.5;
}

a.gallerypic:hover span.zoom-icon{
  visibility:visible;
}

I left a lot of the sample in there on the CSS so you can see how I decided to do the style. Note I lowered the opacity so you could see through the magnifying glass.

Hope this helps.

EDIT: To clarify for your example - you could ignore the visibility:hidden; and kill the :hover execution if you wanted, this was just the way I did it.

Why is it common to put CSRF prevention tokens in cookies?

My best guess as to the answer: Consider these 3 options for how to get the CSRF token down from the server to the browser.

  1. In the request body (not an HTTP header).
  2. In a custom HTTP header, not Set-Cookie.
  3. As a cookie, in a Set-Cookie header.

I think the 1st one, request body (while demonstrated by the Express tutorial I linked in the question), is not as portable to a wide variety of situations; not everyone is generating every HTTP response dynamically; where you end up needing to put the token in the generated response might vary widely (in a hidden form input; in a fragment of JS code or a variable accessible by other JS code; maybe even in a URL though that seems generally a bad place to put CSRF tokens). So while workable with some customization, #1 is a hard place to do a one-size-fits-all approach.

The second one, custom header, is attractive but doesn't actually work, because while JS can get the headers for an XHR it invoked, it can't get the headers for the page it loaded from.

That leaves the third one, a cookie carried by a Set-Cookie header, as an approach that is easy to use in all situations (anyone's server will be able to set per-request cookie headers, and it doesn't matter what kind of data is in the request body). So despite its downsides, it was the easiest method for frameworks to implement widely.

How to create JNDI context in Spring Boot with Embedded Tomcat Container

In SpringBoot 2.1, I found another solution. Extend standard factory class method getTomcatWebServer. And then return it as a bean from anywhere.

public class CustomTomcatServletWebServerFactory extends TomcatServletWebServerFactory {

    @Override
    protected TomcatWebServer getTomcatWebServer(Tomcat tomcat) {
        System.setProperty("catalina.useNaming", "true");
        tomcat.enableNaming();
        return new TomcatWebServer(tomcat, getPort() >= 0);
    }
}

@Component
public class TomcatConfiguration {
    @Bean
    public ConfigurableServletWebServerFactory webServerFactory() {
        TomcatServletWebServerFactory factory = new CustomTomcatServletWebServerFactory();

        return factory;
    }

Loading resources from context.xml doesn't work though. Will try to find out.

Checking if object is empty, works with ng-show but not from controller?

Check Empty object

$scope.isValid = function(value) {
    return !value
}

Get path from open file in Python

I had the exact same issue. If you are using a relative path os.path.dirname(path) will only return the relative path. os.path.realpath does the trick:

>>> import os
>>> f = open('file.txt')
>>> os.path.realpath(f.name)

MySQL combine two columns into one column

For the MySQL fans out there, I like the IFNULL() function. Other answers here suggest similar functionality with the ISNULL() function in some implementations. In my situation, I have a column of descriptions which is NOT NULL, and a column of serial numbers which may be NULL This is how I combined them into one column:

SELECT CONCAT(description,IFNULL(' SN: ', serial_number),'')) FROM my_table;

My results suggest that the results of concatenating a string with NULL results in a NULL. I have been getting the alternative value in those cases.

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

Put this in C2 and copy down

=IF(ISNA(VLOOKUP(A2,$B$2:$B$65535,1,FALSE)),"not in B","")

Then if the value in A isn't in B the cell in column C will say "not in B".

What does "dereferencing" a pointer mean?

A pointer is a "reference" to a value.. much like a library call number is a reference to a book. "Dereferencing" the call number is physically going through and retrieving that book.

int a=4 ;
int *pA = &a ;
printf( "The REFERENCE/call number for the variable `a` is %p\n", pA ) ;

// The * causes pA to DEREFERENCE...  `a` via "callnumber" `pA`.
printf( "%d\n", *pA ) ; // prints 4.. 

If the book isn't there, the librarian starts shouting, shuts the library down, and a couple of people are set to investigate the cause of a person going to find a book that isn't there.

How to test an Internet connection with bash?

For the fastest result, ping a DNS server:

ping -c1 "8.8.8.8" &>"/dev/null"

if [[ "${?}" -ne 0 ]]; then
    echo "offline"
elif [[ "${#args[@]}" -eq 0 ]]; then
    echo "online"
fi

Available as a standalone command: linkStatus

linking problem: fatal error LNK1112: module machine type 'x64' conflicts with target machine type 'X86'

Thanks for the answers guys. My problem was that I changed a x64 solution in Visual Studio to 32 bit in the Configuration Manager only. I ended up just creating a new solution as 32 bit and then copying my C++ code and this error was gone. I think l00g33k and RogerAttrill's suggestions may have been the solution, but mine worked, too.

jQuery: How can I show an image popup onclick of the thumbnail?

I like prettyPhoto

prettyPhoto is a jQuery lightbox clone. Not only does it support images, it also support for videos, flash, YouTube, iframes and ajax. It’s a full blown media lightbox

cmake error 'the source does not appear to contain CMakeLists.txt'

You should do mkdir build and cd build while inside opencv folder, not the opencv-contrib folder. The CMakeLists.txt is there.

TypeError: 'tuple' object does not support item assignment when swapping values

Evaluating "1,2,3" results in (1, 2, 3), a tuple. As you've discovered, tuples are immutable. Convert to a list before processing.

How to append a char to a std::string?

I test the several propositions by running them into a large loop. I used microsoft visual studio 2015 as compiler and my processor is an i7, 8Hz, 2GHz.

    long start = clock();
    int a = 0;
    //100000000
    std::string ret;
    for (int i = 0; i < 60000000; i++)
    {
        ret.append(1, ' ');
        //ret += ' ';
        //ret.push_back(' ');
        //ret.insert(ret.end(), 1, ' ');
        //ret.resize(ret.size() + 1, ' ');
    }
    long stop = clock();
    long test = stop - start;
    return 0;

According to this test, results are :

     operation             time(ms)            note
------------------------------------------------------------------------
append                     66015
+=                         67328      1.02 time slower than 'append'
resize                     83867      1.27 time slower than 'append'
push_back & insert         90000      more than 1.36 time slower than 'append'

Conclusion

+= seems more understandable, but if you mind about speed, use append

regex pattern to match the end of a string

Something like this should work: /([^/]*)$

What language are you using? End-of-string regex signifiers can vary in different languages.

How to increase application heap size in Eclipse?

In Eclipse Folder there is eclipse.ini file. Increase size -Xms512m -Xmx1024m

Regex for parsing directory and filename

What about this?

[/]{0,1}([^/]+[/])*([^/]*)

Deterministic :

((/)|())([^/]+/)*([^/]*)

Strict :

^[/]{0,1}([^/]+[/])*([^/]*)$
^((/)|())([^/]+/)*([^/]*)$

How to access JSON Object name/value?

Here is a friendly piece of advice. Use something like Chrome Developer Tools or Firebug for Firefox to inspect your Ajax calls and results.

You may also want to invest some time in understanding a helper library like Underscore, which complements jQuery and gives you 60+ useful functions for manipulating data objects with JavaScript.

Node.js heap out of memory

In my case I had ran npm install on previous version of node, after some day I upgraded node version and ram npm install for few modules. After this I was getting this error. To fix this problem I deleted node_module folder from each project and ran npm install again.

Hope this might fix the problem.

Note : This was happening on my local machine and it got fixed on local machine only.

Set port for php artisan.php serve

You can use

php artisan serve --port 80

Works on Windows platform

MySQL Orderby a number, Nulls last

Why don't you order by NULLS LAST?

SELECT * 
FROM tablename
WHERE visible = 1 
ORDER BY position ASC NULLS LAST, id DESC 

How to POST a FORM from HTML to ASPX page

You sure can.

The easiest way to see how you might do this is to browse to the aspx page you want to post to. Then save the source of that page as HTML. Change the action of the form on your new html page to point back to the aspx page you originally copied it from.

Add value tags to your form fields and put the data you want in there, then open the page and hit the submit button.

Cookies vs. sessions

TL;DR

Criteria / factors Sessions Cookies
Epoch (start of existence) Created BEFORE an HTTP response Created AFTER an HTTP response
Availability during the first HTTP request YES NO
Availability during the succeeding HTTP requests YES YES
Ultimate control for the data and expiration Server administrator End-user
Default expiration Expires earlier than cookies Lasts longer than sessions
Server costs Memory Memory
Network costs None Unnecessary extra bytes
Browser costs None Memory
Security Difficult to hijack Easy to hijack
Deprecation None Now discouraged in favor of the JavaScript "Web Storage"

Details

Advantages and disadvantages are subjective. They can result in a dichotomy (an advantage for some, but considered disadvantage for others). Instead, I laid out above the factors that can help you decide which one to pick.

Existence during the first HTTP request-and-response

Let's just say you are a server-side person who wants to process both the session and cookie. The first HTTP handshake will go like so:

  1. Browser prepares the HTTP request -- SESSIONS: not available; COOKIES: not available
  2. Browser sends the HTTP request
  3. Server receives the HTTP request
  4. Server processes the HTTP request -- SESSIONS: existed; COOKIES: cast
  5. Server sends the HTTP response
  6. Browser receives the HTTP response
  7. Browser processes the HTTP response -- SESSIONS: not available; COOKIES: existed

In step 1, the browser have no idea of the contents of both sessions and cookies. In step 4, the server can have the opportunity to set the values of the session and cookies.

Availability during the succeeding HTTP requests-and-responses

  1. Browser prepares the HTTP request -- SESSIONS: not available; COOKIES: available
  2. Browser sends the HTTP request
  3. Server receives the HTTP request
  4. Server processes the HTTP request -- SESSIONS: available; COOKIES: available
  5. Server sends the HTTP response
  6. Browser receives the HTTP response
  7. Browser processes the HTTP response -- SESSIONS: not available; COOKIES: available

Payload

Let's say in a single web page you are loading 20 resources hosted by example.com, those 20 resources will carry extra bytes of information about the cookies. Even if it's just a resource request for CSS or a JPG image, it would still carry cookies in their headers on the way to the server. Should an HTTP request to a JPG resource carry a bunch of unnecessary cookies?

Deprecation

There is no replacement for sessions. For cookies, there are many other options in storing data in the browser rather than the old school cookies.

Storing of user data

Session is safer for storing user data because it can not be modified by the end-user and can only be set on the server-side. Cookies on the other hand can be hijacked because they are just stored on the browser.

submit the form using ajax

I would suggest to use jquery for this type of requirement . Give this a try

<div id="commentList"></div>
<div id="addCommentContainer">
    <p>Add a Comment</p> <br/> <br/>
    <form id="addCommentForm" method="post" action="">
        <div>
            Your Name <br/>
            <input type="text" name="name" id="name" />


            <br/> <br/>
            Comment Body <br/>
            <textarea name="body" id="body" cols="20" rows="5"></textarea>

            <input type="submit" id="submit" value="Submit" />
        </div>
    </form>
</div>?

$(document).ready(function(){
    /* The following code is executed once the DOM is loaded */

    /* This flag will prevent multiple comment submits: */
    var working = false;
    $("#submit").click(function(){
    $.ajax({
         type: 'POST',
         url: "mysubmitpage.php",
         data: $('#addCommentForm').serialize(), 
         success: function(response) {
            alert("Submitted comment"); 
             $("#commentList").append("Name:" + $("#name").val() + "<br/>comment:" + $("#body").val());
         },
        error: function() {
             //$("#commentList").append($("#name").val() + "<br/>" + $("#body").val());
            alert("There was an error submitting comment");
        }
     });
});
});?

open a url on click of ok button in android

No need for any Java or Kotlin code to make it a clickable link, now you just need to follow given below code. And you can also link text color change by using textColorLink.

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autoLink="web"
android:textColorLink="@color/white"/>

What is function overloading and overriding in php?

Although overloading paradigm is not fully supported by PHP the same (or very similar) effect can be achieved with default parameter(s) (as somebody mentioned before).

If you define your function like this:

function f($p=0)
{
  if($p)
  {
    //implement functionality #1 here
  }
  else
  {
    //implement functionality #2 here
  }
}

When you call this function like:

f();

you'll get one functionality (#1), but if you call it with parameter like:

f(1);

you'll get another functionality (#2). That's the effect of overloading - different functionality depending on function's input parameter(s).

I know, somebody will ask now what functionality one will get if he/she calls this function as f(0).

How to post ASP.NET MVC Ajax form using JavaScript rather than submit button

Try the following way:

<input type="submit" value="Search" class="search-btn" />
<a href="javascript:;" onclick="$('.search-btn').click();">Go</a>

How to register multiple implementations of the same interface in Asp.Net Core?

You're correct, the built in ASP.NET Core container does not have the concept of registering multiple services and then retrieving a specific one, as you suggest, a factory is the only real solution in that case.

Alternatively, you could switch to a third party container like Unity or StructureMap that does provide the solution you need (documented here: https://docs.asp.net/en/latest/fundamentals/dependency-injection.html?#replacing-the-default-services-container).

NSString with \n or line break

I found that when I was reading strings in from a .plist file, occurrences of "\n" were parsed as "\\n". The solution for me was to replace occurrences of "\\n" with "\n". For example, given an instance of NSString named myString read in from my .plist file, I had to call...

myString = [myString stringByReplacingOccurrencesOfString:@"\\n" withString:@"\n"];

... before assigning it to my UILabel instance...

myLabel.text = myString;

Efficiently checking if arbitrary object is NaN in Python / numpy / pandas?

I found this brilliant solution here, it uses the simple logic NAN!=NAN. https://www.codespeedy.com/check-if-a-given-string-is-nan-in-python/

Using above example you can simply do the following. This should work on different type of objects as it simply utilize the fact that NAN is not equal to NAN.

 import numpy as np
 s = pd.Series(['apple', np.nan, 'banana'])
 s.apply(lambda x: x!=x)
 out[252]
 0    False
 1     True
 2    False
 dtype: bool

Authentication plugin 'caching_sha2_password' cannot be loaded

you can change the encryption of the password like this.

ALTER USER 'yourusername'@'localhost' IDENTIFIED WITH mysql_native_password BY 'youpassword';

Fast way to get the min/max values among properties of object

Using the lodash library you can write shorter

_({ "a":4, "b":0.5 , "c":0.35, "d":5 }).values().max();

php convert datetime to UTC

Convert local time zone string to UTC string.
e.g. New Zealand Time Zone

$datetime = "2016-02-01 00:00:01";
$given = new DateTime($datetime, new DateTimeZone("Pacific/Auckland"));
$given->setTimezone(new DateTimeZone("UTC"));
$output = $given->format("Y-m-d H:i:s"); 
echo ($output);
  • NZDT: UTC+13:00
    if $datetime = "2016-02-01 00:00:01", $output = "2016-01-31 11:00:01";
    if $datetime = "2016-02-29 23:59:59", $output = "2016-02-29 10:59:59";
  • NZST: UTC+12:00
    if $datetime = "2016-05-01 00:00:01", $output = "2016-04-30 12:00:01";
    if $datetime = "2016-05-31 23:59:59", $output = "2016-05-31 11:59:59";

https://en.wikipedia.org/wiki/Time_in_New_Zealand

Typescript: React event types

For those who are looking for a solution to get an event and store something, in my case a HTML 5 element, on a useState here's my solution:

const [anchorElement, setAnchorElement] = useState<HTMLButtonElement | null>(null);

const handleMenu = (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) : void => {
    setAnchorElement(event.currentTarget);
};

Launch custom android application from android browser

You need to add a pseudo-hostname to the CALLBACK_URL 'app://' doesn't make sense as a URL and cannot be parsed.

How to store image in SQL Server database tables column

Insert Into FEMALE(ID, Image)
Select '1', BulkColumn 
from Openrowset (Bulk 'D:\thepathofimage.jpg', Single_Blob) as Image

You will also need admin rights to run the query.

Multiprocessing vs Threading Python

Python documentation quotes

The canonical version of this answer is now at the dupliquee question: What are the differences between the threading and multiprocessing modules?

I've highlighted the key Python documentation quotes about Process vs Threads and the GIL at: What is the global interpreter lock (GIL) in CPython?

Process vs thread experiments

I did a bit of benchmarking in order to show the difference more concretely.

In the benchmark, I timed CPU and IO bound work for various numbers of threads on an 8 hyperthread CPU. The work supplied per thread is always the same, such that more threads means more total work supplied.

The results were:

enter image description here

Plot data.

Conclusions:

  • for CPU bound work, multiprocessing is always faster, presumably due to the GIL

  • for IO bound work. both are exactly the same speed

  • threads only scale up to about 4x instead of the expected 8x since I'm on an 8 hyperthread machine.

    Contrast that with a C POSIX CPU-bound work which reaches the expected 8x speedup: What do 'real', 'user' and 'sys' mean in the output of time(1)?

    TODO: I don't know the reason for this, there must be other Python inefficiencies coming into play.

Test code:

#!/usr/bin/env python3

import multiprocessing
import threading
import time
import sys

def cpu_func(result, niters):
    '''
    A useless CPU bound function.
    '''
    for i in range(niters):
        result = (result * result * i + 2 * result * i * i + 3) % 10000000
    return result

class CpuThread(threading.Thread):
    def __init__(self, niters):
        super().__init__()
        self.niters = niters
        self.result = 1
    def run(self):
        self.result = cpu_func(self.result, self.niters)

class CpuProcess(multiprocessing.Process):
    def __init__(self, niters):
        super().__init__()
        self.niters = niters
        self.result = 1
    def run(self):
        self.result = cpu_func(self.result, self.niters)

class IoThread(threading.Thread):
    def __init__(self, sleep):
        super().__init__()
        self.sleep = sleep
        self.result = self.sleep
    def run(self):
        time.sleep(self.sleep)

class IoProcess(multiprocessing.Process):
    def __init__(self, sleep):
        super().__init__()
        self.sleep = sleep
        self.result = self.sleep
    def run(self):
        time.sleep(self.sleep)

if __name__ == '__main__':
    cpu_n_iters = int(sys.argv[1])
    sleep = 1
    cpu_count = multiprocessing.cpu_count()
    input_params = [
        (CpuThread, cpu_n_iters),
        (CpuProcess, cpu_n_iters),
        (IoThread, sleep),
        (IoProcess, sleep),
    ]
    header = ['nthreads']
    for thread_class, _ in input_params:
        header.append(thread_class.__name__)
    print(' '.join(header))
    for nthreads in range(1, 2 * cpu_count):
        results = [nthreads]
        for thread_class, work_size in input_params:
            start_time = time.time()
            threads = []
            for i in range(nthreads):
                thread = thread_class(work_size)
                threads.append(thread)
                thread.start()
            for i, thread in enumerate(threads):
                thread.join()
            results.append(time.time() - start_time)
        print(' '.join('{:.6e}'.format(result) for result in results))

GitHub upstream + plotting code on same directory.

Tested on Ubuntu 18.10, Python 3.6.7, in a Lenovo ThinkPad P51 laptop with CPU: Intel Core i7-7820HQ CPU (4 cores / 8 threads), RAM: 2x Samsung M471A2K43BB1-CRC (2x 16GiB), SSD: Samsung MZVLB512HAJQ-000L7 (3,000 MB/s).

Visualize which threads are running at a given time

This post https://rohanvarma.me/GIL/ taught me that you can run a callback whenever a thread is scheduled with the target= argument of threading.Thread and the same for multiprocessing.Process.

This allows us to view exactly which thread runs at each time. When this is done, we would see something like (I made this particular graph up):

            +--------------------------------------+
            + Active threads / processes           +
+-----------+--------------------------------------+
|Thread   1 |********     ************             |
|         2 |        *****            *************|
+-----------+--------------------------------------+
|Process  1 |***  ************** ******  ****      |
|         2 |** **** ****** ** ********* **********|
+-----------+--------------------------------------+
            + Time -->                             +
            +--------------------------------------+

which would show that:

  • threads are fully serialized by the GIL
  • processes can run in parallel

Android ADB stop application command like "force-stop" for non rooted device

To kill from the application, you can do:

android.os.Process.killProcess(android.os.Process.myPid());

Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods

We have found that adding the Apptentive cocoa pod to an existing Xcode project may potentially not include some of our required frameworks.

Check your linker flags:

Target > Build Settings > Other Linker Flags 

You should see -lApptentiveConnect listed as a linker flag:

... -ObjC -lApptentiveConnect ... 

You should also see our required Frameworks listed:

  • Accelerate
  • CoreData
  • CoreText
  • CoreGraphics
  • CoreTelephony
  • Foundation
  • QuartzCore
  • StoreKit
  • SystemConfiguration
  • UIKit

    -ObjC -lApptentiveConnect -framework Accelerate -framework CoreData -framework CoreGraphics -framework CoreText -framework Foundation -framework QuartzCore -framework SystemConfiguration -framework UIKit -framework CoreTelephony -framework StoreKit  

Remove .php extension with .htaccess

I found 100% working Concept for me:

# Options is required by Many Hosting
Options +MultiViews

RewriteEngine on

# For .php & .html URL's:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]
RewriteRule ^([^\.]+)$ $1.html [NC,L]

Use this code in Root of your website .htaccess file like :

offline - wamp\www\YourWebDir

online - public_html/

If it doesn't work correct, then change the settings of your Wamp Server: 1) Left click WAMP icon 2) Apache 3) Apache Modules 4) Left click rewrite_module

Find duplicates and delete all in notepad++

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

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

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

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

MySQL Removing Some Foreign keys

As explained here, seems the foreign key constraint has to be dropped by constraint name and not the index name.

The syntax is:

ALTER TABLE footable DROP FOREIGN KEY fooconstraint;

CSS media queries: max-width OR max-height

Use a comma to specify two (or more) different rules:

@media screen and (max-width: 995px), 
       screen and (max-height: 700px) {
  ...
}

From https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries

Commas are used to combine multiple media queries into a single rule. Each query in a comma-separated list is treated separately from the others. Thus, if any of the queries in a list is true, the entire media statement returns true. In other words, lists behave like a logical or operator.

How to make a button redirect to another page using jQuery or just Javascript

You can use:

  location.href = "newpage.html"

in the button's onclick event.

How can I get the active screen dimensions?

in C# winforms I have got start point (for case when we have several monitor/diplay and one form is calling another one) with help of the following method:

private Point get_start_point()
    {
        return
            new Point(Screen.GetBounds(parent_class_with_form.ActiveForm).X,
                      Screen.GetBounds(parent_class_with_form.ActiveForm).Y
                      );
    }

How to check if a subclass is an instance of a class at runtime?

Maybe I'm missing something, but wouldn't this suffice:

if (view instanceof B) {
    // this view is an instance of B
}

Full width image with fixed height

<div id="container">
    <img style="width: 100%; height: 40%;" id="image" src="...">
</div>

I hope this will serve your purpose.

Failed to load resource 404 (Not Found) - file location error?

Looks like the path you gave doesn't have any bootstrap files in them.

href="~/lib/bootstrap/dist/css/bootstrap.min.css"

Make sure the files exist over there , else point the files to the correct path, which should be in your case

href="~/node_modules/bootstrap/dist/css/bootstrap.min.css"

How do I get the real .height() of a overflow: hidden or overflow: scroll div?

Other possibility would be place the html in a non overflow:hidden element placed 'out' of screen, like a position absolute top and left lesse then 5000px, then read this elements height. Its ugly, but work well.

Sublime Text 2: How to delete blank/empty lines

Their is a more easily way to do that without regex. you have just to select the whole text. then go to: Edit--> Permute Lines --> Unique.

That's all. and all blank lines will be deleted.

Python - TypeError: 'int' object is not iterable

Your problem is with this line:

number4 = list(cow[n])

It tries to take cow[n], which returns an integer, and make it a list. This doesn't work, as demonstrated below:

>>> a = 1
>>> list(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>>

Perhaps you meant to put cow[n] inside a list:

number4 = [cow[n]]

See a demonstration below:

>>> a = 1
>>> [a]
[1]
>>>

Also, I wanted to address two things:

  1. Your while-statement is missing a : at the end.
  2. It is considered very dangerous to use input like that, since it evaluates its input as real Python code. It would be better here to use raw_input and then convert the input to an integer with int.

To split up the digits and then add them like you want, I would first make the number a string. Then, since strings are iterable, you can use sum:

>>> a = 137
>>> a = str(a)
>>> # This way is more common and preferred
>>> sum(int(x) for x in a)
11
>>> # But this also works
>>> sum(map(int, a))
11
>>>

How do I remove repeated elements from ArrayList?

ArrayList<String> city=new ArrayList<String>();
city.add("rajkot");
city.add("gondal");
city.add("rajkot");
city.add("gova");
city.add("baroda");
city.add("morbi");
city.add("gova");

HashSet<String> hashSet = new HashSet<String>();
hashSet.addAll(city);
city.clear();
city.addAll(hashSet);
Toast.makeText(getActivity(),"" + city.toString(),Toast.LENGTH_SHORT).show();

Android notification is not showing

I had the same issue with my Android app. I was trying out notifications and found that notifications were showing on my Android emulator which ran a Android 7.0 (Nougat) system, whereas it wasn't running on my phone which had Android 8.1 (Oreo).

After reading the documentation, I found that Android had a feature called notification channel, without which notifications won't show up on Oreo devices. Below is the link to official Android documentation on notification channels.

What are the differences between B trees and B+ trees?

The principal advantage of B+ trees over B trees is they allow you to pack in more pointers to other nodes by removing pointers to data, thus increasing the fanout and potentially decreasing the depth of the tree.

The disadvantage is that there are no early outs when you might have found a match in an internal node. But since both data structures have huge fanouts, the vast majority of your matches will be on leaf nodes anyway, making on average the B+ tree more efficient.

Connecting to local SQL Server database using C#

If you use SQL authentication, use this:

using System.Data.SqlClient;

SqlConnection conn = new SqlConnection();
conn.ConnectionString = 
     "Data Source=.\SQLExpress;" + 
     "User Instance=true;" + 
     "User Id=UserName;" + 
     "Password=Secret;" + 
     "AttachDbFilename=|DataDirectory|Database1.mdf;"
conn.Open();

If you use Windows authentication, use this:

using System.Data.SqlClient;
SqlConnection conn = new SqlConnection();
conn.ConnectionString = 
     "Data Source=.\SQLExpress;" + 
     "User Instance=true;" + 
     "Integrated Security=true;" + 
     "AttachDbFilename=|DataDirectory|Database1.mdf;"
conn.Open();

What is PECS (Producer Extends Consumer Super)?

Remember this:

Consumer eat supper(super); Producer extends his parent's factory

How to fix "Attempted relative import in non-package" even with __init__.py

As Paolo said, we have 2 invocation methods:

1) python -m tests.core_test
2) python tests/core_test.py

One difference between them is sys.path[0] string. Since the interpret will search sys.path when doing import, we can do with tests/core_test.py:

if __name__ == '__main__':
    import sys
    from pathlib import Path
    sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
    from components import core
    <other stuff>

And more after this, we can run core_test.py with other methods:

cd tests
python core_test.py
python -m core_test
...

Note, py36 tested only.

How do I get first element rather than using [0] in jQuery?

You can use the first selector.

var header = $('.header:first')

Get the closest number out of an array

#include <algorithm>
#include <iostream>
#include <cmath>

using namespace std;

class CompareFunctor
{

public:
    CompareFunctor(int n) { _n = n; }
    bool operator()(int & val1, int & val2)
    {
        int diff1 = abs(val1 - _n);
        int diff2 = abs(val2 - _n);
        return (diff1 < diff2);
    }

private:
    int _n;
};

int Find_Closest_Value(int nums[], int size, int n)
{
    CompareFunctor cf(n);
    int cn = *min_element(nums, nums + size, cf);
    return cn;
}

int main()
{
    int nums[] = { 2, 42, 82, 122, 162, 202, 242, 282, 322, 362 };
    int size = sizeof(nums) / sizeof(int);
    int n = 80;
    int cn = Find_Closest_Value(nums, size, n);
    cout << "\nClosest value = " << cn << endl;
    cin.get();
}

Bootstrap 3 Collapse show state with Chevron icon

Here's a couple of pure css helper classes which lets you handle any kind of toggle content right in your html.

It works with any element you need to switch. Whatever your layout is you just put it inside a couple of elements with the .if-collapsed and .if-not-collapsed classes within the toggle element.

The only catch is that you have to make sure you put the desired initial state of the toggle. If it's initially closed, then put a collapsed class on the toggle.

It also requires the :not selector, it doesn't work on IE8.

HTML example:

<a class="btn btn-primary collapsed" data-toggle="collapse" href="#collapseExample">
  <!--You can put any valid html inside these!-->
  <span class="if-collapsed">Open</span>
  <span class="if-not-collapsed">Close</span>
</a>
<div class="collapse" id="collapseExample">
  <div class="well">
    ...
  </div>
</div>

Less version:

[data-toggle="collapse"] {
    &.collapsed .if-not-collapsed {
         display: none;
    }
    &:not(.collapsed) .if-collapsed {
         display: none;
    }
}

CSS version:

[data-toggle="collapse"].collapsed .if-not-collapsed {
  display: none;
}
[data-toggle="collapse"]:not(.collapsed) .if-collapsed {
  display: none;
}

Converting from hex to string

Your reference to "0x31 = 1" makes me think you're actually trying to convert ASCII values to strings - in which case you should be using something like Encoding.ASCII.GetString(Byte[])

Storing a Key Value Array into a compact JSON string

If the logic parsing this knows that {"key": "slide0001.html", "value": "Looking Ahead"} is a key/value pair, then you could transform it in an array and hold a few constants specifying which index maps to which key.

For example:

var data = ["slide0001.html", "Looking Ahead"];

var C_KEY = 0;
var C_VALUE = 1;

var value = data[C_VALUE];

So, now, your data can be:

[
    ["slide0001.html", "Looking Ahead"],
    ["slide0008.html", "Forecast"],
    ["slide0021.html", "Summary"]
]

If your parsing logic doesn't know ahead of time about the structure of the data, you can add some metadata to describe it. For example:

{ meta: { keys: [ "key", "value" ] },
  data: [
    ["slide0001.html", "Looking Ahead"],
    ["slide0008.html", "Forecast"],
    ["slide0021.html", "Summary"]
  ]
}

... which would then be handled by the parser.

SOAP-UI - How to pass xml inside parameter

To send CDATA in a request object use the SoapObject.setInnerText("..."); method.

HTTP Get with 204 No Content: Is that normal

Http GET returning 204 is perfectly fine, and so is returning 404.

The important thing is that you define the design standards/guidelines for your API, so that all your endpoints use status codes consistently.

For example:

  • you may indicate that a GET endpoint that returns a collection of resources will return 204 if the collection is empty. In this case GET /complaints/year/2019/month/04 may return 204 if there are no complaints filed in April 2019. This is not an error on the client side, so we return a success status code (204). OTOH, GET /complaints/12345 may return 404 if complaint number 12345 doesn't exist.
  • if your API uses HATEOAS, 204 is probably a bad idea because the response should contain links to navigate to other states.

Parse JSON String to JSON Object in C#.NET

Another choice besides JObject is System.Json.JsonValue for Weak-Typed JSON object.

It also has a JsonValue blob = JsonValue.Parse(json); you can use. The blob will most likely be of type JsonObject which is derived from JsonValue, but could be JsonArray. Check the blob.JsonType if you need to know.

And to answer you question, YES, you may replace json with the name of your actual variable that holds the JSON string. ;-D

There is a System.Json.dll you should add to your project References.

-Jesse

How to check the input is an integer or not in Java?

        String input = "";
        int inputInteger = 0;
        BufferedReader br    = new BufferedReader(new InputStreamReader (System.in));

        System.out.println("Enter the radious: ");
        try {
            input = br.readLine();
            inputInteger = Integer.parseInt(input);
        } catch (NumberFormatException e) {
            System.out.println("Please Enter An Integer");
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        float area = (float) (3.14*inputInteger*inputInteger);
        System.out.println("Area = "+area);

How do I get a file's last modified time in Perl?

Use the builtin stat function. Or more specifically:

my $modtime = (stat($fh))[9]

Clean up a fork and restart it from the upstream

How to do it 100% through the Sourcetree GUI

(Not everyone likes doing things through the git command line interface)

Once this has been set up, you only need to do steps 7-13 from then on.

Fetch > checkout master branch > reset to their master > Push changes to server

Steps

  1. In the menu toolbar at the top of the screen: "Repository" > "Repository settings"

"Repository" highlighted in the top menu bar

  1. "Add"

"Add" button at the bottom of the dialog

  1. Go back to GitHub and copy the clone URL.

"Clone or Download" button on the Github website followed by the git url

  1. Paste the url into the "URL / Path" field then give it a name that makes sense. I called it "master". Do not check the "Default remote" checkbox. You will not be able to push directly to this repository.

"Remote name" and "URL / Path" fields highlighted in the"Remote details" dialog

  1. Press "OK" and you should see it appear in your list of repositories now.

"master" repository added to the list of repositories in the "Repository settings" dialog

  1. Press "OK" again and you should see it appear in your list of "Remotes".

"master" repository highlighted in remotes list in side bar

  1. Click the "Fetch" button (top left of the Source tree header area)

"Fetch" button in the header area

  1. Make sure the "Fetch from all remotes" checkbox is checked and press "ok"

"Fetch from all remotes" checkbox highlighted in the "Fetch" dialog

  1. Double click on your "master" branch to check it out if it is not checked out already.

  2. Find the commit that you want to reset to, if you called the repo "master" you will most likely want to find the commit with the "master/master" tag on it.

Example of a commit with a "master/master" tag on it

  1. Right click on the commit > "Reset current branch to this commit".

  2. In the dialog, set the "Using mode:" field to "Hard - discard all working copy changes" then press "OK" (make sure to put any changes that you don't want to lose onto a separate branch first).

"Using mode" field highlighted in the "Reset to commit" dialog. It is set to "discard all working copy changes"

  1. Click the "Push" button (top left of the Source tree header area) to upload the changes to your copy of the repo.

"Push" button in the header area

Your Done!

fcntl substitute on Windows

Although this does not help you right away, there is an alternative that can work with both Unix (fcntl) and Windows (win32 api calls), called: portalocker

It describes itself as a cross-platform (posix/nt) API for flock-style file locking for Python. It basically maps fcntl to win32 api calls.

The original code at http://code.activestate.com/recipes/65203/ can now be installed as a separate package - https://pypi.python.org/pypi/portalocker

How can I avoid getting this MySQL error Incorrect column specifier for column COLUMN NAME?

I was having the same problem, but using Long type. I changed for INT and it worked for me.

CREATE TABLE lists (
 id INT NOT NULL AUTO_INCREMENT,
 desc varchar(30),
 owner varchar(20),
 visibility boolean,
 PRIMARY KEY (id)
 );

Full-screen responsive background image

This worked for me, so posting this.

.my-container {
  position: relative;
  background: #696969;
  overflow: hidden;
}
.my-container:before {
  content: ' ';
  display: block;
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
  opacity: 0.6;
  background-image: url('https://images.pexels.com/photos/1084542/pexels-photo-1084542.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260');
  background-repeat: no-repeat;
  background-position: 50% 0;
  -ms-background-size: cover;
  -o-background-size: cover;
  -moz-background-size: cover;
  -webkit-background-size: cover;
  background-size: cover;
}

creating list of objects in Javascript

dynamically build list of objects

var listOfObjects = [];
var a = ["car", "bike", "scooter"];
a.forEach(function(entry) {
    var singleObj = {};
    singleObj['type'] = 'vehicle';
    singleObj['value'] = entry;
    listOfObjects.push(singleObj);
});

here's a working example http://jsfiddle.net/b9f6Q/2/ see console for output

How to stop/cancel 'git log' command in terminal?

You can hit the key q (for quit) and it should take you to the prompt.

Please see this link.

Read .doc file with python

I agree with Shivam's answer except for textract doesn't exist for windows. And, for some reason antiword also fails to read the '.doc' files and gives an error:

'filename.doc' is not a word document. # This happens when the file wasn't generated via MS Office. Eg: Web-pages may be stored in .doc format offline.

So, I've got the following workaround to extract the text:

from bs4 import BeautifulSoup as bs
soup = bs(open(filename).read())
[s.extract() for s in soup(['style', 'script'])]
tmpText = soup.get_text()
text = "".join("".join(tmpText.split('\t')).split('\n')).encode('utf-8').strip()
print text

This script will work with most kinds of files. Have fun!

Execution failed for task ':app:processDebugResources' even with latest build tools

I want to add that sometimes android studio loses track of the resources file and can't build on launch. If the above answers are to no avail, try

Build => Rebuild Project

I lost many hours to this when I was a beginner at Android Studio.

Read XML file using javascript

If you get this from a Webserver, check out jQuery. You can load it, using the Ajax load function and select the node or text you want, using Selectors.

If you don't want to do this in a http environment or avoid using jQuery, please explain in greater detail.

"Initializing" variables in python?

Python treats comma on the left hand side of equal sign ( = ) as an input splitter, Very useful for functions that return a tuple.

e.g,

x,y = (5,2)

What you want to do is:

grade_1 = grade_2 = grade_3 = average = 0.0

though that might not be the most clear way to write it.

Adding 30 minutes to time formatted as H:i in PHP

In order for that to work $time has to be a timestamp. You cannot pass in "10:00" or something like $time = date('H:i', '10:00'); which is what you seem to do, because then I get 0:30 and 1:30 as results too.

Try

$time = strtotime('10:00');

As an alternative, consider using DateTime (the below requires PHP 5.3 though):

$dt = DateTime::createFromFormat('H:i', '10:00'); // create today 10 o'clock
$dt->sub(new DateInterval('PT30M'));              // substract 30 minutes
echo $dt->format('H:i');                          // echo modified time
$dt->add(new DateInterval('PT1H'));               // add 1 hour
echo $dt->format('H:i');                          // echo modified time

or procedural if you don't like OOP

$dateTime = date_create_from_format('H:i', '10:00');
date_sub($dateTime, date_interval_create_from_date_string('30 minutes'));
echo date_format($dateTime, 'H:i');
date_add($dateTime, date_interval_create_from_date_string('1 hour'));
echo date_format($dateTime, 'H:i');

How to clear the JTextField by clicking JButton

Looking for EventHandling, ActionListener?

or code?

JButton b = new JButton("Clear");
b.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
        textfield.setText("");
        //textfield.setText(null); //or use this
    }
});

Also See
How to Use Buttons

Tensorflow r1.0 : could not a find a version that satisfies the requirement tensorflow

Tensorflow requires a 64-bit version of Python.

Additionally, it only supports Python 3.5.x through Python 3.8.x.

If you're using a 32-bit version of Python or a version that's too old or new, then you'll get that error message.

To fix it, you can install the 64-bit version of Python 3.8.6 via Python's website.

Multiple conditions in if statement shell script

if using /bin/sh you can use:

if [ <condition> ] && [ <condition> ]; then
    ...
fi

if using /bin/bash you can use:

if [[ <condition> && <condition> ]]; then
    ...
fi

Generate sql insert script from excel worksheet

You can use the following excel statement:

="INSERT INTO table_name(`"&$A$1&"`,`"&$B$1&"`,`"&$C$1&"`, `"&$D$1&"`) VALUES('"&SUBSTITUTE(A2, "'", "\'")&"','"&SUBSTITUTE(B2, "'", "\'")&"','"&SUBSTITUTE(C2, "'", "\'")&"', "&D2&");"

This improves upon Hart CO's answer as it takes into account column names and gets rid of compile errors due to quotes in the column. The final column is an example of a numeric value column, without quotes.

Direct download from Google Drive using Google Drive API

Using a Service Account might work for you.

Parsing arguments to a Java command line program

You could use the refcodes-console artifact at refcodes-console on REFCODES.ORG:

Option<String> r     = new StringOptionImpl( "-r", null, "opt1", "..." );
Option<String> s     = new StringOptionImpl( "-S", null, "opt2", "..." );
Operand<String> arg1 = new StringOperandImpl( "arg1", "..." );
Operand<String> arg2 = new StringOperandImpl( "arg2", "..." );
Operand<String> arg3 = new StringOperandImpl( "arg3", "..." );
Operand<String> arg4 = new StringOperandImpl( "arg4", "..." );
Switch test          = new SwitchImpl( null, "--test", "..." );
Option<String> a     = new StringOptionImpl( "-A", null, "opt3", "..." );
Condition theRoot    = new AndConditionImpl( r, s, a, arg1, arg2, arg3, arg4,
    test );

Create your arguments parser ArgsParserImpl with your root condition:

ArgsParser theArgsParser = new ArgsParserImpl( theRoot );
theArgsParser.setName( "MyProgramm" );
theArgsParser.setSyntaxNotation( SyntaxNotation.GNU_POSIX );

Above you define your syntax, below you invoke the parser:

theArgsParser.printUsage();
theArgsParser.printSeparatorLn();
theArgsParser.printOptions();
theArgsParser.evalArgs( new String[] {
    "-r", "RRRRR", "-S", "SSSSS", "11111", "22222", "33333", "44444", 
    "--test", "-A", "AAAAA"
} );

In case you provided some good descriptions, theArgsParser.printUsage() will even show you the pretty printed usage:

Usage: MyProgramm -r <opt1> -S <opt2> -A <opt3> arg1 arg2 arg3 arg4 --test

In the above example all defined arguments must be passed by the user, else the parser will detect a wrong usage. In case the --test switch is to be optional (or any other argument), assign theRoot as follows:

theRoot = new AndConditionImpl( r, s, a, arg1, arg2, arg3, arg4, new OptionalImpl( test ) );

Then your syntax looks as follows:

Usage: MyProgramm -r <opt1> -S <opt2> -A <opt3> arg1 arg2 arg3 arg4 [--test]

The full example for your case you find in the StackOverFlowExamle. You can use AND, OR, XOR conditions and any kind of nesting ... hope this helps.

Evaluate the parsed arguments as follows: r.getValue() ); or if (test.getValue() == true) ...:

LOGGER.info( "r    :=" + r.getValue() );
LOGGER.info( "S    :=" + s.getValue() );
LOGGER.info( "arg1 :=" + arg1.getValue() );
LOGGER.info( "arg2 :=" + arg2.getValue() );
LOGGER.info( "arg3 :=" + arg3.getValue() );
LOGGER.info( "arg4 :=" + arg4.getValue() );
LOGGER.info( "test :=" + test.getValue() + "" );
LOGGER.info( "A    :=" + a.getValue() );

extract column value based on another column pandas dataframe

You could use loc to get series which satisfying your condition and then iloc to get first element:

In [2]: df
Out[2]:
    A  B
0  p1  1
1  p1  2
2  p3  3
3  p2  4

In [3]: df.loc[df['B'] == 3, 'A']
Out[3]:
2    p3
Name: A, dtype: object

In [4]: df.loc[df['B'] == 3, 'A'].iloc[0]
Out[4]: 'p3'

Entity Framework - Code First - Can't Store List<String>

This answer is based on the ones provided by @Sasan and @CAD bloke.

If you wish to use this in .NET Standard 2 or don't want Newtonsoft, see Xaniff's answer below

Works only with EF Core 2.1+ (not .NET Standard compatible)(Newtonsoft JsonConvert)

builder.Entity<YourEntity>().Property(p => p.Strings)
    .HasConversion(
        v => JsonConvert.SerializeObject(v),
        v => JsonConvert.DeserializeObject<List<string>>(v));

Using the EF Core fluent configuration we serialize/deserialize the List to/from JSON.

Why this code is the perfect mix of everything you could strive for:

  • The problem with Sasn's original answer is that it will turn into a big mess if the strings in the list contains commas (or any character chosen as the delimiter) because it will turn a single entry into multiple entries but it is the easiest to read and most concise.
  • The problem with CAD bloke's answer is that it is ugly and requires the model to be altered which is a bad design practice (see Marcell Toth's comment on Sasan's answer). But it is the only answer that is data-safe.

Check if application is installed - Android

Try this:

public static boolean isAvailable(Context ctx, Intent intent) {
    final PackageManager mgr = ctx.getPackageManager();
    List<ResolveInfo> list =
        mgr.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
    return list.size() > 0;
}

How do I apply a style to all children of an element

Instead of the * selector you can use the :not(selector) with the > selector and set something that definitely wont be a child.

Edit: I thought it would be faster but it turns out I was wrong. Disregard.

Example:

.container > :not(marquee){
        color:red;
    }


<div class="container">
    <p></p>
    <span></span>
<div>

How can I get a list of all values in select box?

As per the DOM structure you can use below code:

var x = document.getElementById('mySelect');
     var txt = "";
     var val = "";
     for (var i = 0; i < x.length; i++) {
         txt +=x[i].text + ",";
         val +=x[i].value + ",";
      }

How can I run a directive after the dom has finished rendering?

I had the a similar problem and want to share my solution here.

I have the following HTML:

<div data-my-directive>
  <div id='sub' ng-include='includedFile.htm'></div>
</div>

Problem: In the link-function of directive of the parent div I wanted to jquery'ing the child div#sub. But it just gave me an empty object because ng-include hadn't finished when link function of directive ran. So first I made a dirty workaround with $timeout, which worked but the delay-parameter depended on client speed (nobody likes that).

Works but dirty:

app.directive('myDirective', [function () {
    var directive = {};
    directive.link = function (scope, element, attrs) {
        $timeout(function() {
            //very dirty cause of client-depending varying delay time 
            $('#sub').css(/*whatever*/);
        }, 350);
    };
    return directive;
}]);

Here's the clean solution:

app.directive('myDirective', [function () {
    var directive = {};
    directive.link = function (scope, element, attrs) {
        scope.$on('$includeContentLoaded', function() {
            //just happens in the moment when ng-included finished
            $('#sub').css(/*whatever*/);
        };
    };
    return directive;
}]);

Maybe it helps somebody.

matplotlib: how to change data points color based on some variable

If you want to plot lines instead of points, see this example, modified here to plot good/bad points representing a function as a black/red as appropriate:

def plot(xx, yy, good):
    """Plot data

    Good parts are plotted as black, bad parts as red.

    Parameters
    ----------
    xx, yy : 1D arrays
        Data to plot.
    good : `numpy.ndarray`, boolean
        Boolean array indicating if point is good.
    """
    import numpy as np
    import matplotlib.pyplot as plt
    fig, ax = plt.subplots()
    from matplotlib.colors import from_levels_and_colors
    from matplotlib.collections import LineCollection
    cmap, norm = from_levels_and_colors([0.0, 0.5, 1.5], ['red', 'black'])
    points = np.array([xx, yy]).T.reshape(-1, 1, 2)
    segments = np.concatenate([points[:-1], points[1:]], axis=1)
    lines = LineCollection(segments, cmap=cmap, norm=norm)
    lines.set_array(good.astype(int))
    ax.add_collection(lines)
    plt.show()

How do you declare an object array in Java?

It's the other way round:

Vehicle[] car = new Vehicle[N];

This makes more sense, as the number of elements in the array isn't part of the type of car, but it is part of the initialization of the array whose reference you're initially assigning to car. You can then reassign it in another statement:

car = new Vehicle[10]; // Creates a new array

(Note that I've changed the type name to match Java naming conventions.)

For further information about arrays, see section 10 of the Java Language Specification.

linux execute command remotely

I guess ssh is the best secured way for this, for example :

ssh -OPTIONS -p SSH_PORT user@remote_server "remote_command1; remote_command2; remote_script.sh"  

where the OPTIONS have to be deployed according to your specific needs (for example, binding to ipv4 only) and your remote command could be starting your tomcat daemon.

Note:
If you do not want to be prompt at every ssh run, please also have a look to ssh-agent, and optionally to keychain if your system allows it. Key is... to understand the ssh keys exchange process. Please take a careful look to ssh_config (i.e. the ssh client config file) and sshd_config (i.e. the ssh server config file). Configuration filenames depend on your system, anyway you'll find them somewhere like /etc/sshd_config. Ideally, pls do not run ssh as root obviously but as a specific user on both sides, servers and client.

Some extra docs over the source project main pages :

ssh and ssh-agent
man ssh

http://www.snailbook.com/index.html
https://help.ubuntu.com/community/SSH/OpenSSH/Configuring

keychain
http://www.gentoo.org/doc/en/keychain-guide.xml
an older tuto in French (by myself :-) but might be useful too :
http://hornetbzz.developpez.com/tutoriels/debian/ssh/keychain/

How to convert C# nullable int to int

It will assign value of v1 to v2 if it is not null, else it will take a default value as zero.

v2=v1??0

Or below is the other way to write it.

v2 = v1.HasValue?v1:0

Executing <script> elements inserted with .innerHTML

The OP's script doesn't work in IE 7. With help from SO, here's a script that does:

exec_body_scripts: function(body_el) {
  // Finds and executes scripts in a newly added element's body.
  // Needed since innerHTML does not run scripts.
  //
  // Argument body_el is an element in the dom.

  function nodeName(elem, name) {
    return elem.nodeName && elem.nodeName.toUpperCase() ===
              name.toUpperCase();
  };

  function evalScript(elem) {
    var data = (elem.text || elem.textContent || elem.innerHTML || "" ),
        head = document.getElementsByTagName("head")[0] ||
                  document.documentElement,
        script = document.createElement("script");

    script.type = "text/javascript";
    try {
      // doesn't work on ie...
      script.appendChild(document.createTextNode(data));      
    } catch(e) {
      // IE has funky script nodes
      script.text = data;
    }

    head.insertBefore(script, head.firstChild);
    head.removeChild(script);
  };

  // main section of function
  var scripts = [],
      script,
      children_nodes = body_el.childNodes,
      child,
      i;

  for (i = 0; children_nodes[i]; i++) {
    child = children_nodes[i];
    if (nodeName(child, "script" ) &&
      (!child.type || child.type.toLowerCase() === "text/javascript")) {
          scripts.push(child);
      }
  }

  for (i = 0; scripts[i]; i++) {
    script = scripts[i];
    if (script.parentNode) {script.parentNode.removeChild(script);}
    evalScript(scripts[i]);
  }
};

Comparing two joda DateTime instances

This code (example) :

    Chronology ch1 = GregorianChronology.getInstance();     Chronology ch2 = ISOChronology.getInstance();      DateTime dt = new DateTime("2013-12-31T22:59:21+01:00",ch1);     DateTime dt2 = new DateTime("2013-12-31T22:59:21+01:00",ch2);      System.out.println(dt);     System.out.println(dt2);      boolean b = dt.equals(dt2);      System.out.println(b); 

Will print :

2013-12-31T16:59:21.000-05:00 2013-12-31T16:59:21.000-05:00 false 

You are probably comparing two DateTimes with same date but different Chronology.

How to say no to all "do you want to overwrite" prompts in a batch file copy?

I use XCOPY with the following parameters for copying .NET assemblies:

/D /Y /R /H 

/D:m-d-y - Copies files changed on or after the specified date. If no date is given, copies only those files whose source time is newer than the destination time.

/Y - Suppresses prompting to confirm you want to overwrite an existing destination file.

/R - Overwrites read-only files.

/H - Copies hidden and system files also.

View stored procedure/function definition in MySQL

SHOW CREATE PROCEDURE <name>

Returns the text of a previously defined stored procedure that was created using the CREATE PROCEDURE statement. Swap PROCEDURE for FUNCTION for a stored function.

Eclipse interface icons very small on high resolution screen in Windows 8.1

Thank you Sigh David Levy. I could not develop on Eclipse w/out your sol'n. I had to add a coupla catch (exceptions) to your code to get it to work:

            while (srcEntries.hasMoreElements()) {
                    ZipEntry entry = (ZipEntry) srcEntries.nextElement();
                    logger.info("Processing zip entry ["+ entry.getName() + "]");

                    ZipEntry newEntry = new ZipEntry(entry.getName());


                    try { outStream.putNextEntry(newEntry); } 
                    ***catch (Exception e) { 
                        logger.error("error: ", e);
                        outStream.closeEntry();
                        continue;*
                    }**

Oracle: Import CSV file

I would like to share 2 tips: (tip 1) create a csv file (tip 2) Load rows from a csv file into a table.

====[ (tip 1) SQLPLUS to create a csv file form an Oracle table ]====

I use SQLPLUS with the following commands:

set markup csv on
set lines 1000
set pagesize 100000 linesize 1000
set feedback off 
set trimspool on
spool /MyFolderAndFilename.csv
Select *  from MYschema.MYTABLE  where MyWhereConditions ;
spool off
exit

====[tip 2 SQLLDR to load a csv file into a table ]====

I use SQLLDR and a csv ( comma separated ) file to add (APPEND) rows form the csv file to a table. the file has , between fields text fields have " before and after the text CRITICAL: if last column is null there is a , at the end of the line

Example of data lines in the csv file:

11,"aa",1001
22,"bb',2002
33,"cc",
44,"dd",4004
55,"ee',

This is the control file:

LOAD DATA
APPEND 
INTO TABLE MYSCHEMA.MYTABLE
fields terminated by ',' optionally enclosed by '"'
TRAILING NULLCOLS
(
CoulmnName1,
CoulmnName2,
CoulmnName3
)

This is the command to execute sqlldr in Linux. If you run in Windows use \ instead of / c:

sqlldr userid=MyOracleUser/MyOraclePassword@MyOracleServerIPaddress:port/MyOracleSIDorService  DATA=datafile.csv  CONTROL=controlfile.ctl  LOG=logfile.log  BAD=notloadedrows.bad

Good luck !

Mobile Redirect using htaccess

I tested bits and pieces of the following, but not the complete rule set in its entirety, so if you run into trouble with it let me know and I'll dig around a bit more. However, assuming I got everything correct, you could try something like the following:

RewriteEngine On

# Check if this is the noredirect query string
RewriteCond %{QUERY_STRING} (^|&)noredirect=true(&|$)
# Set a cookie, and skip the next rule
RewriteRule ^ - [CO=mredir:0:%{HTTP_HOST},S]

# Check if this looks like a mobile device
# (You could add another [OR] to the second one and add in what you
#  had to check, but I believe most mobile devices should send at
#  least one of these headers)
RewriteCond %{HTTP:x-wap-profile} !^$ [OR]
RewriteCond %{HTTP:Profile}       !^$
# Check if we're not already on the mobile site
RewriteCond %{HTTP_HOST}          !^m\.
# Check to make sure we haven't set the cookie before
RewriteCond %{HTTP:Cookie}        !\smredir=0(;|$)
# Now redirect to the mobile site
RewriteRule ^ http://m.example.org%{REQUEST_URI} [R,L]

Add views below toolbar in CoordinatorLayout

Take the attribute

app:layout_behavior="@string/appbar_scrolling_view_behavior"

off the RecyclerView and put it on the FrameLayout that you are trying to show under the Toolbar.

I've found that one important thing the scrolling view behavior does is to layout the component below the toolbar. Because the FrameLayout has a descendant that will scroll (RecyclerView), the CoordinatorLayout will get those scrolling events for moving the Toolbar.


One other thing to be aware of: That layout behavior will cause the FrameLayout height to be sized as if the Toolbar is already scrolled, and with the Toolbar fully displayed the entire view is simply pushed down so that the bottom of the view is below the bottom of the CoordinatorLayout.

This was a surprise to me. I was expecting the view to be dynamically resized as the toolbar is scrolled up and down. So if you have a scrolling component with a fixed component at the bottom of your view, you won't see that bottom component until you have fully scrolled the Toolbar.

So when I wanted to anchor a button at the bottom of the UI, I worked around this by putting the button at the bottom of the CoordinatorLayout (android:layout_gravity="bottom") and adding a bottom margin equal to the button's height to the view beneath the toolbar.

Convert integer to hex and hex to integer

SQL Server equivalents to Excel's string-based DEC2HEX, HEX2DEC functions:

--Convert INT to hex string:
PRINT CONVERT(VARCHAR(8),CONVERT(VARBINARY(4), 16777215),2) --DEC2HEX

--Convert hex string to INT:
PRINT CONVERT(INT,CONVERT(VARBINARY(4),'00FFFFFF',2)) --HEX2DEC

Check if a input box is empty

If your textbox is a Required field and have some regex pattern to match and has minlength and maxlength

TestBox code

<input type="text" name="myfieldname" ng-pattern="/^[ A-Za-z0-9_@./#&+-]*$/" ng-minlength="3" ng-maxlength="50" class="classname" ng-model="model.myfieldmodel">

Ng-Class to Add

ng-class="{ 'err' :  myform.myfieldname.$invalid || (myform.myfieldname.$touched && !model.myfieldmodel.length) }"

Class file has wrong version 52.0, should be 50.0

i faced the same problem "Class file has wrong version 52.0, should be 50.0" when running java through ant... all i did was add fork="true" wherever i used the javac task and it worked...

if statement in ng-click

This maybe irrelevant and of no use, but as it's javascript, you don't have to use the ternary as suggested above in the ng-click statement. You should also be able to use the lazy evaluation ("or die") syntax as well. So for your example above:

<input  ng-click="{{if(profileForm.$valid) updateMyProfile()}}" name="submit" id="submit" value="Save" class="submit" type="submit">

would become:

<input  ng-click="profileForm.$valid && updateMyProfile()" name="submit" id="submit" value="Save" class="submit" type="submit">

In this case, if the profile is not valid then nothing happens, otherwise, updateMyProfile() is called. Like in the link @falinsky provides above.

Create a string of variable length, filled with a repeated character

Based on answers from Hogan and Zero Trick Pony. I think this should be both fast and flexible enough to handle well most use cases:

var hash = '####################################################################'

function build_string(length) {  
    if (length == 0) {  
        return ''  
    } else if (hash.length <= length) {  
        return hash.substring(0, length)  
    } else {  
        var result = hash  
        const half_length = length / 2  
        while (result.length <= half_length) {  
            result += result  
        }  
        return result + result.substring(0, length - result.length)  
    }  
}  

Vertically align text to top within a UILabel

(As of March 7, 2018)

Swift 4

let maxFrameHeight = 75

myLabel = UILabel()
myLabel.frame = CGRect(x: 9, y: 9, width: 126, height: maxFrameHeight)
myLabel.text = "my labels text displayed"
myLabel.numberOfLines = 0

myLabel.sizeToFit()
let newFrameHeight = myLabel.frame.size.height
let safeNewHeight = min(newFrameHeight, maxFrameHeight)

myLabel.frame = CGRect(x: 9, y: 9, width: 126, height: safeNewHeight)

This will get the desired outcome, and it will make sure the new height of the UILabel doesn't pass a certain maximum height you desire for this label.

Round up double to 2 decimal places

String(format: "%.2f", Double(round(1000*34.578)/1000))

Output: 34.58

Sending the bearer token with axios

You can create config once and use it everywhere.

const instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'Authorization': 'Bearer '+token}
});

instance.get('/path')
.then(response => {
    return response.data;
})

Html encode in PHP

Try this:

<?php
    $str = "This is some <b>bold</b> text.";
    echo htmlspecialchars($str);
?>

Copy file(s) from one project to another using post build event...VS2010

Like the previous replies, I'm also suggesting xcopy. However, I would like to add to Hallgeir Engen's answer with the /exclude parameter. There seems to be a bug with the parameter preventing it from working with path names that are long or that contain spaces, as quotes will not work. The path names need to be in the "DOS"-format with "Documents" translating to "DOCUME~1" (according to this source).

So, if you want to use the \exclude parameter, there is a workaround here:

cd $(SolutionDir)
xcopy "source-relative-to-path-above" "destination-relative-to-path-above
/exclude:exclude-file-relative-path

Note that the source and destination paths can (and should, if they contain spaces) be within quotes, but not the path to the exclude file.

How to delete files recursively from an S3 bucket

The voted up answer is missing a step.

Per aws s3 help:

Currently, there is no support for the use of UNIX style wildcards in a command's path arguments. However, most commands have --exclude "<value>" and --include "<value>" parameters that can achieve the desired result......... When there are multiple filters, the rule is the filters that appear later in the command take precedence over filters that appear earlier in the command. For example, if the filter parameters passed to the command were --exclude "*" --include "*.txt" All files will be excluded from the command except for files ending with .txt

aws s3 rm --recursive s3://bucket/ --exclude="*" --include="/folder_path/*" 

The builds tools for v120 (Platform Toolset = 'v120') cannot be found

When a VS2013 C++ project is opened in VS2015, and there are warnings about "The build tools for v120... cannot be found", I simply need to edit the .vcxproj file and change <PlatformToolset>v120</PlatformToolset> to <PlatformToolset>v140</PlatformToolset>, and close and re-open the solution.

Check a collection size with JSTL

As suggested by @Joel and @Mark Chorley in earlier comments:

${empty companies}

This checks for null and empty lists/collections/arrays. It doesn't get you the length but it satisfies the example in the OP. If you can get away with it this is just cleaner than importing a tag library and its crusty syntax like gt.

Update UI from Thread in Android

You should do this with the help of AsyncTask (an intelligent backround thread) and ProgressDialog

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called begin, doInBackground, processProgress and end.

The 4 steps

When an asynchronous task is executed, the task goes through 4 steps:

onPreExecute(), invoked on the UI thread immediately after the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.

doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.

onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.

onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter. Threading rules

There are a few threading rules that must be followed for this class to work properly:

The task instance must be created on the UI thread. execute(Params...) must be invoked on the UI thread. Do not call onPreExecute(), onPostExecute(Result), doInBackground(Params...), onProgressUpdate(Progress...) manually. The task can be executed only once (an exception will be thrown if a second execution is attempted.)

Example code
What the adapter does in this example is not important, more important to understand that you need to use AsyncTask to display a dialog for the progress.

private class PrepareAdapter1 extends AsyncTask<Void,Void,ContactsListCursorAdapter > {
    ProgressDialog dialog;
    @Override
    protected void onPreExecute() {
        dialog = new ProgressDialog(viewContacts.this);
        dialog.setMessage(getString(R.string.please_wait_while_loading));
        dialog.setIndeterminate(true);
        dialog.setCancelable(false);
        dialog.show();
    }
    /* (non-Javadoc)
     * @see android.os.AsyncTask#doInBackground(Params[])
     */
    @Override
    protected ContactsListCursorAdapter doInBackground(Void... params) {
        cur1 = objItem.getContacts();
        startManagingCursor(cur1);

        adapter1 = new ContactsListCursorAdapter (viewContacts.this,
                R.layout.contact_for_listitem, cur1, new String[] {}, new int[] {});

        return adapter1;
    }

    protected void onPostExecute(ContactsListCursorAdapter result) {
        list.setAdapter(result);
        dialog.dismiss();
    }
}

Python: Find index of minimum item in list of floats

I would use:

val, idx = min((val, idx) for (idx, val) in enumerate(my_list))

Then val will be the minimum value and idx will be its index.

Angular 2: import external js file into component

Here is a simple way i did it in my project.

lets say you need to use clipboard.min.js and for the sake of the example lets say that inside clipboard.min.js there is a function that called test2().

in order to use test2() function you need:

  1. make a reference to the .js file inside you index.html.
  2. import clipboard.min.js to your component.
  3. declare a variable that will use you to call the function.

here are only the relevant parts from my project (see the comments):

index.html:

<!DOCTYPE html>
<html>
<head>
    <title>Angular QuickStart</title>
    <base href="/src/">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="styles.css">

    <!-- Polyfill(s) for older browsers -->
    <script src="/node_modules/core-js/client/shim.min.js"></script>


    <script src="/node_modules/zone.js/dist/zone.js"></script>
    <script src="/node_modules/systemjs/dist/system.src.js"></script>

    <script src="systemjs.config.js"></script>
    <script>
        System.import('main.js').catch(function (err) { console.error(err); });
    </script>

    <!-- ************ HERE IS THE REFERENCE TO clipboard.min.js -->
    <script src="app/txtzone/clipboard.min.js"></script>
</head>

<body>
    <my-app>Loading AppComponent content here ...</my-app>
</body>
</html>

app.component.ts:

import '../txtzone/clipboard.min.js';
declare var test2: any; // variable as the name of the function inside clipboard.min.js

@Component({
    selector: 'txt-zone',
    templateUrl: 'app/txtzone/Txtzone.component.html',
    styleUrls: ['app/txtzone/TxtZone.css'],
})



export class TxtZoneComponent implements AfterViewInit {

    // call test2
    callTest2()
    {   
        new test2(); // the javascript function will execute
    }

}

Replacing objects in array

If you don't care about the order of the array, then you may want to get the difference between arr1 and arr2 by id using differenceBy() and then simply use concat() to append all the updated objects.

var result = _(arr1).differenceBy(arr2, 'id').concat(arr2).value();

_x000D_
_x000D_
var arr1 = [{_x000D_
  id: '124',_x000D_
  name: 'qqq'_x000D_
}, {_x000D_
  id: '589',_x000D_
  name: 'www'_x000D_
}, {_x000D_
  id: '45',_x000D_
  name: 'eee'_x000D_
}, {_x000D_
  id: '567',_x000D_
  name: 'rrr'_x000D_
}]_x000D_
_x000D_
var arr2 = [{_x000D_
  id: '124',_x000D_
  name: 'ttt'_x000D_
}, {_x000D_
  id: '45',_x000D_
  name: 'yyy'_x000D_
}];_x000D_
_x000D_
var result = _(arr1).differenceBy(arr2, 'id').concat(arr2).value();_x000D_
_x000D_
console.log(result);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.js"></script>
_x000D_
_x000D_
_x000D_

Visual Studio 6 Windows Common Controls 6.0 (sp6) Windows 7, 64 bit

SIMPLE SOLUTION

  1. Create a new blank project and save it
  2. using NOTEPAD open the .VBP of the new project and copy the MSCOMCTL line
  3. using NOTEPAD open the .VBP file of your project
  4. replace the MSCOMCTL line and save it

DONE

good luck

'do...while' vs. 'while'

while loops check the condition before the loop, do...while loops check the condition after the loop. This is useful is you want to base the condition on side effects from the loop running or, like other posters said, if you want the loop to run at least once.

I understand where you're coming from, but the do-while is something that most use rarely, and I've never used myself. You're not doing it wrong.

You're not doing it wrong. That's like saying someone is doing it wrong because they've never used the byte primitive. It's just not that commonly used.

How do I download a file with Angular2 or greater

<a href="my_url" download="myfilename">Download file</a>

my_url should have the same origin, otherwise it will redirect to that location

What does the shrink-to-fit viewport meta attribute do?

It is Safari specific, at least at time of writing, being introduced in Safari 9.0. From the "What's new in Safari?" documentation for Safari 9.0:

Viewport Changes

Viewport meta tags using "width=device-width" cause the page to scale down to fit content that overflows the viewport bounds. You can override this behavior by adding "shrink-to-fit=no" to your meta tag as shown below. The added value will prevent the page from scaling to fit the viewport.

<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">

In short, adding this to the viewport meta tag restores pre-Safari 9.0 behaviour.

Example

Here's a worked visual example which shows the difference upon loading the page in the two configurations.

The red section is the width of the viewport and the blue section is positioned outside the initial viewport (eg left: 100vw). Note how in the first example the page is zoomed to fit when shrink-to-fit=no is omitted (thus showing the out-of-viewport content) and the blue content remains off screen in the latter example.

The code for this example can be found at https://codepen.io/davidjb/pen/ENGqpv.

Without shrink-to-fit specified

Without shrink-to-fit=no

With shrink-to-fit=no

With shrink-to-fit=no

Practical uses for the "internal" keyword in C#

Utility or helper classes/methods that you would like to access from many other classes within the same assembly, but that you want to ensure code in other assemblies can't access.

From MSDN (via archive.org):

A common use of internal access is in component-based development because it enables a group of components to cooperate in a private manner without being exposed to the rest of the application code. For example, a framework for building graphical user interfaces could provide Control and Form classes that cooperate using members with internal access. Since these members are internal, they are not exposed to code that is using the framework.

You can also use the internal modifier along with the InternalsVisibleTo assembly level attribute to create "friend" assemblies that are granted special access to the target assembly internal classes.

This can be useful for creation of unit testing assemblies that are then allowed to call internal members of the assembly to be tested. Of course no other assemblies are granted this level of access, so when you release your system, encapsulation is maintained.

Unfamiliar symbol in algorithm: what does ? mean?

The upside-down A symbol is the universal quantifier from predicate logic. (Also see the more complete discussion of the first-order predicate calculus.) As others noted, it means that the stated assertions holds "for all instances" of the given variable (here, s). You'll soon run into its sibling, the backwards capital E, which is the existential quantifier, meaning "there exists at least one" of the given variable conforming to the related assertion.

If you're interested in logic, you might enjoy the book Logic and Databases: The Roots of Relational Theory by C.J. Date. There are several chapters covering these quantifiers and their logical implications. You don't have to be working with databases to benefit from this book's coverage of logic.

Download file from web in Python 3

I hope I understood the question right, which is: how to download a file from a server when the URL is stored in a string type?

I download files and save it locally using the below code:

import requests

url = 'https://www.python.org/static/img/python-logo.png'
fileName = 'D:\Python\dwnldPythonLogo.png'
req = requests.get(url)
file = open(fileName, 'wb')
for chunk in req.iter_content(100000):
    file.write(chunk)
file.close()

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

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

Writing a dictionary to a csv file with one line for every 'key: value'

Can you just do:

for key in mydict.keys():
    f.write(str(key) + ":" + str(mydict[key]) + ",");

So that you can have

key_1: value_1, key_2: value_2

Enabling the OpenSSL in XAMPP

Yes, you must open php.ini and remove the semicolon to:

;extension=php_openssl.dll

If you don't have that line, check that you have the file (In my PC is on D:\xampp\php\ext) and add this to php.ini in the "Dynamic Extensions" section:

extension=php_openssl.dll

Things have changed for PHP > 7. This is what i had to do for PHP 7.2.

Step: 1: Uncomment extension=openssl

Step: 2: Uncomment extension_dir = "ext"

Step: 3: Restart xampp.

Done.

Explanation: ( From php.ini )

If you wish to have an extension loaded automatically, use the following syntax:

extension=modulename

Note : The syntax used in previous PHP versions (extension=<ext>.so and extension='php_<ext>.dll) is supported for legacy reasons and may be deprecated in a future PHP major version. So, when it is possible, please move to the new (extension=<ext>) syntax.

Special Note: Be sure to appropriately set the extension_dir directive.

remove all variables except functions

I wrote this to remove all objects apart from functions from the current environment (Programming language used is R with IDE R-Studio):

    remove_list=c()                             # create a vector

      for(i in 1:NROW(ls())){                   # repeat over all objects in environment
        if(class(get(ls()[i]))!="function"){    # if object is *not* a function
         remove_list=c(remove_list,ls()[i])     # ..add to vector remove_list
         }    
      }

    rm(list=remove_list)                        # remove all objects named in remove_list

Notes-

The argument "list" in rm(list=) must be a character vector.

The name of an object in position i of the current environment is returned from ls()[i] and the object itself from get(ls()[i]). Therefore the class of an object is returned from class(get(ls()[i]))

How to generate javadoc comments in Android Studio

ALT+SHIFT+G will create the auto generated comments for your method (place the cursor at starting position of your method).

Codeigniter : calling a method of one controller from other

very simple in first controllr call

 $this->load->model('MyController');
 $this->MyController->test();

place file MyController.php to /model patch

MyController.php should be contain

class MyController extends CI_Model {

    function __construct() {
        parent::__construct();
    }
    function test()
    {
        echo 'OK';
    }
}

Combine two columns of text in pandas dataframe

Although the @silvado answer is good if you change df.map(str) to df.astype(str) it will be faster:

import pandas as pd
df = pd.DataFrame({'Year': ['2014', '2015'], 'quarter': ['q1', 'q2']})

In [131]: %timeit df["Year"].map(str)
10000 loops, best of 3: 132 us per loop

In [132]: %timeit df["Year"].astype(str)
10000 loops, best of 3: 82.2 us per loop

How to calculate Average Waiting Time and average Turn-around time in SJF Scheduling?

The Gantt charts given by Hifzan and Raja are for FCFS algorithms.

With an SJF algorithm, processes can be interrupted. That is, every process doesn't necessarily execute straight through their given burst time.

P3|P2|P4|P3|P5|P1|P5

1|2|3|5|7|8|11|14

P3 arrives at 1ms, then is interrupted by P2 and P4 since they both have smaller burst times, and then P3 resumes. P5 starts executing next, then is interrupted by P1 since P1's burst time is smaller than P5's. You must note the arrival times and be careful. These problems can be trickier than how they appear at-first-glance.

EDIT: This applies only to Preemptive SJF algorithms. A plain SJF algorithm is non-preemptive, meaning it does not interrupt a process.

EC2 instance types's exact network performance?

Almost everything in EC2 is multi-tenant. What the network performance indicates is what priority you will have compared with other instances sharing the same infrastructure.

If you need a guaranteed level of bandwidth, then EC2 will likely not work well for you.

How do I get DOUBLE_MAX?

INT_MAX is just a definition in limits.h. You don't make it clear whether you need to store an integer or floating point value. If integer, and using a 64-bit compiler, use a LONG (LLONG for 32-bit).

How do I use Docker environment variable in ENTRYPOINT array?

I tried to resolve with the suggested answer and still ran into some issues...

This was a solution to my problem:

ARG APP_EXE="AppName.exe"
ENV _EXE=${APP_EXE}

# Build a shell script because the ENTRYPOINT command doesn't like using ENV
RUN echo "#!/bin/bash \n mono ${_EXE}" > ./entrypoint.sh
RUN chmod +x ./entrypoint.sh

# Run the generated shell script.
ENTRYPOINT ["./entrypoint.sh"]

Specifically targeting your problem:

RUN echo "#!/bin/bash \n ./greeting --message ${ADDRESSEE}" > ./entrypoint.sh
RUN chmod +x ./entrypoint.sh
ENTRYPOINT ["./entrypoint.sh"]

Pylint "unresolved import" error in Visual Studio Code

The solution from Shinebayar G worked, but this other one is a little bit more elegant:

Copied from Python unresolved import issue #3840:

Given the following example project structure:

  • workspaceRootFolder
    • .vscode
  • ... other folders
  • codeFolder

What I did to resolve this issue:

  1. Go into the workspace folder (here workspaceRootFolder) and create a .env file
  2. In this empty .env file, add the line PYTHONPATH=codeFolder (replace codeFolder with your folder name)
  3. Add "python.envFile": "${workspaceFolder}/.env" to the settings.json
  4. Restart Visual Studio Code

Docker: Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock

Change the access permission of the docker.sock file

chmod 777 /var/run/docker.sock

or u can use sudo in the start of the command.

chmod 777 will allow all actions for all users while chmod 666 will allow all users to read and write but cannot execute the file.

Trust Anchor not found for Android SSL Connection

In my case this was happening after update to Android 8.0. The self-signed certificate Android was set to trust was using signature algorithm SHA1withRSA. Switching to a new cert, using signature algorithm SHA256withRSA fixed the problem.

Page Redirect after X seconds wait using JavaScript

setTimeout('Redirect()', 1000);
function Redirect() 
{  
    window.location="https://stackoverflow.com"; 
} 

//document.write("You will be Redirect to a new page in 1000 -> 1 Seconds, 2000 -> 2 Seconds");

How to retrieve available RAM from Windows command line?

PS C:\Users\Rack> systeminfo | findstr "System Memory"
System Boot Time:          5/5/2016, 11:10:41 PM
System Manufacturer:       VMware, Inc.
System Model:              VMware Virtual Platform
System Type:               x64-based PC
System Directory:          C:\Windows\system32
System Locale:             en-us;English (United States)
Total Physical Memory:     40,959 MB
Available Physical Memory: 36,311 MB
Virtual Memory: Max Size:  45,054 MB
Virtual Memory: Available: 41,390 MB
Virtual Memory: In Use:    3,664 MB

Session TimeOut in web.xml

Usually the session will not expire when request processing is happening. I think there is an LB or something in between which reads the entire file and then invokes the web container.

This might be causing a delay which is leading to expiry of the session.

Can I use conditional statements with EJS templates (in JMVC)?

For others that stumble on this, you can also use ejs params/props in conditional statements:

recipes.js File:

app.get("/recipes", function(req, res) {
    res.render("recipes.ejs", {
        recipes: recipes
    });
});

recipes.ejs File:

<%if (recipes.length > 0) { %>
// Do something with more than 1 recipe
<% } %>

How to change MySQL data directory?

The above steps are foundation and basic. I followed them and still got error of "mysql failed to start".

For the new folder to store mysql data, you need to make sure that the folder has permissions and ownership mysql:mysql.

Beside this, it needs to check the permissions and ownership of parent directory of mysql if having, say, /data/mysql/. Here /data/ directory should be root:root. I fixed the error of "mysql failed to start" after changing ownership of parent directory of /mysql. The OS in my VM is RHEL 7.6.

Using pip behind a proxy with CNTLM

$ pip --proxy http://proxy-host:proxy-port install packagename

This is what worked for me on

ASP.NET MVC Yes/No Radio Buttons with Strongly Bound Model MVC

Adding label tags around the radio buttons using regular HTML will fix the 'labelfor' issue as well:

<label><%= Html.RadioButton("blah", !Model.blah) %> Yes</label>
<label><%= Html.RadioButton("blah", Model.blah) %> No</label>

Clicking on the text now selects the appropriate radio button.

Why should I use a pointer rather than the object itself?

In C++, objects allocated on the stack (using Object object; statement within a block) will only live within the scope they are declared in. When the block of code finishes execution, the object declared are destroyed. Whereas if you allocate memory on heap, using Object* obj = new Object(), they continue to live in heap until you call delete obj.

I would create an object on heap when I like to use the object not only in the block of code which declared/allocated it.

how to attach url link to an image?

Alternatively,

<style type="text/css">
#example {
    display: block;
    width: 30px;
    height: 10px;
    background: url(../images/example.png) no-repeat;
    text-indent: -9999px;
}
</style>

<a href="http://www.example.com" id="example">See an example!</a>

More wordy, but it may benefit SEO, and it will look like nice simple text with CSS disabled.

Prevent direct access to a php include file

An alternative (or complement) to Chuck's solution would be to deny access to files matching a specific pattern by putting something like this in your .htaccess file

<FilesMatch "\.(inc)$">
    Order deny,allow
    Deny from all
</FilesMatch>

Delete last char of string

Additional to sll's solution: It's better to trim the string in case there are some blank(s) at the end.

strgroupids = strgroupids.Remove(strgroupids.Trim().Length - 1);

how to console.log result of this ajax call?

$.ajax({
    type: 'POST',
    url: 'loginCheck',
    data: $(formLogin).serialize(),    
    success: function(result){
        console.log('my message' + result);
    }
});

Remove IE10's "clear field" X button on certain inputs?

I would apply this rule to all input fields of type text, so it doesn't need to be duplicated later:

input[type=text]::-ms-clear { display: none; }

One can even get less specific by using just:

::-ms-clear { display: none; }

I have used the later even before adding this answer, but thought that most people would prefer to be more specific than that. Both solutions work fine.

Create a remote branch on GitHub

Before creating a new branch always the best practice is to have the latest of repo in your local machine. Follow these steps for error free branch creation.

 1. $ git branch (check which branches exist and which one is currently active (prefixed with *). This helps you avoid creating duplicate/confusing branch name)
 2. $ git branch <new_branch> (creates new branch)
 3. $ git checkout new_branch
 4. $ git add . (After making changes in the current branch)
 5. $ git commit -m "type commit msg here"
 6. $ git checkout master (switch to master branch so that merging with new_branch can be done)
 7. $ git merge new_branch (starts merging)
 8. $ git push origin master (push to the remote server)

I referred this blog and I found it to be a cleaner approach.

angular-cli server - how to proxy API requests to another server?

EDIT: THIS NO LONGER WORKS IN CURRENT ANGULAR-CLI

See answer from @imal hasaranga perera for up-to-date solution


The server in angular-cli comes from the ember-cli project. To configure the server, create an .ember-cli file in the project root. Add your JSON config in there:

{
   "proxy": "https://api.example.com"
}

Restart the server and it will proxy all requests there.

For example, I'm making relative requests in my code to /v1/foo/123, which is being picked up at https://api.example.com/v1/foo/123.

You can also use a flag when you start the server: ng serve --proxy https://api.example.com

Current for angular-cli version: 1.0.0-beta.0

Can we open pdf file using UIWebView on iOS?

UIWebviews can also load the .pdf using loadData method, if you acquire it as NSData:

[self.webView loadData:self.pdfData 
              MIMEType:@"application/pdf" 
      textEncodingName:@"UTF-8" 
               baseURL:nil];

PHP String to Float

Use this function to cast a float value from any kind of text style:

function parseFloat($value) {
    return floatval(preg_replace('#^([-]*[0-9\.,\' ]+?)((\.|,){1}([0-9-]{1,3}))*$#e', "str_replace(array('.', ',', \"'\", ' '), '', '\\1') . '.\\4'", $value));
}

This solution is not dependant on any locale settings. Thus for user input users can type float values in any way they like. This is really helpful e.g. when you have a project wich is in english only but people all over the world are using it and might not have in mind that the project wants a dot instead of a comma for float values. You could throw javascript in the mix and fetch the browsers default settings but still many people set these values to english but still typing 1,25 instead of 1.25 (especially but not limited to the translation industry, research and IT)

DataTable: How to get item value with row name and column name? (VB)

For i = 0 To dt.Rows.Count - 1

    ListV.Items.Add(dt.Rows(i).Item("STU_NUMBER").ToString)
    ListV.Items(i).SubItems.Add(dt.Rows(i).Item("FNAME").ToString & " " & dt.Rows(i).Item("MI").ToString & ". " & dt.Rows(i).Item("LNAME").ToString)
    ListV.Items(i).SubItems.Add(dt.Rows(i).Item("SEX").ToString)

Next

When to use StringBuilder in Java

Some compilers may not replace any string concatenations with StringBuilder equivalents. Be sure to consider which compilers your source will use before relying on compile time optimizations.

Add new attribute (element) to JSON object using JavaScript

extend: function(){
    if(arguments.length === 0){ return; }
    var x = arguments.length === 1 ? this : arguments[0];
    var y;

    for(var i = 1, len = arguments.length; i < len; i++) {
        y = arguments[i];
        for(var key in y){
            if(!(y[key] instanceof Function)){
                x[key] = y[key];
            }
        }           
    };

    return x;
}

Extends multiple json objects (ignores functions):

extend({obj: 'hej'}, {obj2: 'helo'}, {obj3: {objinside: 'yes'}});

Will result in a single json object

conditional Updating a list using LINQ

Try this:

li.ForEach(x => x.age = (x.name == "di") ?
                10 : (x.name == "marks") ?
                20 : (x.name == "grade") ?
                30 : 0 );

All values are updated in one line of code and you browse the List only ONE time. You have also a way to set a default value.

Gradient borders

Try the below example:

.border-gradient {
      border-width: 5px 5px 5px 5px;
      border-image: linear-gradient(45deg, rgba(100,57,242,1) 0%, rgba(242,55,55,1) 100%);
      border-image-slice: 9;
      border-style: solid;
}

How to convert an iterator to a stream?

One way is to create a Spliterator from the Iterator and use that as a basis for your stream:

Iterator<String> sourceIterator = Arrays.asList("A", "B", "C").iterator();
Stream<String> targetStream = StreamSupport.stream(
          Spliterators.spliteratorUnknownSize(sourceIterator, Spliterator.ORDERED),
          false);

An alternative which is maybe more readable is to use an Iterable - and creating an Iterable from an Iterator is very easy with lambdas because Iterable is a functional interface:

Iterator<String> sourceIterator = Arrays.asList("A", "B", "C").iterator();

Iterable<String> iterable = () -> sourceIterator;
Stream<String> targetStream = StreamSupport.stream(iterable.spliterator(), false);

HTML5 Dynamically create Canvas

It happens because you call it before DOM has loaded. Firstly, create the element and add atrributes to it, then after DOM has loaded call it. In your case it should look like that:

var canvas = document.createElement('canvas');
canvas.id     = "CursorLayer";
canvas.width  = 1224;
canvas.height = 768;
canvas.style.zIndex   = 8;
canvas.style.position = "absolute";
canvas.style.border   = "1px solid";
window.onload = function() {
    document.getElementById("CursorLayer");
}

Kubernetes how to make Deployment to update image

You can configure your pod with a grace period (for example 30 seconds or more, depending on container startup time and image size) and set "imagePullPolicy: "Always". And use kubectl delete pod pod_name. A new container will be created and the latest image automatically downloaded, then the old container terminated.

Example:

spec:
  terminationGracePeriodSeconds: 30
  containers:
  - name: my_container
    image: my_image:latest
    imagePullPolicy: "Always"

I'm currently using Jenkins for automated builds and image tagging and it looks something like this:

kubectl --user="kube-user" --server="https://kubemaster.example.com"  --token=$ACCESS_TOKEN set image deployment/my-deployment mycontainer=myimage:"$BUILD_NUMBER-$SHORT_GIT_COMMIT"

Another trick is to intially run:

kubectl set image deployment/my-deployment mycontainer=myimage:latest

and then:

kubectl set image deployment/my-deployment mycontainer=myimage

It will actually be triggering the rolling-update but be sure you have also imagePullPolicy: "Always" set.

Update:

another trick I found, where you don't have to change the image name, is to change the value of a field that will trigger a rolling update, like terminationGracePeriodSeconds. You can do this using kubectl edit deployment your_deployment or kubectl apply -f your_deployment.yaml or using a patch like this:

kubectl patch deployment your_deployment -p \
  '{"spec":{"template":{"spec":{"terminationGracePeriodSeconds":31}}}}'

Just make sure you always change the number value.

Run Java Code Online

rextester runs java snippets

Also accessible as runjavaonline.com

How to stretch a fixed number of horizontal navigation items evenly and fully across a specified container

I tried all the above and found them wanting. This is the simplest most flexible solution I could figure out (thanks to all of the above for inspiration).

HTML

<div id="container">
<ul>
    <li>HOME</li>
    <li>ABOUT US</li>
    <li>SERVICES</li>
    <li>PREVIOUS PROJECTS</li>
    <li>TESTIMONIALS</li>
    <li>NEWS</li>
    <li>RESEARCH &amp; DEV</li>
    <li>CONTACT</li>
</ul>
</div>

CSS

div#container{
  width:900px;
  background-color:#eee;
    padding:20px;
}
ul {
    display:table;
    width: 100%;
    margin:0 0;
    -webkit-padding-start:0px; /* reset chrome default */
}
ul li {
    display:table-cell;
    height:30px;
    line-height:30px;
    font-size:12px;    
    padding:20px 10px;
    text-align: center;
    background-color:#999;
    border-right:2px solid #fff;
}
ul li:first-child {
    border-radius:10px 0 0 10px;
}
ul li:last-child {
    border-radius:0 10px 10px 0;
    border-right:0 none;
}

You can drop the first/last child-rounded ends, obviously, but I think they're real purdy (and so does your client ;)

The container width limits the horizontal list, but you can ditch this and just apply an absolute value to the UL if you like.

Fiddle with it, if you like..

http://jsfiddle.net/tobyworth/esehY/1/

Convert Mercurial project to Git

Ok I finally worked this out. This is using TortoiseHg on Windows. If you're not using that you can do it on the command line.

  1. Install TortoiseHg
  2. Right click an empty space in explorer, and go to the TortoiseHg settings:

TortoiseHg Settings

  1. Enable hggit:

enter image description here

  1. Open a command line, enter an empty directory.

  2. git init --bare .git (If you don't use a bare repo you'll get an error like abort: git remote error: refs/heads/master failed to update

  3. cd to your Mercurial repository.

  4. hg bookmarks hg

  5. hg push c:/path/to/your/git/repo

  6. In the Git directory: git config --bool core.bare false (Don't ask me why. Something about "work trees". Git is seriously unfriendly. I swear writing the actual code is easier than using Git.)

Hopefully it will work and then you can push from that new git repo to a non-bare one.

git stash changes apply to new branch?

If you have some changes on your workspace and you want to stash them into a new branch use this command:

git stash branch branchName

It will make:

  1. a new branch
  2. move changes to this branch
  3. and remove latest stash (Like: git stash pop)

Adding an img element to a div with javascript

document.getElementById("placehere").appendChild(elem);

not

document.getElementById("placehere").appendChild("elem");

and use the below to set the source

elem.src = 'images/hydrangeas.jpg';

Laravel 5 Clear Views Cache

Right now there is no view:clear command. For laravel 4 this can probably help you: https://gist.github.com/cjonstrup/8228165

Disabling caching can be done by skipping blade. View caching is done because blade compiling each time is a waste of time.

How can I check if the array of objects have duplicate property values?

In TS and ES6 you can create a new Set with the property to be unique and compare it's size to the original array.

_x000D_
_x000D_
const values = [_x000D_
  { name: 'someName1' },_x000D_
  { name: 'someName2' },_x000D_
  { name: 'someName3' },_x000D_
  { name: 'someName1' }_x000D_
]_x000D_
_x000D_
const uniqueValues = new Set(values.map(v => v.name));_x000D_
_x000D_
if (uniqueValues.size < values.length) {_x000D_
  console.log('duplicates found')_x000D_
}
_x000D_
_x000D_
_x000D_

How to convert text to binary code in JavaScript?

This might be the simplest you can get:

function text2Binary(string) {
    return string.split('').map(function (char) {
        return char.charCodeAt(0).toString(2);
    }).join(' ');
}

fail to change placeholder color with Bootstrap 3

A Possible Gotcha

Recommended Sanity Check - Make sure to add the form-control class to your inputs.

If you have bootstrap css loaded on your page, but your inputs don't have the
class="form-control" then placeholder CSS selector won't apply to them.

Example markup from the docs:

I know this didn't apply to the OP's markup but as I missed this at first and spent a little bit of effort trying to debug it, I'm posting this answer to help others.

CSS3 transition on click using pure CSS

Method #1: CSS :focus pseudo-class

As pure CSS solution, you could achieve sort of the effect by using a tabindex attribute for the image, and :focus pseudo-class as follows:

<img class="crossRotate" src="http://placehold.it/100" tabindex="1" />
.crossRotate {
    outline: 0;
    /* other styles... */
}

.crossRotate:focus {
  -webkit-transform: rotate(45deg);
  -ms-transform: rotate(45deg);
  transform: rotate(45deg);
}

WORKING DEMO.

Note: Using this approach, the image gets rotated onclick (focused), to negate the rotation, you'll need to click somewhere out of the image (blured).

Method #2: Hidden input & :checked pseudo-class

This is one of my favorite methods. In this approach, there's a hidden checkbox input and a <label> element which wraps the image.

Once you click on the image, the hidden input is checked because of using for attribute for the label.

Hence by using the :checked pseudo-class and adjacent sibling selector +, we could get the image to be rotated:

<input type="checkbox" id="hacky-input">

<label for="hacky-input">
  <img class="crossRotate" src="http://placehold.it/100">
</label>
#hacky-input {
  display: none; /* Hide the input */
}

#hacky-input:checked + label img.crossRotate {
  -webkit-transform: rotate(45deg);
  -ms-transform: rotate(45deg);
  transform: rotate(45deg);
}

WORKING DEMO #1.

WORKING DEMO #2 (Applying the rotate to the label gives a better experience).

Method #3: Toggling a class via JavaScript

If using JavaScript/jQuery is an option, you could toggle a .active class by .toggleClass() to trigger the rotation effect, as follows:

$('.crossRotate').on('click', function(){
    $(this).toggleClass('active');
});
.crossRotate.active {
    /* vendor-prefixes here... */
    transform: rotate(45deg);
}

WORKING DEMO.

How to line-break from css, without using <br />?

This works in Chrome:

p::after {
    content: "-";
    color: transparent;
    display: block;
}

How to find the serial port number on Mac OS X?

Found the port esp32 was connected to by -

ls /dev/*

You would get a long list and you can find the port you need

How to increase IDE memory limit in IntelliJ IDEA on Mac?

For IDEA 13 and OS X 10.9 Mavericks, the correct paths are:

Original: /Applications/IntelliJ IDEA 13.app/Contents/bin/idea.vmoptions

Copy to: ~/Library/Preferences/IntelliJIdea13/idea.vmoptions

Oracle Differences between NVL and Coalesce

COALESCE is more modern function that is a part of ANSI-92 standard.

NVL is Oracle specific, it was introduced in 80's before there were any standards.

In case of two values, they are synonyms.

However, they are implemented differently.

NVL always evaluates both arguments, while COALESCE usually stops evaluation whenever it finds the first non-NULL (there are some exceptions, such as sequence NEXTVAL):

SELECT  SUM(val)
FROM    (
        SELECT  NVL(1, LENGTH(RAWTOHEX(SYS_GUID()))) AS val
        FROM    dual
        CONNECT BY
                level <= 10000
        )

This runs for almost 0.5 seconds, since it generates SYS_GUID()'s, despite 1 being not a NULL.

SELECT  SUM(val)
FROM    (
        SELECT  COALESCE(1, LENGTH(RAWTOHEX(SYS_GUID()))) AS val
        FROM    dual
        CONNECT BY
                level <= 10000
        )

This understands that 1 is not a NULL and does not evaluate the second argument.

SYS_GUID's are not generated and the query is instant.

Ruby Arrays: select(), collect(), and map()

EDIT: I just realized you want to filter details, which is an array of hashes. In that case you could do

details.reject { |item| item[:qty].empty? }

The inner data structure itself is not an Array, but a Hash. You can also use select here, but the block is given the key and value in this case:

irb(main):001:0> h = {:sku=>"507772-B21", :desc=>"HP 1TB 3G SATA 7.2K RPM LFF (3 .", :qty=>"", :qty2=>"1", :price=>"5,204.34 P"}
irb(main):002:0> h.select { |key, value| !value.empty? }
=> {:sku=>"507772-B21", :desc=>"HP 1TB 3G SATA 7.2K RPM LFF (3 .", 
    :qty2=>"1", :price=>"5,204.34 P"}

Or using reject, which is the inverse of select (excludes all items for which the given condition holds):

h.reject { |key, value| value.empty? }

Note that this is Ruby 1.9. If you have to maintain compatibility with 1.8, you could do:

Hash[h.reject { |key, value| value.empty? }]

Django Reverse with arguments '()' and keyword arguments '{}' not found

The solution @miki725 is absolutely correct. Alternatively, if you would like to use the args attribute as opposed to kwargs, then you can simply modify your code as follows:

project_id = 4
reverse('edit_project', args=(project_id,))

An example of this can be found in the documentation. This essentially does the same thing, but the attributes are passed as arguments. Remember that any arguments that are passed need to be assigned a value before being reversed. Just use the correct namespace, which in this case is 'edit_project'.

SQL Server equivalent to Oracle's CREATE OR REPLACE VIEW

I typically use something like this:

if exists (select * from dbo.sysobjects
  where id = object_id(N'dbo.MyView') and
  OBJECTPROPERTY(id, N'IsView') = 1)
drop view dbo.MyView
go
create view dbo.MyView [...]

How to select a div element in the code-behind page?

id + runat="server" leads to accessible at the server

Getting file size in Python?

You may use os.stat() function, which is a wrapper of system call stat():

import os

def getSize(filename):
    st = os.stat(filename)
    return st.st_size

How to print formatted BigDecimal values?

Another way which could make sense for the given situation is

BigDecimal newBD = oldBD.setScale(2);

I just say this because in some cases when it comes to money going beyond 2 decimal places does not make sense. Taking this a step further, this could lead to

String displayString = oldBD.setScale(2).toPlainString();

but I merely wanted to highlight the setScale method (which can also take a second rounding mode argument to control how that last decimal place is handled. In some situations, Java forces you to specify this rounding method).

JavaFX Application Icon

If you got Invalid URL or resource not found put your icon.png in the "bin" folder in your workspace.

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)

C char* to int conversion

Use atoi() from <stdlib.h>

http://linux.die.net/man/3/atoi

Or, write your own atoi() function which will convert char* to int

int a2i(const char *s)
{
  int sign=1;
  if(*s == '-'){
    sign = -1;
    s++;
  }
  int num=0;
  while(*s){
    num=((*s)-'0')+num*10;
    s++;   
  }
  return num*sign;
}

Return array from function

Your BlockID function uses the undefined variable images, which will lead to an error. Also, you should not use an Array here - JavaScripts key-value-maps are plain objects:

function BlockID() {
    return {
        "s": "Images/Block_01.png",
        "g": "Images/Block_02.png",
        "C": "Images/Block_03.png",
        "d": "Images/Block_04.png"
    };
}

How to make php display \t \n as tab and new line instead of characters

"\t" not '\t', php doesnt escape in single quotes

Redis strings vs Redis hashes to represent JSON: efficiency?

Some additions to a given set of answers:

First of all if you going to use Redis hash efficiently you must know a keys count max number and values max size - otherwise if they break out hash-max-ziplist-value or hash-max-ziplist-entries Redis will convert it to practically usual key/value pairs under a hood. ( see hash-max-ziplist-value, hash-max-ziplist-entries ) And breaking under a hood from a hash options IS REALLY BAD, because each usual key/value pair inside Redis use +90 bytes per pair.

It means that if you start with option two and accidentally break out of max-hash-ziplist-value you will get +90 bytes per EACH ATTRIBUTE you have inside user model! ( actually not the +90 but +70 see console output below )

 # you need me-redis and awesome-print gems to run exact code
 redis = Redis.include(MeRedis).configure( hash_max_ziplist_value: 64, hash_max_ziplist_entries: 512 ).new 
  => #<Redis client v4.0.1 for redis://127.0.0.1:6379/0> 
 > redis.flushdb
  => "OK" 
 > ap redis.info(:memory)
    {
                "used_memory" => "529512",
          **"used_memory_human" => "517.10K"**,
            ....
    }
  => nil 
 # me_set( 't:i' ... ) same as hset( 't:i/512', i % 512 ... )    
 # txt is some english fictionary book around 56K length, 
 # so we just take some random 63-symbols string from it 
 > redis.pipelined{ 10000.times{ |i| redis.me_set( "t:#{i}", txt[rand(50000), 63] ) } }; :done
 => :done 
 > ap redis.info(:memory)
  {
               "used_memory" => "1251944",
         **"used_memory_human" => "1.19M"**, # ~ 72b per key/value
            .....
  }
  > redis.flushdb
  => "OK" 
  # setting **only one value** +1 byte per hash of 512 values equal to set them all +1 byte 
  > redis.pipelined{ 10000.times{ |i| redis.me_set( "t:#{i}", txt[rand(50000), i % 512 == 0 ? 65 : 63] ) } }; :done 
  > ap redis.info(:memory)
   {
               "used_memory" => "1876064",
         "used_memory_human" => "1.79M",   # ~ 134 bytes per pair  
          ....
   }
    redis.pipelined{ 10000.times{ |i| redis.set( "t:#{i}", txt[rand(50000), 65] ) } };
    ap redis.info(:memory)
    {
             "used_memory" => "2262312",
          "used_memory_human" => "2.16M", #~155 byte per pair i.e. +90 bytes    
           ....
    }

For TheHippo answer, comments on Option one are misleading:

hgetall/hmset/hmget to the rescue if you need all fields or multiple get/set operation.

For BMiner answer.

Third option is actually really fun, for dataset with max(id) < has-max-ziplist-value this solution has O(N) complexity, because, surprise, Reddis store small hashes as array-like container of length/key/value objects!

But many times hashes contain just a few fields. When hashes are small we can instead just encode them in an O(N) data structure, like a linear array with length-prefixed key value pairs. Since we do this only when N is small, the amortized time for HGET and HSET commands is still O(1): the hash will be converted into a real hash table as soon as the number of elements it contains will grow too much

But you should not worry, you'll break hash-max-ziplist-entries very fast and there you go you are now actually at solution number 1.

Second option will most likely go to the fourth solution under a hood because as question states:

Keep in mind that if I use a hash, the value length isn't predictable. They're not all short such as the bio example above.

And as you already said: the fourth solution is the most expensive +70 byte per each attribute for sure.

My suggestion how to optimize such dataset:

You've got two options:

  1. If you cannot guarantee max size of some user attributes than you go for first solution and if memory matter is crucial than compress user json before store in redis.

  2. If you can force max size of all attributes. Than you can set hash-max-ziplist-entries/value and use hashes either as one hash per user representation OR as hash memory optimization from this topic of a Redis guide: https://redis.io/topics/memory-optimization and store user as json string. Either way you may also compress long user attributes.

Python equivalent for HashMap

You need a dict:

my_dict = {'cheese': 'cake'}

Example code (from the docs):

>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True

You can read more about dictionaries here.

Output array to CSV in Ruby

I've got this down to just one line.

rows = [['a1', 'a2', 'a3'],['b1', 'b2', 'b3', 'b4'], ['c1', 'c2', 'c3'], ... ]
csv_str = rows.inject([]) { |csv, row|  csv << CSV.generate_line(row) }.join("")
#=> "a1,a2,a3\nb1,b2,b3\nc1,c2,c3\n" 

Do all of the above and save to a csv, in one line.

File.open("ss.csv", "w") {|f| f.write(rows.inject([]) { |csv, row|  csv << CSV.generate_line(row) }.join(""))}

NOTE:

To convert an active record database to csv would be something like this I think

CSV.open(fn, 'w') do |csv|
  csv << Model.column_names
  Model.where(query).each do |m|
    csv << m.attributes.values
  end
end

Hmm @tamouse, that gist is somewhat confusing to me without reading the csv source, but generically, assuming each hash in your array has the same number of k/v pairs & that the keys are always the same, in the same order (i.e. if your data is structured), this should do the deed:

rowid = 0
CSV.open(fn, 'w') do |csv|
  hsh_ary.each do |hsh|
    rowid += 1
    if rowid == 1
      csv << hsh.keys# adding header row (column labels)
    else
      csv << hsh.values
    end# of if/else inside hsh
  end# of hsh's (rows)
end# of csv open

If your data isn't structured this obviously won't work

what innerHTML is doing in javascript?

The innerHTML property is used to get or set the HTML content of an element node.

Example: http://jsfiddle.net/mQMVc/

     // get the element with the "someElement" id, and give it new content
document.getElementById('someElement').innerHTML = "<p>new content</p>";

     // retrieve the content from an element
var content = document.getElementById('someElement').innerHTML;

alert( content );