Programs & Examples On #Non greedy

A technique used in regular expressions, that limits the matching text until all conditions of the given regex have been met. The operator "?" is added to the end of wildcard operations.

How can I write a regex which matches non greedy?

The other answers here presuppose that you have a regex engine which supports non-greedy matching, which is an extension introduced in Perl 5 and widely copied to other modern languages; but it is by no means ubiquitous.

Many older or more conservative languages and editors only support traditional regular expressions, which have no mechanism for controlling greediness of the repetition operator * - it always matches the longest possible string.

The trick then is to limit what it's allowed to match in the first place. Instead of .* you seem to be looking for

[^>]*

which still matches as many of something as possible; but the something is not just . "any character", but instead "any character which isn't >".

Depending on your application, you may or may not want to enable an option to permit "any character" to include newlines.

Even if your regular expression engine supports non-greedy matching, it's better to spell out what you actually mean. If this is what you mean, you should probably say this, instead of rely on non-greedy matching to (hopefully, probably) Do What I Mean.

For example, a regular expression with a trailing context after the wildcard like .*?><br/> will jump over any nested > until it finds the trailing context (here, ><br/>) even if that requires straddling multiple > instances and newlines if you let it, where [^>]*><br/> (or even [^\n>]*><br/> if you have to explicitly disallow newline) obviously can't and won't do that.

Of course, this is still not what you want if you need to cope with <img title="quoted string with > in it" src="other attributes"> and perhaps <img title="nested tags">, but at that point, you should finally give up on using regular expressions for this like we all told you in the first place.

What do 'lazy' and 'greedy' mean in the context of regular expressions?

+-------------------+-----------------+------------------------------+
| Greedy quantifier | Lazy quantifier |        Description           |
+-------------------+-----------------+------------------------------+
| *                 | *?              | Star Quantifier: 0 or more   |
| +                 | +?              | Plus Quantifier: 1 or more   |
| ?                 | ??              | Optional Quantifier: 0 or 1  |
| {n}               | {n}?            | Quantifier: exactly n        |
| {n,}              | {n,}?           | Quantifier: n or more        |
| {n,m}             | {n,m}?          | Quantifier: between n and m  |
+-------------------+-----------------+------------------------------+

Add a ? to a quantifier to make it ungreedy i.e lazy.

Example:
test string : stackoverflow
greedy reg expression : s.*o output: stackoverflow
lazy reg expression : s.*?o output: stackoverflow

What is the difference between .*? and .* regular expressions?

Let's say you have:

<a></a>

<(.*)> would match a></a where as <(.*?)> would match a. The latter stops after the first match of >. It checks for one or 0 matches of .* followed by the next expression.

The first expression <(.*)> doesn't stop when matching the first >. It will continue until the last match of >.

How to make a Generic Type Cast function

Something like this?

public static T ConvertValue<T>(string value)
{
    return (T)Convert.ChangeType(value, typeof(T));
}

You can then use it like this:

int val = ConvertValue<int>("42");

Edit:

You can even do this more generic and not rely on a string parameter provided the type U implements IConvertible - this means you have to specify two type parameters though:

public static T ConvertValue<T,U>(U value) where U : IConvertible
{
    return (T)Convert.ChangeType(value, typeof(T));
}

I considered catching the InvalidCastException exception that might be raised by Convert.ChangeType() - but what would you return in this case? default(T)? It seems more appropriate having the caller deal with the exception.

Javascript to export html table to Excel

ShieldUI's export to excel functionality should already support all special chars.

How to check if a user is logged in (how to properly use user.is_authenticated)?

For Django 2.0+ versions use:

    if request.auth:
       # Only for authenticated users.

For more info visit https://www.django-rest-framework.org/api-guide/requests/#auth

request.user.is_authenticated() has been removed in Django 2.0+ versions.

Passing data to a bootstrap modal

For updating an href value, for example, I would do something like:

<a href="#myModal" data-toggle="modal" data-url="http://example.com">Show modal</a>

$('#myModal').on('show.bs.modal', function (e) {
    var url = $(e.relatedTarget).data('url');
    $(e.currentTarget).find('.any-class').attr("href", "url");
})

error: Your local changes to the following files would be overwritten by checkout

Your error appears when you have modified a file and the branch that you are switching to has changes for this file too (from latest merge point).

Your options, as I see it, are - commit, and then amend this commit with extra changes (you can modify commits in git, as long as they're not pushed); or - use stash:

git stash save your-file-name
git checkout master
# do whatever you had to do with master
git checkout staging
git stash pop

git stash save will create stash that contains your changes, but it isn't associated with any commit or even branch. git stash pop will apply latest stash entry to your current branch, restoring saved changes and removing it from stash.

How to make a HTTP request using Ruby on Rails?

My favorite two ways to grab the contents of URLs are either OpenURI or Typhoeus.

OpenURI because it's everywhere, and Typhoeus because it's very flexible and powerful.

Understanding dispatch_async

Swift version

This is the Swift version of David's Objective-C answer. You use the global queue to run things in the background and the main queue to update the UI.

DispatchQueue.global(qos: .background).async {
    
    // Background Thread
    
    DispatchQueue.main.async {
        // Run UI Updates
    }
}

How to determine if a string is a number with C++?

to check if a string is a number integer or floating point or so you could use :

 #include <sstream>

    bool isNumber(string str) {
    double d;
    istringstream is(str);
    is >> d;
    return !is.fail() && is.eof();
}

Why does dividing two int not yield the right value when assigned to double?

This is technically a language-dependent, but almost all languages treat this subject the same. When there is a type mismatch between two data types in an expression, most languages will try to cast the data on one side of the = to match the data on the other side according to a set of predefined rules.

When dividing two numbers of the same type (integers, doubles, etc.) the result will always be of the same type (so 'int/int' will always result in int).

In this case you have double var = integer result which casts the integer result to a double after the calculation in which case the fractional data is already lost. (most languages will do this casting to prevent type inaccuracies without raising an exception or error).

If you'd like to keep the result as a double you're going to want to create a situation where you have double var = double result

The easiest way to do that is to force the expression on the right side of an equation to cast to double:

c = a/(double)b

Division between an integer and a double will result in casting the integer to the double (note that when doing maths, the compiler will often "upcast" to the most specific data type this is to prevent data loss).

After the upcast, a will wind up as a double and now you have division between two doubles. This will create the desired division and assignment.

AGAIN, please note that this is language specific (and can even be compiler specific), however almost all languages (certainly all the ones I can think of off the top of my head) treat this example identically.

Visual Studio - How to change a project's folder name and solution name without breaking the solution

You could open the SLN file in any text editor (Notepad, etc.) and simply change the project path there.

How to share my Docker-Image without using the Docker-Hub?

[Update]

More recently, there is Amazon AWS ECR (Elastic Container Registry), which provides a Docker image registry to which you can control access by means of the AWS IAM access management service. ECR can also run a CVE (vulnerabilities) check on your image when you push it.

Once you create your ECR, and obtain the "URL" you can push and pull as required, subject to the permissions you create: hence making it private or public as you wish.

Pricing is by amount of data stored, and data transfer costs.

https://aws.amazon.com/ecr/

[Original answer]

If you do not want to use the Docker Hub itself, you can host your own Docker repository under Artifactory by JFrog:

https://www.jfrog.com/confluence/display/RTF/Docker+Repositories

which will then run on your own server(s).

Other hosting suppliers are available, eg CoreOS:

http://www.theregister.co.uk/2014/10/30/coreos_enterprise_registry/

which bought quay.io

Converting Decimal to Binary Java

Even better with StringBuilder using insert() in front of the decimal string under construction, without calling reverse(),

static String toBinary(int n) {
    if (n == 0) {
        return "0";
    }

    StringBuilder bldr = new StringBuilder();
    while (n > 0) {
        bldr = bldr.insert(0, n % 2);
        n = n / 2;
    }

    return bldr.toString();
}

Vue Js - Loop via v-for X times (in a range)

In 2.2.0+, when using v-for with a component, a key is now required.

<div v-for="item in items" :key="item.id">

Source

MySQL - Using If Then Else in MySQL UPDATE or SELECT Queries

UPDATE table
SET A = IF(A > 0 AND A < 1, 1, IF(A > 1 AND A < 2, 2, A))
WHERE A IS NOT NULL;

you might want to use CEIL() if A is always a floating point value > 0 and <= 2

Combine two (or more) PDF's

I know a lot of people have recommended PDF Sharp, however it doesn't look like that project has been updated since june of 2008. Further, source isn't available.

Personally, I've been playing with iTextSharp which has been pretty easy to work with.

Spring get current ApplicationContext

Step 1 :Inject following code in class

@Autowired
private ApplicationContext _applicationContext;

Step 2 : Write Getter & Setter

Step 3: define autowire="byType" in xml file in which bean is defined

SQL Server Pivot Table with multiple column aggregates

I used your own pivot as a nested query and came to this result:

SELECT
  [sub].[chardate],
  SUM(ISNULL([Australia], 0)) AS [Transactions Australia],
  SUM(CASE WHEN [Australia] IS NOT NULL THEN [TotalAmount] ELSE 0 END) AS [Amount Australia],
  SUM(ISNULL([Austria], 0)) AS [Transactions Austria],
  SUM(CASE WHEN [Austria] IS NOT NULL THEN [TotalAmount] ELSE 0 END) AS [Amount Austria]
FROM
(
  select * 
  from  mytransactions
  pivot (sum (totalcount) for country in ([Australia], [Austria])) as pvt
) AS [sub]
GROUP BY
  [sub].[chardate],
  [sub].[numericmonth]
ORDER BY 
  [sub].[numericmonth] ASC

Here is the Fiddle.

How to remove all options from a dropdown using jQuery / JavaScript

Try this

function removeElements(){
    $('#models').html("");
}

How can I get Apache gzip compression to work?

Try this :

####################
# GZIP COMPRESSION #
####################
SetOutputFilter DEFLATE
AddOutputFilterByType DEFLATE text/html text/css text/plain text/xml application/x-javascript application/x-httpd-php
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
BrowserMatch \bMSI[E] !no-gzip !gzip-only-text/html
SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-gzip

How to set header and options in axios?

This is a simple example of a configuration with headers and responseType:

var config = {
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  responseType: 'blob'
};

axios.post('http://YOUR_URL', this.data, config)
  .then((response) => {
  console.log(response.data);
});

Content-Type can be 'application/x-www-form-urlencoded' or 'application/json' and it may work also 'application/json;charset=utf-8'

responseType can be 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'

In this example, this.data is the data you want to send. It can be a value or an Array. (If you want to send an object you'll probably have to serialize it)

ReactJS map through Object

Do you get an error when you try to map through the object keys, or does it throw something else.

Also note when you want to map through the keys you make sure to refer to the object keys correctly. Just like this:

{ Object.keys(subjects).map((item, i) => (
   <li className="travelcompany-input" key={i}>
     <span className="input-label">key: {i} Name: {subjects[item]}</span>
    </li>
))}

You need to use {subjects[item]} instead of {subjects[i]} because it refers to the keys of the object. If you look for subjects[i] you will get undefined.

#1142 - SELECT command denied to user ''@'localhost' for table 'pma_table_uiprefs'

I had the same problem and it might look so easy but it solved my problem. I have tried all the solutions recommended here but there was no problem just a day ago. So I thought the problem might be about the Session data. I tried to stop and run apache and mysql services but it didn't work also. Then I realized there are buttons on phpMyAdmin just below its logo on the left side. The button next to "Home"; "Empty Session Data" solved all of my problems.

addID in jQuery?

do you mean a method?

$('div.foo').attr('id', 'foo123');

Just be careful that you don't set multiple elements to the same ID.

Where is the Docker daemon log?

For Mac with Docker Toolbox, ssh into the VM first with docker-machine ssh %VM-NAME% and then check /var/log/docker.log

Hibernate show real SQL

log4j.properties

log4j.logger.org.hibernate=INFO, hb
log4j.logger.org.hibernate.SQL=DEBUG
log4j.logger.org.hibernate.type=TRACE
log4j.logger.org.hibernate.hql.ast.AST=info
log4j.logger.org.hibernate.tool.hbm2ddl=warn
log4j.logger.org.hibernate.hql=debug
log4j.logger.org.hibernate.cache=info
log4j.logger.org.hibernate.jdbc=debug

log4j.appender.hb=org.apache.log4j.ConsoleAppender
log4j.appender.hb.layout=org.apache.log4j.PatternLayout
log4j.appender.hb.layout.ConversionPattern=HibernateLog --> %d{HH:mm:ss} %-5p %c - %m%n
log4j.appender.hb.Threshold=TRACE

hibernate.cfg.xml

<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="use_sql_comments">true</property>

persistence.xml

Some frameworks use persistence.xml:

<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hibernate.use_sql_comments" value="true"/>

How to access accelerometer/gyroscope data from Javascript?

Can't add a comment to the excellent explanation in the other post but wanted to mention that a great documentation source can be found here.

It is enough to register an event function for accelerometer like so:

if(window.DeviceMotionEvent){
  window.addEventListener("devicemotion", motion, false);
}else{
  console.log("DeviceMotionEvent is not supported");
}

with the handler:

function motion(event){
  console.log("Accelerometer: "
    + event.accelerationIncludingGravity.x + ", "
    + event.accelerationIncludingGravity.y + ", "
    + event.accelerationIncludingGravity.z
  );
}

And for magnetometer a following event handler has to be registered:

if(window.DeviceOrientationEvent){
  window.addEventListener("deviceorientation", orientation, false);
}else{
  console.log("DeviceOrientationEvent is not supported");
}

with a handler:

function orientation(event){
  console.log("Magnetometer: "
    + event.alpha + ", "
    + event.beta + ", "
    + event.gamma
  );
}

There are also fields specified in the motion event for a gyroscope but that does not seem to be universally supported (e.g. it didn't work on a Samsung Galaxy Note).

There is a simple working code on GitHub

HTTP 400 (bad request) for logical error, not malformed request syntax

Even though, I have been using 400 to represent logical errors also, I have to say that returning 400 is wrong in this case because of the way the spec reads. Here is why i think so, the logical error could be that a relationship with another entity was failing or not satisfied and making changes to the other entity could cause the same exact to pass later. Like trying to (completely hypothetical) add an employee as a member of a department when that employee does not exist (logical error). Adding employee as member request could fail because employee does not exist. But the same exact request could pass after the employee has been added to the system.

Just my 2 cents ... We need lawyers & judges to interpret the language in the RFC these days :)

Thank You, Vish

Remove all items from a FormArray in Angular

Since Angular 8 you can use this.formArray.clear() to clear all values in form array. It's a simpler and more efficient alternative to removing all elements one by one

Java: Array with loop

int[] nums = new int[100];

int sum = 0;

// Fill it with numbers using a for-loop for (int i = 0; i < nums.length; i++)

{ 
     nums[i] = i + 1;
    sum += n;
}

System.out.println(sum);

How to reset index in a pandas dataframe?

data1.reset_index(inplace=True)

How can I get the source code of a Python function?

If the function is from a source file available on the filesystem, then inspect.getsource(foo) might be of help:

If foo is defined as:

def foo(arg1,arg2):         
    #do something with args 
    a = arg1 + arg2         
    return a  

Then:

import inspect
lines = inspect.getsource(foo)
print(lines)

Returns:

def foo(arg1,arg2):         
    #do something with args 
    a = arg1 + arg2         
    return a                

But I believe that if the function is compiled from a string, stream or imported from a compiled file, then you cannot retrieve its source code.

PHP Multiple Checkbox Array

Try this, by for Loop

<form method="post">
<?php
for ($i=1; $i <5 ; $i++) 
{ 
    echo'<input type="checkbox" value="'.$i.'" name="checkbox[]"/>';
} 
?>
<input type="submit" name="submit" class="form-control" value="Submit">  
</form>

<?php 
if(isset($_POST['submit']))
{
    $check=implode(", ", $_POST['checkbox']);
    print_r($check);
}     
?>

Regex to match alphanumeric and spaces

I suspect ^ doesn't work the way you think it does outside of a character class.

What you're telling it to do is replace everything that isn't an alphanumeric with an empty string, OR any leading space. I think what you mean to say is that spaces are ok to not replace - try moving the \s into the [] class.

What command shows all of the topics and offsets of partitions in Kafka?

You might want to try kt. It's also quite faster than the bundled kafka-topics.

This is the current most complete info description you can get out of a topic with kt:

kt topic -brokers localhost:9092 -filter my_topic_name -partitions -leaders -replicas

It also outputs as JSON, so you can pipe it to jq for further flexibility.

What is a "bundle" in an Android application

bundle is used to share data between activities , and to save state of app in oncreate() method so that app will come to know where it was stopped ... I hope it helps :)

Best way to load module/class from lib folder in Rails 3?

As of Rails 5, it is recommended to put the lib folder under app directory or instead create other meaningful name spaces for the folder as services , presenters, features etc and put it under app directory for auto loading by rails.

Please check this GitHub Discussion Link as well.

Postgres FOR LOOP

Procedural elements like loops are not part of the SQL language and can only be used inside the body of a procedural language function, procedure (Postgres 11 or later) or a DO statement, where such additional elements are defined by the respective procedural language. The default is PL/pgSQL, but there are others.

Example with plpgsql:

DO
$do$
BEGIN 
   FOR i IN 1..25 LOOP
      INSERT INTO playtime.meta_random_sample
         (col_i, col_id)                       -- declare target columns!
      SELECT  i,     id
      FROM   tbl
      ORDER  BY random()
      LIMIT  15000;
   END LOOP;
END
$do$;

For many tasks that can be solved with a loop, there is a shorter and faster set-based solution around the corner. Pure SQL equivalent for your example:

INSERT INTO playtime.meta_random_sample (col_i, col_id)
SELECT t.*
FROM   generate_series(1,25) i
CROSS  JOIN LATERAL (
   SELECT i, id
   FROM   tbl
   ORDER  BY random()
   LIMIT  15000
   ) t;

About generate_series():

About optimizing performance of random selections:

Add an element to an array in Swift

To add to the end, use the += operator:

myArray += ["Craig"]
myArray += ["Jony", "Eddy"]

That operator is generally equivalent to the append(contentsOf:) method. (And in really old Swift versions, could append single elements, not just other collections of the same element type.)

There's also insert(_:at:) for inserting at any index.

If, say, you'd like a convenience function for inserting at the beginning, you could add it to the Array class with an extension.

Run jar file in command prompt

Try this

java -jar <jar-file-name>.jar

C# Base64 String to JPEG Image

Front :

  <Image Name="camImage"/>

Back:

 public async void Base64ToImage(string base64String)
        {
            // read stream
            var bytes = Convert.FromBase64String(base64String);
            var image = bytes.AsBuffer().AsStream().AsRandomAccessStream();

            // decode image
            var decoder = await BitmapDecoder.CreateAsync(image);
            image.Seek(0);

            // create bitmap
            var output = new WriteableBitmap((int)decoder.PixelHeight, (int)decoder.PixelWidth);
            await output.SetSourceAsync(image);

            camImage.Source = output;
        }

How to retrieve Jenkins build parameters using the Groovy API?

To get the parameterized build params from the current build from your GroovyScript (using Pipeline), all you need to do is: Say you had a variable called VARNAME.

def myVariable = env.VARNAME

Android how to convert int to String?

Use this String.valueOf(value);

How to create folder with PHP code?

You can create a directory with PHP using the mkdir() function.

mkdir("/path/to/my/dir", 0700);

You can use fopen() to create a file inside that directory with the use of the mode w.

fopen('myfile.txt', 'w');

w : Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.

Android: How to bind spinner to custom object list?

Here's the complete process in Kotlin:

the spinner adapter class:

class CustomSpinnerAdapter(
    context: Context,
    textViewResourceId: Int,
    val list: List<User>
) : ArrayAdapter<User>(
    context,
    textViewResourceId,
    list
) {
    override fun getCount() = list.size

    override fun getItem(position: Int) = list[position]

    override fun getItemId(position: Int) = list[position].report.toLong()

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        return (super.getDropDownView(position, convertView, parent) as TextView).apply {
            text = list[position].name
        }
    }

    override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View {
        return (super.getDropDownView(position, convertView, parent) as TextView).apply {
            text = list[position].name
        }
    }
}

and use it in your activity/fragment like this:

spinner.adapter = CustomerSalesSpinnerAdapter(
            context,
            R.layout.cuser_spinner_item,
            userList
        )

Error: Configuration with name 'default' not found in Android Studio

This is probably a rare case, but for me a library that was included in the settings.gradle was not there.

E.g. I had: include ':libraries:Android-RateThisApp:library' in my settings.gradle

but the folder Android-RateThisApp was empty. As soon as I checked out this submodule the gradle sync succeed.

How to find a value in an array and remove it by using PHP array functions?

Just in case you want to use any of mentioned codes, be aware that array_search returns FALSE when the "needle" is not found in "haystack" and therefore these samples would unset the first (zero-indexed) item. Use this instead:

<?php
$haystack = Array('one', 'two', 'three');
if (($key = array_search('four', $haystack)) !== FALSE) {
  unset($haystack[$key]);
}
var_dump($haystack);

The above example will output:

Array
(
    [0] => one
    [1] => two
    [2] => three
)

And that's good!

Remove part of a string

If you're a Tidyverse kind of person, here's the stringr solution:

R> library(stringr)
R> strings = c("TGAS_1121", "MGAS_1432", "ATGAS_1121") 
R> strings %>% str_replace(".*_", "_")
[1] "_1121" "_1432" "_1121"
# Or:
R> strings %>% str_replace("^[A-Z]*", "")
[1] "_1121" "_1432" "_1121"

How to save a bitmap on internal storage

Modify onClick() as follows:

@Override
public void onClick(View v) {
    if(v == btn) {
        canvas=sv.getHolder().lockCanvas();
        if(canvas!=null) {
            canvas.drawBitmap(bitmap, 100, 100, null);
            sv.getHolder().unlockCanvasAndPost(canvas);
        }
    } else if(v == btn1) {
        saveBitmapToInternalStorage(bitmap);
    }
}

There are several ways to enforce that btn must be pressed before btn1 so that the bitmap is painted before you attempt to save it.

I suggest that you initially disable btn1, and that you enable it when btn is clicked, like this:

if(v == btn) {
    ...
    btn1.setEnabled(true);
}

Functional style of Java 8's Optional.ifPresent and if-not-Present?

Java 9 introduces

ifPresentOrElse if a value is present, performs the given action with the value, otherwise performs the given empty-based action.

See excellent Optional in Java 8 cheat sheet.

It provides all answers for most use cases.

Short summary below

ifPresent() - do something when Optional is set

opt.ifPresent(x -> print(x)); 
opt.ifPresent(this::print);

filter() - reject (filter out) certain Optional values.

opt.filter(x -> x.contains("ab")).ifPresent(this::print);

map() - transform value if present

opt.map(String::trim).filter(t -> t.length() > 1).ifPresent(this::print);

orElse()/orElseGet() - turning empty Optional to default T

int len = opt.map(String::length).orElse(-1);
int len = opt.
    map(String::length).
    orElseGet(() -> slowDefault());     //orElseGet(this::slowDefault)

orElseThrow() - lazily throw exceptions on empty Optional

opt.
filter(s -> !s.isEmpty()).
map(s -> s.charAt(0)).
orElseThrow(IllegalArgumentException::new);

How do I deploy Node.js applications as a single executable file?

Not to beat a dead horse, but the solution you're describing sounds a lot like Node-Webkit.

From the Git Page:

node-webkit is an app runtime based on Chromium and node.js. You can write native apps in HTML and JavaScript with node-webkit. It also lets you call Node.js modules directly from the DOM and enables a new way of writing native applications with all Web technologies.

These instructions specifically detail the creation of a single file app that a user can execute, and this portion describes the external dependencies.

I'm not sure if it's the exact solution, but it seems pretty close.

Hope it helps!

Checking if a number is an Integer in Java

Quick and dirty...

if (x == (int)x)
{
   ...
}

edit: This is assuming x is already in some other numeric form. If you're dealing with strings, look into Integer.parseInt.

List only stopped Docker containers

The typical command is:

docker container ls -f 'status=exited'

However, this will only list one of the possible non-running statuses. Here's a list of all possible statuses:

  • created
  • restarting
  • running
  • removing
  • paused
  • exited
  • dead

You can filter on multiple statuses by passing multiple filters on the status:

docker container ls -f 'status=exited' -f 'status=dead' -f 'status=created'

If you are integrating this with an automatic cleanup script, you can chain one command to another with some bash syntax, output just the container id's with -q, and you can also limit to just the containers that exited successfully with an exit code filter:

docker container rm $(docker container ls -q -f 'status=exited' -f 'exited=0')

For more details on filters you can use, see Docker's documentation: https://docs.docker.com/engine/reference/commandline/ps/#filtering

Install IPA with iTunes 12

Edit: See Jayprakash Dubey's answer for iTunes 12.7


From the menu shown in the following screenshot, choose Apps. You can drag and drop you IPA file in the next view.

enter image description here

After that, go to your device's page, you'll see the list of apps, install your app and press Apply from the bottom bar.

How do I create a custom Error in JavaScript?

This is implemented nicely in the Cesium DeveloperError:

In it's simplified form:

var NotImplementedError = function(message) {
    this.name = 'NotImplementedError';
    this.message = message;
    this.stack = (new Error()).stack;
}

// Later on...

throw new NotImplementedError();

Is String.Contains() faster than String.IndexOf()?

From a little reading, it appears that under the hood the String.Contains method simply calls String.IndexOf. The difference is String.Contains returns a boolean while String.IndexOf returns an integer with (-1) representing that the substring was not found.

I would suggest writing a little test with 100,000 or so iterations and see for yourself. If I were to guess, I'd say that IndexOf may be slightly faster but like I said it just a guess.

Jeff Atwood has a good article on strings at his blog. It's more about concatenation but may be helpful nonetheless.

Why is sed not recognizing \t as a tab?

TAB=$(printf '\t')
sed "s/${TAB}//g" input_file

It works for me on Red Hat, which will remove tabs from the input file.

how to rotate text left 90 degree and cell size is adjusted according to text in html

Daniel Imms answer is excellent in regards to applying your CSS rotation to an inner element. However, it is possible to accomplish the end goal in a way that does not require JavaScript and works with longer strings of text.

Typically the whole reason to have vertical text in the first table column is to fit a long line of text in a short horizontal space and to go alongside tall rows of content (as in your example) or multiple rows of content (which I'll use in this example).

enter image description here

By using the ".rotate" class on the parent TD tag, we can not only rotate the inner DIV, but we can also set a few CSS properties on the parent TD tag that will force all of the text to stay on one line and keep the width to 1.5em. Then we can use some negative margins on the inner DIV to make sure that it centers nicely.

_x000D_
_x000D_
td {_x000D_
    border: 1px black solid;_x000D_
    padding: 5px;_x000D_
}_x000D_
.rotate {_x000D_
  text-align: center;_x000D_
  white-space: nowrap;_x000D_
  vertical-align: middle;_x000D_
  width: 1.5em;_x000D_
}_x000D_
.rotate div {_x000D_
     -moz-transform: rotate(-90.0deg);  /* FF3.5+ */_x000D_
       -o-transform: rotate(-90.0deg);  /* Opera 10.5 */_x000D_
  -webkit-transform: rotate(-90.0deg);  /* Saf3.1+, Chrome */_x000D_
             filter:  progid:DXImageTransform.Microsoft.BasicImage(rotation=0.083);  /* IE6,IE7 */_x000D_
         -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=0.083)"; /* IE8 */_x000D_
         margin-left: -10em;_x000D_
         margin-right: -10em;_x000D_
}
_x000D_
<table cellpadding="0" cellspacing="0" align="center">_x000D_
    <tr>_x000D_
        <td class='rotate' rowspan="4"><div>10 kilograms</div></td>_x000D_
        <td>B</td>_x000D_
        <td>C</td>_x000D_
        <td>D</td>_x000D_
        <td>E</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>G</td>_x000D_
        <td>H</td>_x000D_
        <td>I</td>_x000D_
        <td>J</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>L</td>_x000D_
        <td>M</td>_x000D_
        <td>N</td>_x000D_
        <td>O</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>Q</td>_x000D_
        <td>R</td>_x000D_
        <td>S</td>_x000D_
        <td>T</td>_x000D_
    </tr>_x000D_
    _x000D_
    <tr>_x000D_
        <td class='rotate' rowspan="4"><div>20 kilograms</div></td>_x000D_
        <td>B</td>_x000D_
        <td>C</td>_x000D_
        <td>D</td>_x000D_
        <td>E</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>G</td>_x000D_
        <td>H</td>_x000D_
        <td>I</td>_x000D_
        <td>J</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>L</td>_x000D_
        <td>M</td>_x000D_
        <td>N</td>_x000D_
        <td>O</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>Q</td>_x000D_
        <td>R</td>_x000D_
        <td>S</td>_x000D_
        <td>T</td>_x000D_
    </tr>_x000D_
    _x000D_
    <tr>_x000D_
        <td class='rotate' rowspan="4"><div>30 kilograms</div></td>_x000D_
        <td>B</td>_x000D_
        <td>C</td>_x000D_
        <td>D</td>_x000D_
        <td>E</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>G</td>_x000D_
        <td>H</td>_x000D_
        <td>I</td>_x000D_
        <td>J</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>L</td>_x000D_
        <td>M</td>_x000D_
        <td>N</td>_x000D_
        <td>O</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>Q</td>_x000D_
        <td>R</td>_x000D_
        <td>S</td>_x000D_
        <td>T</td>_x000D_
    </tr>_x000D_
    _x000D_
</table>
_x000D_
_x000D_
_x000D_

One thing to keep in mind with this solution is that it does not work well if the height of the row (or spanned rows) is shorter than the vertical text in the first column. It works best if you're spanning multiple rows or you have a lot of content creating tall rows.

Have fun playing around with this on jsFiddle.

You need to use a Theme.AppCompat theme (or descendant) with this activity

In my case, I was using a style called "FullScreenTheme", and although it seemed to be correctly defined (it was a descendant of Theme.AppCompat) it was not working.

I finally realized that I was using an AAR library that internally also had defined a style called "FullScreenTheme" and it was not descendant of Theme.AppCompat. The clashing of the names was causing the problem.

Fix it by renaming my own style name so now Android is using the correct style.

Disable keyboard on EditText

try: android:editable="false" or android:inputType="none"

Django: Get list of model fields?

MyModel._meta.get_all_field_names() was deprecated several versions back and removed in Django 1.10.

Here's the backwards-compatible suggestion from the docs:

from itertools import chain

list(set(chain.from_iterable(
    (field.name, field.attname) if hasattr(field, 'attname') else (field.name,)
    for field in MyModel._meta.get_fields()
    # For complete backwards compatibility, you may want to exclude
    # GenericForeignKey from the results.
    if not (field.many_to_one and field.related_model is None)
)))

Make the current commit the only (initial) commit in a Git repository?

The only solution that works for me (and keeps submodules working) is

git checkout --orphan newBranch
git add -A  # Add all files and commit them
git commit
git branch -D master  # Deletes the master branch
git branch -m master  # Rename the current branch to master
git push -f origin master  # Force push master branch to github
git gc --aggressive --prune=all     # remove the old files

Deleting .git/ always causes huge issues when I have submodules. Using git rebase --root would somehow cause conflicts for me (and take long since I had a lot of history).

facebook: permanent Page Access Token?

Here's my solution using only Graph API Explorer & Access Token Debugger:

  1. Graph API Explorer:
    • Select your App from the top right dropdown menu
    • Select "Get User Access Token" from dropdown (right of access token field) and select needed permissions
    • Copy user access token
  2. Access Token Debugger:
    • Paste copied token and press "Debug"
    • Press "Extend Access Token" and copy the generated long-lived user access token
  3. Graph API Explorer:
    • Paste copied token into the "Access Token" field
    • Make a GET request with "PAGE_ID?fields=access_token"
    • Find the permanent page access token in the response (node "access_token")
  4. (Optional) Access Token Debugger:
    • Paste the permanent token and press "Debug"
    • "Expires" should be "Never"

(Tested with API Version 2.9-2.11, 3.0-3.1)

How should I pass an int into stringWithFormat?

You want to use %d or %i for integers. %@ is used for objects.

It's worth noting, though, that the following code will accomplish the same task and is much clearer.

label.intValue = count;

jQuery.active function

This is a variable jQuery uses internally, but had no reason to hide, so it's there to use. Just a heads up, it becomes jquery.ajax.active next release. There's no documentation because it's exposed but not in the official API, lots of things are like this actually, like jQuery.cache (where all of jQuery.data() goes).

I'm guessing here by actual usage in the library, it seems to be there exclusively to support $.ajaxStart() and $.ajaxStop() (which I'll explain further), but they only care if it's 0 or not when a request starts or stops. But, since there's no reason to hide it, it's exposed to you can see the actual number of simultaneous AJAX requests currently going on.


When jQuery starts an AJAX request, this happens:

if ( s.global && ! jQuery.active++ ) {
  jQuery.event.trigger( "ajaxStart" );
}

This is what causes the $.ajaxStart() event to fire, the number of connections just went from 0 to 1 (jQuery.active++ isn't 0 after this one, and !0 == true), this means the first of the current simultaneous requests started. The same thing happens at the other end. When an AJAX request stops (because of a beforeSend abort via return false or an ajax call complete function runs):

if ( s.global && ! --jQuery.active ) {
  jQuery.event.trigger( "ajaxStop" );
}

This is what causes the $.ajaxStop() event to fire, the number of requests went down to 0, meaning the last simultaneous AJAX call finished. The other global AJAX handlers fire in there along the way as well.

Change header text of columns in a GridView

protected void grdDis_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            #region Dynamically Show gridView header From data base
            getAllheaderName();/*To get all Allowences master headerName*/

            TextBox txt_Days = (TextBox)grdDis.HeaderRow.FindControl("txtDays");
            txt_Days.Text = hidMonthsDays.Value;
            #endregion
        }
    }

Intro to GPU programming

  1. You get programmable vertex and pixel shaders that allow execution of code directly on the GPU to manipulate the buffers that are to be drawn. These languages (i.e. OpenGL's GL Shader Lang and High Level Shader Lang and DirectX's equivalents ), are C style syntax, and really easy to use. Some examples of HLSL can be found here for XNA game studio and Direct X. I don't have any decent GLSL references, but I'm sure there are a lot around. These shader languages give an immense amount of power to manipulate what gets drawn at a per-vertex or per-pixel level, directly on the graphics card, making things like shadows, lighting, and bloom really easy to implement.
  2. The second thing that comes to mind is using openCL to code for the new lines of general purpose GPU's. I'm not sure how to use this, but my understanding is that openCL gives you the beginnings of being able to access processors on both the graphics card and normal cpu. This is not mainstream technology yet, and seems to be driven by Apple.
  3. CUDA seems to be a hot topic. CUDA is nVidia's way of accessing the GPU power. Here are some intros

What does LPCWSTR stand for and how should it be handled with?

It's a long pointer to a constant, wide string (i.e. a string of wide characters).

Since it's a wide string, you want to make your constant look like: L"TestWindow". I wouldn't create the intermediate a either, I'd just pass L"TestWindow" for the parameter:

ghTest = FindWindowEx(NULL, NULL, NULL, L"TestWindow");

If you want to be pedantically correct, an "LPCTSTR" is a "text" string -- a wide string in a Unicode build and a narrow string in an ANSI build, so you should use the appropriate macro:

ghTest = FindWindow(NULL, NULL, NULL, _T("TestWindow"));

Few people care about producing code that can compile for both Unicode and ANSI character sets though, and if you don't getting it to really work correctly can be quite a bit of extra work for little gain. In this particular case, there's not much extra work, but if you're manipulating strings, there's a whole set of string manipulation macros that resolve to the correct functions.

Rails: Adding an index after adding column

Add in the generated migration after creating the column the following (example)

add_index :photographers, :email, :unique => true

How to check if the request is an AJAX request with PHP

There is no sure-fire way of knowing that a request was made via Ajax. You can never trust data coming from the client. You could use a couple of different methods but they can be easily overcome by spoofing.

How does one check if a table exists in an Android SQLite database?

 // @param db, readable database from SQLiteOpenHelper

 public boolean doesTableExist(SQLiteDatabase db, String tableName) {
        Cursor cursor = db.rawQuery("select DISTINCT tbl_name from sqlite_master where tbl_name = '" + tableName + "'", null);

    if (cursor != null) {
        if (cursor.getCount() > 0) {
            cursor.close();
            return true;
        }
        cursor.close();
    }
    return false;
}
  • sqlite maintains sqlite_master table containing information of all tables and indexes in database.
  • So here we are simply running SELECT command on it, we'll get cursor having count 1 if table exists.

Java : Cannot format given Object as a Date

java.time

I should like to contribute the modern answer. The SimpleDateFormat class is notoriously troublesome, and while it was reasonable to fight one’s way through with it when this question was asked six and a half years ago, today we have much better in java.time, the modern Java date and time API. SimpleDateFormat and its friend Date are now considered long outdated, so don’t use them anymore.

    DateTimeFormatter monthFormatter = DateTimeFormatter.ofPattern("MM/uuuu");
    String dateformat = "2012-11-17T00:00:00.000-05:00";
    OffsetDateTime dateTime = OffsetDateTime.parse(dateformat);
    String monthYear = dateTime.format(monthFormatter);
    System.out.println(monthYear);

Output:

11/2012

I am exploiting the fact that your string is in ISO 8601 format, the international standard, and that the classes of java.time parse this format as their default, that is, without any explicit formatter. It’s stil true what the other answers say, you need to parse the original string first, then format the resulting date-time object into a new string. Usually this requires two formatters, only in this case we’re lucky and can do with just one formatter.

What went wrong in your code

  • As others have said, SimpleDateFormat.format cannot accept a String argument, also when the parameter type is declared to be Object.
  • Because of the exception you didn’t get around to discovering: there is also a bug in your format pattern string, mm/yyyy. Lowercase mm os for minute of the hour. You need uppercase MM for month.
  • Finally the Java naming conventions say to use a lowercase first letter in variable names, so use lowercase m in monthYear (also because java.time includes a MonthYear class with uppercase M, so to avoid confusion).

Links

Default session timeout for Apache Tomcat applications

Open $CATALINA_BASE/conf/web.xml and find this

<!-- ==================== Default Session Configuration ================= -->
<!-- You can set the default session timeout (in minutes) for all newly   -->
<!-- created sessions by modifying the value below.                       -->

<session-config>
  <session-timeout>30</session-timeout>
</session-config>

all webapps implicitly inherit from this default web descriptor. You can override session-config as well as other settings defined there in your web.xml.

This is actually from my Tomcat 7 (Windows) but I think 5.5 conf is not very different

Have nginx access_log and error_log log to STDOUT and STDERR of master process

For a debug purpose:

/usr/sbin/nginx -g "daemon off;error_log /dev/stdout debug;"

For a classic purpose

/usr/sbin/nginx -g "daemon off;error_log /dev/stdout info;"

Require

Under the server bracket on the config file

access_log /dev/stdout;

PHPExcel auto size column width

for ($i = 'A'; $i !=  $objPHPExcel->getActiveSheet()->getHighestColumn(); $i++) {
    $objPHPExcel->getActiveSheet()->getColumnDimension($i)->setAutoSize(TRUE);
}

Tensorflow 2.0 - AttributeError: module 'tensorflow' has no attribute 'Session'

Tensorflow 2.x support's Eager Execution by default hence Session is not supported.

MySql: Tinyint (2) vs tinyint(1) - what is the difference?

About the INT, TINYINT... These are different data types, INT is 4-byte number, TINYINT is 1-byte number. More information here - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT.

The syntax of TINYINT data type is TINYINT(M), where M indicates the maximum display width (used only if your MySQL client supports it).

Numeric Type Attributes.

Check whether a string contains a substring

To find out if a string contains substring you can use the index function:

if (index($str, $substr) != -1) {
    print "$str contains $substr\n";
} 

It will return the position of the first occurrence of $substr in $str, or -1 if the substring is not found.

Http Basic Authentication in Java using HttpClient?

This is the code from the accepted answer above, with some changes made regarding the Base64 encoding. The code below compiles.

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.commons.codec.binary.Base64;


public class HttpBasicAuth {

    public static void main(String[] args) {

        try {
            URL url = new URL ("http://ip:port/login");

            Base64 b = new Base64();
            String encoding = b.encodeAsString(new String("test1:test1").getBytes());

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setRequestProperty  ("Authorization", "Basic " + encoding);
            InputStream content = (InputStream)connection.getInputStream();
            BufferedReader in   = 
                new BufferedReader (new InputStreamReader (content));
            String line;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
        } 
        catch(Exception e) {
            e.printStackTrace();
        }
    }
}

entity object cannot be referenced by multiple instances of IEntityChangeTracker. while adding related objects to entity in Entity Framework 4.1

I had the same problem but my issue with the @Slauma's solution (although great in certain instances) is that it recommends that I pass the context into the service which implies that the context is available from my controller. It also forces tight coupling between my controller and service layers.

I'm using Dependency Injection to inject the service/repository layers into the controller and as such do not have access to the context from the controller.

My solution was to have the service/repository layers use the same instance of the context - Singleton.

Context Singleton Class:

Reference: http://msdn.microsoft.com/en-us/library/ff650316.aspx
and http://csharpindepth.com/Articles/General/Singleton.aspx

public sealed class MyModelDbContextSingleton
{
  private static readonly MyModelDbContext instance = new MyModelDbContext();

  static MyModelDbContextSingleton() { }

  private MyModelDbContextSingleton() { }

  public static MyModelDbContext Instance
  {
    get
    {
      return instance;
    }
  }
}  

Repository Class:

public class ProjectRepository : IProjectRepository
{
  MyModelDbContext context = MyModelDbContextSingleton.Instance;
  [...]

Other solutions do exist such as instantiating the context once and passing it into the constructors of your service/repository layers or another I read about which is implementing the Unit of Work pattern. I'm sure there are more...

How to generate the "create table" sql statement for an existing table in postgreSQL

Even more modification based on response from @vkkeeper. Added possibility to query table from the specific schema.

CREATE OR REPLACE FUNCTION public.describe_table(p_schema_name character varying, p_table_name character varying)
  RETURNS SETOF text AS
$BODY$
DECLARE
    v_table_ddl   text;
    column_record record;
    table_rec record;
    constraint_rec record;
    firstrec boolean;
BEGIN
    FOR table_rec IN
        SELECT c.relname, c.oid FROM pg_catalog.pg_class c
            LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
                WHERE relkind = 'r'
                AND n.nspname = p_schema_name
                AND relname~ ('^('||p_table_name||')$')
          ORDER BY c.relname
    LOOP
        FOR column_record IN
            SELECT
                b.nspname as schema_name,
                b.relname as table_name,
                a.attname as column_name,
                pg_catalog.format_type(a.atttypid, a.atttypmod) as column_type,
                CASE WHEN
                    (SELECT substring(pg_catalog.pg_get_expr(d.adbin, d.adrelid) for 128)
                     FROM pg_catalog.pg_attrdef d
                     WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef) IS NOT NULL THEN
                    'DEFAULT '|| (SELECT substring(pg_catalog.pg_get_expr(d.adbin, d.adrelid) for 128)
                                  FROM pg_catalog.pg_attrdef d
                                  WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef)
                ELSE
                    ''
                END as column_default_value,
                CASE WHEN a.attnotnull = true THEN
                    'NOT NULL'
                ELSE
                    'NULL'
                END as column_not_null,
                a.attnum as attnum,
                e.max_attnum as max_attnum
            FROM
                pg_catalog.pg_attribute a
                INNER JOIN
                 (SELECT c.oid,
                    n.nspname,
                    c.relname
                  FROM pg_catalog.pg_class c
                       LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
                  WHERE c.oid = table_rec.oid
                  ORDER BY 2, 3) b
                ON a.attrelid = b.oid
                INNER JOIN
                 (SELECT
                      a.attrelid,
                      max(a.attnum) as max_attnum
                  FROM pg_catalog.pg_attribute a
                  WHERE a.attnum > 0
                    AND NOT a.attisdropped
                  GROUP BY a.attrelid) e
                ON a.attrelid=e.attrelid
            WHERE a.attnum > 0
              AND NOT a.attisdropped
            ORDER BY a.attnum
        LOOP
            IF column_record.attnum = 1 THEN
                v_table_ddl:='CREATE TABLE '||column_record.schema_name||'.'||column_record.table_name||' (';
            ELSE
                v_table_ddl:=v_table_ddl||',';
            END IF;

            IF column_record.attnum <= column_record.max_attnum THEN
                v_table_ddl:=v_table_ddl||chr(10)||
                         '    '||column_record.column_name||' '||column_record.column_type||' '||column_record.column_default_value||' '||column_record.column_not_null;
            END IF;
        END LOOP;

        firstrec := TRUE;
        FOR constraint_rec IN
            SELECT conname, pg_get_constraintdef(c.oid) as constrainddef
                FROM pg_constraint c
                    WHERE conrelid=(
                        SELECT attrelid FROM pg_attribute
                        WHERE attrelid = (
                            SELECT oid FROM pg_class WHERE relname = table_rec.relname
                                AND relnamespace = (SELECT ns.oid FROM pg_namespace ns WHERE ns.nspname = p_schema_name)
                        ) AND attname='tableoid'
                    )
        LOOP
            v_table_ddl:=v_table_ddl||','||chr(10);
            v_table_ddl:=v_table_ddl||'CONSTRAINT '||constraint_rec.conname;
            v_table_ddl:=v_table_ddl||chr(10)||'    '||constraint_rec.constrainddef;
            firstrec := FALSE;
        END LOOP;
        v_table_ddl:=v_table_ddl||');';
        RETURN NEXT v_table_ddl;
    END LOOP;
END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;

open cv error: (-215) scn == 3 || scn == 4 in function cvtColor

In my case the error got resolved by migrating to OpenCV 4.0 (or higher).

How to upload files to server using Putty (ssh)

Use WinSCP for file transfer over SSH, putty is only for SSH commands.

Destroy or remove a view in Backbone.js

I had to be absolutely sure the view was not just removed from DOM but also completely unbound from events.

destroy_view: function() {

    // COMPLETELY UNBIND THE VIEW
    this.undelegateEvents();

    this.$el.removeData().unbind(); 

    // Remove view from DOM
    this.remove();  
    Backbone.View.prototype.remove.call(this);

}

Seemed like overkill to me, but other approaches did not completely do the trick.

What is the meaning of "$" sign in JavaScript

Your snippet of code looks like it's referencing methods from one of the popular JavaScript libraries (jQuery, ProtoType, mooTools, and so on).

There's nothing mysterious about the use of $ in JavaScript. $ is simply a valid JavaScript identifier.

JavaScript allows upper and lower letters, numbers, and $ and _. The $ was intended to be used for machine-generated variables (such as $0001).

Prototype, jQuery, and most javascript libraries use the $ as the primary base object (or function). Most of them also have a way to relinquish the $ so that it can be used with another library that uses it. In that case you use jQuery instead of $. In fact, $ is just a shortcut for jQuery.

Reading file line by line (with space) in Unix Shell scripting - Issue

Try this,

IFS=''
while read line
do
    echo $line
done < file.txt

EDIT:

From man bash

IFS - The Internal Field Separator that is used for word
splitting after expansion and to split lines into words
with  the  read  builtin  command. The default value is
``<space><tab><newline>''

Laravel Blade html image

In Laravel 5.x you can use laravelcollective/html and the syntax:

{!! Html::image('img/logo.png') !!}

Is there a command to list all Unix group names?

To list all local groups which have users assigned to them, use this command:

cut -d: -f1 /etc/group | sort

For more info- > Unix groups, Cut command, sort command

How do I edit a file after I shell to a Docker container?

An easy way to edit a few lines would be:

echo "deb http://deb.debian.org/debian stretch main" > sources.list

"Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6

Adding the why this occurs and more possible cause. A lot of interfaces still do not understand ES6 Javascript syntax/features, hence there is need for Es6 to be compiled to ES5 whenever it is used in any file or project. The possible reasons for the SyntaxError: Cannot use import statement outside a module error is you are trying to run the file independently, you are yet to install and set up an Es6 compiler such as Babel or the path of the file in your runscript is wrong/not the compiled file. If you will want to continue without a compiler the best possible solution is to use ES5 syntax which in your case would be var ms = require(./ms.js); this can later be updated as appropriate or better still setup your compiler and ensure your file/project is compiled before running and also ensure your run script is running the compiled file usually named dist, build or whatever you named it and the path to the compiled file in your runscript is correct.

How do I install command line MySQL client on mac?

Open the "MySQL Workbench" DMG file and

# Adjust the path to the version of MySQL Workbench you downloaded
cp "/Volumes/MySQL Workbench 6.3.9.CE/MySQLWorkbench.app/Contents/MacOS/mysql" /usr/local/bin
# Make sure it's executable
chmod +x /usr/local/bin/mysql

Eject the DMG disk

Can I get a patch-compatible output from git-diff?

The git diffs have an extra path segment prepended to the file paths. You can strip the this entry in the path by specifying -p1 with patch, like so:

patch -p1 < save.patch

Learning Ruby on Rails

My steps was:

* Agile development with Rails (book)
* Railscasts - very useful, always learn something new.
* And of course the RoR API

How to randomly pick an element from an array

Take a look at this question:

How do I generate random integers within a specific range in Java?

You will want to generate a random number from 0 to your integers length - 1. Then simply get your int from your array:

myArray[myRandomNumber];

How to make a loop in x86 assembly language?

Yet another method is using the LOOP instruction:

mov  cx, 3

myloop:
    ; Your loop content

    loop myloop

The loop instruction automatically decrements cx, and only jumps if cx != 0. There are also LOOPE, and LOOPNE variants, if you want to do some additional check for your loop to break out early.

If you want to modify cx during your loop, make sure to push it onto the stack before the loop content, and pop it off after:

mov  cx, 3

myloop:
    push cx
    ; Your loop content
    pop  cx

    loop myloop

How to Update Date and Time of Raspberry Pi With out Internet

Thanks for the replies.
What I did was,
1. I install meinberg ntp software application on windows 7 pc. (softros ntp server is also possible.)
2. change raspberry pi ntp.conf file (for auto update date and time)

server xxx.xxx.xxx.xxx iburst
server 1.debian.pool.ntp.org iburst
server 2.debian.pool.ntp.org iburst
server 3.debian.pool.ntp.org iburst

3. If you want to make sure that date and time update at startup run this python script in rpi,

import os

try:
    client = ntplib.NTPClient()
    response = client.request('xxx.xxx.xxx.xxx', version=4)
    print "===================================="
    print "Offset : "+str(response.offset)
    print "Version : "+str(response.version)
    print "Date Time : "+str(ctime(response.tx_time))
    print "Leap : "+str(ntplib.leap_to_text(response.leap))
    print "Root Delay : "+str(response.root_delay)
    print "Ref Id : "+str(ntplib.ref_id_to_text(response.ref_id))
    os.system("sudo date -s '"+str(ctime(response.tx_time))+"'")
    print "===================================="
except:
    os.system("sudo date")
    print "NTP Server Down Date Time NOT Set At The Startup"
    pass

I found more info in raspberry pi forum.

How to get the list of files in a directory in a shell script?

find "${search_dir}" "${work_dir}" -mindepth 1 -maxdepth 1 -type f -print0 | xargs -0 -I {} echo "{}"

Defining a `required` field in Bootstrap

Update 2018

Since the original answer HTML5 validation is now supported in all modern browsers. Now the easiest way to make a field required is simply using the required attibute.

<input type="email" class="form-control" id="exampleInputEmail1" required>

or in compliant HTML5:

<input type="email" class="form-control" id="exampleInputEmail1" required="true">

Read more on Bootstrap 4 validation


In Bootstrap 3, you can apply a "validation state" class to the parent element: http://getbootstrap.com/css/#forms-control-validation

For example has-error will show a red border around the input. However, this will have no impact on the actual validation of the field. You'd need to add some additional client (javascript) or server logic to make the field required.

Demo: http://bootply.com/90564


Dynamic loading of images in WPF

Here is the extension method to load an image from URI:

public static BitmapImage GetBitmapImage(
    this Uri imageAbsolutePath,
    BitmapCacheOption bitmapCacheOption = BitmapCacheOption.Default)
{
    BitmapImage image = new BitmapImage();
    image.BeginInit();
    image.CacheOption = bitmapCacheOption;
    image.UriSource = imageAbsolutePath;
    image.EndInit();

    return image;
}

Sample of use:

Uri _imageUri = new Uri(imageAbsolutePath);
ImageXamlElement.Source = _imageUri.GetBitmapImage(BitmapCacheOption.OnLoad);

Simple as that!

Execution failed for task :':app:mergeDebugResources'. Android Studio

For me. I changed the color of .xml image (vector image) like this.

ic_action_add.xml

  <vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24"
    android:viewportHeight="24"
    android:tint="#FFFFFF"
    android:alpha="0.8">
  <path
      android:fillColor="@android:color/white"
      android:pathData="M19,13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/>
</vector>

to:

<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24"
    android:viewportHeight="24"
    android:tint="#FFFFFF"
    android:alpha="0.8">
  <path
      android:fillColor="#FF000000"
      android:pathData="M19,13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/>
</vector>

i just changed android:fillColor="@android:color/white" to android:fillColor="#FF000000"

and it's worked for me :)

How to set up gradle and android studio to do release build?

  1. open the Build Variants pane, typically found along the lower left side of the window:

Build Variants

  1. set debug to release
  2. shift+f10 run!!

then, Android Studio will execute assembleRelease task and install xx-release.apk to your device.

How to import classes defined in __init__.py

Edit, since i misunderstood the question:

Just put the Helper class in __init__.py. Thats perfectly pythonic. It just feels strange coming from languages like Java.

Android and Facebook share intent

Apparently Facebook no longer (as of 2014) allows you to customise the sharing screen, no matter if you are just opening sharer.php URL or using Android intents in more specialised ways. See for example these answers:

Anyway, using plain Intents, you can still share a URL, but not any default text with it, as billynomates commented. (Also, if you have no URL to share, just launching Facebook app with empty "Write Post" (i.e. status update) dialog is equally easy; use the code below but leave out EXTRA_TEXT.)

Here's the best solution I've found that does not involve using any Facebook SDKs.

This code opens the official Facebook app directly if it's installed, and otherwise falls back to opening sharer.php in a browser. (Most of the other solutions in this question bring up a huge "Complete action using…" dialog which isn't optimal at all!)

String urlToShare = "https://stackoverflow.com/questions/7545254";
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
// intent.putExtra(Intent.EXTRA_SUBJECT, "Foo bar"); // NB: has no effect!
intent.putExtra(Intent.EXTRA_TEXT, urlToShare);

// See if official Facebook app is found
boolean facebookAppFound = false;
List<ResolveInfo> matches = getPackageManager().queryIntentActivities(intent, 0);
for (ResolveInfo info : matches) {
    if (info.activityInfo.packageName.toLowerCase().startsWith("com.facebook.katana")) {
        intent.setPackage(info.activityInfo.packageName);
        facebookAppFound = true;
        break;
    }
}

// As fallback, launch sharer.php in a browser
if (!facebookAppFound) {
    String sharerUrl = "https://www.facebook.com/sharer/sharer.php?u=" + urlToShare;
    intent = new Intent(Intent.ACTION_VIEW, Uri.parse(sharerUrl));
}

startActivity(intent);

(Regarding the com.facebook.katana package name, see MatheusJardimB's comment.)

The result looks like this on my Nexus 7 (Android 4.4) with Facebook app installed:

enter image description here

Manifest merger failed : uses-sdk:minSdkVersion 14

The problem still arises with transitive dependencies. Gradle offers a way to force the usage of a specific version of a dependency.

For example you can add something like:

configurations.all {
    resolutionStrategy {
        force 'com.android.support:support-v4:20.+'
        force 'com.android.support:appcompat-v7:20.+'
    }
}

to your build.gradle.

If you want to learn more about gradle resolution strategies refer to this guide http://www.gradle.org/docs/current/dsl/org.gradle.api.artifacts.ResolutionStrategy.html

I found this while reading the corresponding issue which I will link here

How do I get AWS_ACCESS_KEY_ID for Amazon?

Amazon changes the admin console from time to time, hence the previous answers above are irrelevant in 2020.

The way to get the secret access key (Oct.2020) is:

  1. go to IAM console: https://console.aws.amazon.com/iam
  2. click on "Users". (see image) enter image description here
  3. go to the user you need his access key. enter image description here

As i see the answers above, I can assume my answer will become irrelevant in a year max :-)

HTH

Reset ID autoincrement ? phpmyadmin

ALTER TABLE xxx AUTO_INCREMENT =1; or clear your table by TRUNCATE

Why do we need to use flatMap?

flatMap transform the items emitted by an Observable into Observables, then flatten the emissions from those into a single Observable

I am not stupid but had to read this 10 times and still don't get it. When I read the code snippet :

[1,2,3].map(x => [x, x * 10])
// [[1, 10], [2, 20], [3, 30]]

[1,2,3].flatMap(x => [x, x * 10])
// [1, 10, 2, 20, 3, 30]

then I could understand whats happening, it does two things :

flatMap :

  1. map: transform *) emitted items into Observables.
  2. flat: then merge those Observables as one Observable.

*) The transform word says the item can be transformed in something else.

Then the merge operator becomes clear to, it does the flattening without the mapping. Why not calling it mergeMap? It seems there is also an Alias mergeMap with that name for flatMap.

Using Service to run background and create notification

Your error is in UpdaterServiceManager in onCreate and showNotification method.

You are trying to show notification from Service using Activity Context. Whereas Every Service has its own Context, just use the that. You don't need to pass a Service an Activity's Context.I don't see why you need a specific Activity's Context to show Notification.

Put your createNotification method in UpdateServiceManager.class. And remove CreateNotificationActivity not from Service.

You cannot display an application window/dialog through a Context that is not an Activity. Try passing a valid activity reference

node.js, socket.io with SSL

This is how I managed to set it up with express:

var fs = require( 'fs' );
var app = require('express')();
var https        = require('https');
var server = https.createServer({
    key: fs.readFileSync('./test_key.key'),
    cert: fs.readFileSync('./test_cert.crt'),
    ca: fs.readFileSync('./test_ca.crt'),
    requestCert: false,
    rejectUnauthorized: false
},app);
server.listen(8080);

var io = require('socket.io').listen(server);

io.sockets.on('connection',function (socket) {
    ...
});

app.get("/", function(request, response){
    ...
})


I hope that this will save someone's time.

Update : for those using lets encrypt use this

var server = https.createServer({ 
                key: fs.readFileSync('privkey.pem'),
                cert: fs.readFileSync('fullchain.pem') 
             },app);

What's the difference between JavaScript and Java?

JavaScript is an object-oriented scripting language that allows you to create dynamic HTML pages, allowing you to process input data and maintain data, usually within the browser.

Java is a programming language, core set of libraries, and virtual machine platform that allows you to create compiled programs that run on nearly every platform, without distribution of source code in its raw form or recompilation.

While the two have similar names, they are really two completely different programming languages/models/platforms, and are used to solve completely different sets of problems.

Also, this is directly from the Wikipedia Javascript article:

A common misconception is that JavaScript is similar or closely related to Java; this is not so. Both have a C-like syntax, are object-oriented, are typically sandboxed and are widely used in client-side Web applications, but the similarities end there. Java has static typing; JavaScript's typing is dynamic (meaning a variable can hold an object of any type and cannot be restricted). Java is loaded from compiled bytecode; JavaScript is loaded as human-readable code. C is their last common ancestor language.

How to reverse a 'rails generate'

It's worth mentioning the -p flag here ("p" for pretend).

If you add this to the command it will simply do a "test" run and show you what files will be deleted without actually deleting them.

$ rails d controller welcome -p

  remove  app/controllers/welcome_controller.rb
  invoke  erb
  remove    app/views/welcome
  invoke  test_unit
  remove    test/controllers/welcome_controller_test.rb
  invoke  helper
  remove    app/helpers/welcome_helper.rb
  invoke    test_unit
  remove      test/helpers/welcome_helper_test.rb
  invoke  assets
  invoke    coffee
  remove      app/assets/javascripts/welcome.js.coffee
  invoke    scss
  remove      app/assets/stylesheets/welcome.css.scss

If you're happy with it, run the command again without the -p flag.

Sending email from Command-line via outlook without having to click send

Option 1
You didn't say much about your environment, but assuming you have it available you could use a PowerShell script; one example is here. The essence of this is:

$smtp = New-Object Net.Mail.SmtpClient("ho-ex2010-caht1.exchangeserverpro.net")
$smtp.Send("[email protected]","[email protected]","Test Email","This is a test")

You could then launch the script from the command line as per this example:

powershell.exe -noexit c:\scripts\test.ps1

Note that PowerShell 2.0, which is installed by default on Windows 7 and Windows Server 2008R2, includes a simpler Send-MailMessage command, making things easier.

Option 2
If you're prepared to use third-party software, is something line this SendEmail command-line tool. It depends on your target environment, though; if you're deploying your batch file to multiple machines, that will obviously require inclusion (but not formal installation) each time.

Option 3
You could drive Outlook directly from a VBA script, which in turn you would trigger from a batch file; this would let you send an email using Outlook itself, which looks to be closest to what you're wanting. There are two parts to this; first, figure out the VBA scripting required to send an email. There are lots of examples for this online, including from Microsoft here. Essence of this is:

Sub SendMessage(DisplayMsg As Boolean, Optional AttachmentPath)
    Dim objOutlook As Outlook.Application
    Dim objOutlookMsg As Outlook.MailItem
    Dim objOutlookRecip As Outlook.Recipient
    Dim objOutlookAttach As Outlook.Attachment

    Set objOutlook = CreateObject("Outlook.Application")
    Set objOutlookMsg  = objOutlook.CreateItem(olMailItem)

    With objOutlookMsg
        Set objOutlookRecip = .Recipients.Add("Nancy Davolio")
        objOutlookRecip.Type = olTo
        ' Set the Subject, Body, and Importance of the message.
        .Subject = "This is an Automation test with Microsoft Outlook"
        .Body = "This is the body of the message." &vbCrLf & vbCrLf
        .Importance = olImportanceHigh  'High importance

        If Not IsMissing(AttachmentPath) Then
            Set objOutlookAttach = .Attachments.Add(AttachmentPath)
        End If

        For Each ObjOutlookRecip In .Recipients
            objOutlookRecip.Resolve
        Next

        .Save
        .Send
    End With
    Set objOutlook = Nothing
End Sub

Then, launch Outlook from the command line with the /autorun parameter, as per this answer (alter path/macroname as necessary):

C:\Program Files\Microsoft Office\Office11\Outlook.exe" /autorun macroname

Option 4
You could use the same approach as option 3, but move the Outlook VBA into a PowerShell script (which you would run from a command line). Example here. This is probably the tidiest solution, IMO.

How do you get the width and height of a multi-dimensional array?

You use Array.GetLength with the index of the dimension you wish to retrieve.

Fragment onResume() & onPause() is not called on backstack

A fragment must always be embedded in an activity and the fragment's lifecycle is directly affected by the host activity's lifecycle. For example, when the activity is paused, so are all fragments in it, and when the activity is destroyed, so are all fragments

Apache could not be started - ServerRoot must be a valid directory and Unable to find the specified module

Below solved. I have wrongly given the bin /directory/, so faced the issue:

if you installed apache at C:/httpd-2.4.41-o102s-x64-vc14-r2/Apache24
then the modules are at.. C:/httpd-2.4.41-o102s-x64-vc14-r2/Apache24/modules

So, the file           C:/httpd-2.4.41-o102s-x64-vc14-r2/Apache24/conf/httpd.conf
should have
       Define SRVROOT "C:/httpd-2.4.41-o102s-x64-vc14-r2/Apache24/"

Hope that helps

git status shows modifications, git checkout -- <file> doesn't remove them

If you clone a repository and instantly see pending changes, then the repository is in an inconsistent state. Please do NOT comment out * text=auto from the .gitattributes file. That was put there specifically because the owner of the repository wants all files stored consistently with LF line endings.

As stated by HankCa, following the instructions on https://help.github.com/articles/dealing-with-line-endings/ is the way to go to fix the problem. Easy button:

git clone git@host:repo-name
git checkout -b normalize-line-endings
git add .
git commit -m "Normalize line endings"
git push
git push -u origin normalize-line-endings

Then merge (or pull request) the branch to the owner of the repo.

CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response

The res.header('Access-Control-Allow-Origin', '*'); wouldn't work with Autorization header. Just enable pre-flight request, using cors library:

var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
app.options('*', cors())

Double vs. BigDecimal?

If you write down a fractional value like 1 / 7 as decimal value you get

1/7 = 0.142857142857142857142857142857142857142857...

with an infinite sequence of 142857. Since you can only write a finite number of digits you will inevitably introduce a rounding (or truncation) error.

Numbers like 1/10 or 1/100 expressed as binary numbers with a fractional part also have an infinite number of digits after the decimal point:

1/10 = binary 0.0001100110011001100110011001100110...

Doubles store values as binary and therefore might introduce an error solely by converting a decimal number to a binary number, without even doing any arithmetic.

Decimal numbers (like BigDecimal), on the other hand, store each decimal digit as is (binary coded, but each decimal on its own). This means that a decimal type is not more precise than a binary floating point or fixed point type in a general sense (i.e. it cannot store 1/7 without loss of precision), but it is more accurate for numbers that have a finite number of decimal digits as is often the case for money calculations.

Java's BigDecimal has the additional advantage that it can have an arbitrary (but finite) number of digits on both sides of the decimal point, limited only by the available memory.

Bootstrap 4 - Glyphicons migration?

You can use both Font Awesome and Github Octicons as a free alternative for Glyphicons.

Bootstrap 4 also switched from Less to Sass, so you might integerate the font's Sass (SCSS) into you build process, to create a single CSS file for your projects.

Also see https://getbootstrap.com/docs/4.1/getting-started/build-tools/ to find out how to set up your tooling:

  1. Download and install Node, which we use to manage our dependencies.
  2. Navigate to the root /bootstrap directory and run npm install to install our local dependencies listed in package.json.
  3. Install Ruby, install Bundler with gem install bundler, and finally run bundle install. This will install all Ruby dependencies, such as Jekyll and plugins.

Font Awesome

  1. Download the files at https://github.com/FortAwesome/Font-Awesome/tree/fa-4
  2. Copy the font-awesome/scss folder into your /bootstrap folder
  3. Open your SCSS /bootstrap/bootstrap.scss and write down the following SCSS code at the end of this file:

    $fa-font-path: "../fonts"; @import "../font-awesome/scss/font-awesome.scss";

  4. Notice that you also have to copy the font file from font-awesome/fonts to dist/fonts or any other public folder set by $fa-font-path in the previous step

  5. Run: npm run dist to recompile your code with Font-Awesome

Github Octicons

  1. Download the files at https://github.com/github/octicons/
  2. Copy the octicons folder into your /bootstrap folder
  3. Open your SCSS /bootstrap/bootstrap.scss and write down the following SCSS code at the end of this file:

    $fa-font-path: "../fonts"; @import "../octicons/octicons/octicons.scss";

  4. Notice that you also have to copy the font file from font-awesome/fonts to dist/fonts or any other public folder set by $fa-font-path in the previous step

  5. Run: npm run dist to recompile your code with Octicons

Glyphicons

On the Bootstrap website you can read:

Includes over 250 glyphs in font format from the Glyphicon Halflings set. Glyphicons Halflings are normally not available for free, but their creator has made them available for Bootstrap free of cost. As a thank you, we only ask that you include a link back to Glyphicons whenever possible.

As I understand you can use these 250 glyphs free of cost restricted for Bootstrap but not limited to version 3 exclusive. So you can use them for Bootstrap 4 too.

  1. Copy the fonts files from: https://github.com/twbs/bootstrap-sass/tree/master/assets/fonts/bootstrap
  2. Copy the https://github.com/twbs/bootstrap-sass/blob/master/assets/stylesheets/bootstrap/_glyphicons.scss file into your bootstrap/scss folder
  3. Open your scss /bootstrap/bootstrap.scss and write down the following SCSS code at the end of this file:
$bootstrap-sass-asset-helper: false;
$icon-font-name: 'glyphicons-halflings-regular';
$icon-font-svg-id: 'glyphicons_halflingsregular';
$icon-font-path: '../fonts/';
@import "glyphicons";
  1. Run: npm run dist to recompile your code with Glyphicons

Notice that Bootstrap 4 requires the post CSS Autoprefixer for compiling. When you are using a static Sass compiler to compile your CSS you should have to run the Autoprefixer afterwards.

You can find out more about mixing with the Bootstrap 4 SCSS in here.

You can also use Bower to install the fonts above. Using Bower Font Awesome installs your files in bower_components/components-font-awesome/ also notice that Github Octicons sets the octicons/octicons/octicons-.scss as the main file whilst you should use octicons/octicons/sprockets-octicons.scss.

All the above will compile all your CSS code including into a single file, which requires only one HTTP request. Alternatively you can also load the Font-Awesome font from CDN, which can be fast too in many situations. Both fonts on CDN also include the font files (using data-uri's, possible not supported for older browsers). So consider which solution best fits your situation depending on among others browsers to support.

For Font Awesome paste the following code into the <head> section of your site's HTML:

<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">

Also try Yeoman generator to scaffold out a front-end Bootstrap 4 Web app to test Bootstrap 4 with Font Awesome or Github Octicons.

How do I make Git use the editor of my choice for commits?

For EmEditor users

To set EmEditor as the default text editor for Git, open Git Bash, and type:

git config --global core.editor "emeditor.exe -sp"

EmEditor v19.9.2 or later required.

Tomcat won't stop or restart

Recent I have met several times of stop abnormal. Although shutdown.sh provides some information, The situations are:

  • result of the command ps -ef| grep java is Null.
  • result of the command ps -ef| grep java is not null.

My opinion is just kill the process of Catalina and remove the pid file (In your situation is /opt/tomcat/work/catalina.pid.)

The result seems not so seriously to influence others.

Python 3: UnboundLocalError: local variable referenced before assignment

Why not simply return your calculated value and let the caller modify the global variable. It's not a good idea to manipulate a global variable within a function, as below:

Var1 = 1
Var2 = 0

def function(): 
    if Var2 == 0 and Var1 > 0:
        print("Result One")
    elif Var2 == 1 and Var1 > 0:
        print("Result Two")
    elif Var1 < 1:
        print("Result Three")
    return Var1 - 1

Var1 = function()

or even make local copies of the global variables and work with them and return the results which the caller can then assign appropriately

def function():
v1, v2 = Var1, Var2
# calculate using the local variables v1 & v2
return v1 - 1

Var1 = function()

How do I perform query filtering in django templates

You can't do this, which is by design. The Django framework authors intended a strict separation of presentation code from data logic. Filtering models is data logic, and outputting HTML is presentation logic.

So you have several options. The easiest is to do the filtering, then pass the result to render_to_response. Or you could write a method in your model so that you can say {% for object in data.filtered_set %}. Finally, you could write your own template tag, although in this specific case I would advise against that.

how to set mongod --dbpath

Windows environment, local machine. I had an error

[js] Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed: SocketException: 
Error connecting to 127.0.0.1:27017 :: caused by :: 
No connection could be made because the target machine actively refused it. :

After some back and forth attempts I decided

  • to check Windows "Task Manager". I noticed that MongoDB process is stopped.
  • I made it run. Everything starts working as expected.

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

In very laymen terms the class is a mold and the object is the copy made with that mold. Static belong to the mold and can be accessed directly without making any copies, hence the example above

How to tell if node.js is installed or not

Check the node version using node -v. Check the npm version using npm -v. If these commands gave you version number you are good to go with NodeJs development

Time to test node

Create a Directory using mkdir NodeJs. Inside the NodeJs folder create a file using touch index.js. Open your index.js either using vi or in your favourite text editor. Type in console.log('Welcome to NodesJs.') and save it. Navigate back to your saved file and type node index.js. If you see Welcome to NodesJs. you did a nice job and you are up with NodeJs.

SELECT COUNT in LINQ to SQL C#

You should be able to do the count on the purch variable:

purch.Count();

e.g.

var purch = from purchase in myBlaContext.purchases
select purchase;

purch.Count();

Read Post Data submitted to ASP.Net Form

Read the Request.Form NameValueCollection and process your logic accordingly:

NameValueCollection nvc = Request.Form;
string userName, password;
if (!string.IsNullOrEmpty(nvc["txtUserName"]))
{
  userName = nvc["txtUserName"];
}

if (!string.IsNullOrEmpty(nvc["txtPassword"]))
{
  password = nvc["txtPassword"];
}

//Process login
CheckLogin(userName, password);

... where "txtUserName" and "txtPassword" are the Names of the controls on the posting page.

Set an empty DateTime variable

The .addwithvalue needs dbnull. You could do something like this:

DateTime? someDate = null;
//...
if (someDate == null)
    myCommand.Parameters.AddWithValue("@SurgeryDate", DBnull.value);

or use a method extension...

  public static class Extensions
    {
        public static SqlParameter AddWithNullValue(this SqlParameterCollection collection, string parameterName, object value)
        {
            if (value == null)
                return collection.AddWithValue(parameterName, DBNull.Value);
            else
                return collection.AddWithValue(parameterName, value);
        }
    }

How to delete/truncate tables from Hadoop-Hive?

Use the following to delete all the tables in a linux environment.

hive -e 'show tables' | xargs -I '{}' hive -e 'drop table {}'

How can I manually generate a .pyc file from a .py file

  1. create a new python file in the directory of the file.
  2. type import (the name of the file without the extension)
  3. run the file
  4. open the directory, then find the pycache folder
  5. inside should be your .pyc file

How do I insert multiple checkbox values into a table?

I think you should $_POST[][], i tried it and it work :)), tks

SQL LIKE condition to check for integer?

If you want to search as string, you can cast to text like this:

SELECT * FROM books WHERE price::TEXT LIKE '123%'

jQuery toggle animation

onmouseover="$('.play-detail').stop().animate({'height': '84px'},'300');" 

onmouseout="$('.play-detail').stop().animate({'height': '44px'},'300');"

Just put two stops -- one onmouseover and one onmouseout.

Removing double quotes from a string in Java

String withoutQuotes_line1 = line1.replace("\"", "");

have a look here

How to handle-escape both single and double quotes in an SQL-Update statement

In C# and VB the SqlCommand object implements the Parameter.AddWithValue method which handles this situation

How to show full object in Chrome console?

You might get even better results if you try:

console.log(JSON.stringify(obj, null, 4));

How can I start PostgreSQL server on Mac OS X?

None of the previous answers fixed the issue for me, despite getting the same error messages.

I was able to get my instance back up and running by deleting the existing postmaster.pid file which was locked and was not allowing connections.

What is a correct MIME type for .docx, .pptx, etc.?

Just look at MDN Web Docs.

Here is a list of MIME types, associated by type of documents, ordered by their common extensions:

Common MIME types

How to access single elements in a table in R

?"[" pretty much covers the various ways of accessing elements of things.

Under usage it lists these:

x[i]
x[i, j, ... , drop = TRUE]
x[[i, exact = TRUE]]
x[[i, j, ..., exact = TRUE]]
x$name
getElement(object, name)

x[i] <- value
x[i, j, ...] <- value
x[[i]] <- value
x$i <- value

The second item is sufficient for your purpose

Under Arguments it points out that with [ the arguments i and j can be numeric, character or logical

So these work:

data[1,1]
data[1,"V1"]

As does this:

data$V1[1]

and keeping in mind a data frame is a list of vectors:

data[[1]][1]
data[["V1"]][1]

will also both work.

So that's a few things to be going on with. I suggest you type in the examples at the bottom of the help page one line at a time (yes, actually type the whole thing in one line at a time and see what they all do, you'll pick up stuff very quickly and the typing rather than copypasting is an important part of helping to commit it to memory.)

Creating a DateTime in a specific Time Zone in c#

Using TimeZones class makes it easy to create timezone specific date.

TimeZoneInfo.ConvertTime(DateTime.Now, TimeZoneInfo.FindSystemTimeZoneById(TimeZones.Paris.Id));

Vue.js redirection to another page

can try this too ...

router.push({ name: 'myRoute' })

How to display an unordered list in two columns?

The legacy solution in the top answer didn't work for me because I wanted to affect multiple lists on the page and the answer assumes a single list plus it uses a fair bit of global state. In this case I wanted to alter every list inside a <section class="list-content">:

const columns = 2;
$("section.list-content").each(function (index, element) {
    let section = $(element);
    let items = section.find("ul li").detach();
    section.find("ul").detach();
    for (let i = 0; i < columns; i++) {
        section.append("<ul></ul>");
    }
    let lists = section.find("ul");
    for (let i = 0; i < items.length; i++) {
        lists.get(i % columns).append(items[i]);
    }
});

How to handle a single quote in Oracle SQL

I found the above answer giving an error with Oracle SQL, you also must use square brackets, below;

SQL> SELECT Q'[Paddy O'Reilly]' FROM DUAL;


Result: Paddy O'Reilly

Is there a way to only install the mysql client (Linux)?

[root@localhost administrador]# yum search mysql | grep client
community-mysql.i686 : MySQL client programs and shared libraries
                            : client
community-mysql-libs.i686 : The shared libraries required for MySQL clients
root-sql-mysql.i686 : MySQL client plugin for ROOT
mariadb-libs.i686 : The shared libraries required for MariaDB/MySQL clients
[root@localhost administrador]# yum install  -y community-mysql

How to overwrite the previous print to stdout in python?

Simple Version

One way is to use the carriage return ('\r') character to return to the start of the line without advancing to the next line.

Python 3

for x in range(10):
    print(x, end='\r')
print()

Python 2.7 forward compatible

from __future__ import print_function
for x in range(10):
    print(x, end='\r')
print()

Python 2.7

for x in range(10):
    print '{}\r'.format(x),
print

Python 2.0-2.6

for x in range(10):
    print '{0}\r'.format(x),
print

In the latter two (Python 2-only) cases, the comma at the end of the print statement tells it not to go to the next line. The last print statement advances to the next line so your prompt won't overwrite your final output.

Line Cleaning

If you can’t guarantee that the new line of text is not shorter than the existing line, then you just need to add a “clear to end of line” escape sequence, '\x1b[1K' ('\x1b' = ESC):

for x in range(75):
    print(‘*’ * (75 - x), x, end='\x1b[1K\r')
print()

How to find the day, month and year with moment.js

Just try with:

var check = moment(n.entry.date_entered, 'YYYY/MM/DD');

var month = check.format('M');
var day   = check.format('D');
var year  = check.format('YYYY');

JSFiddle

What's a clean way to stop mongod on Mac OS X?

If the service is running via brew, you can stop it using the following command:

brew services stop mongodb

String delimiter in string.split method

String[] splitArray = subjectString.split("\\|\\|");

You use a function:

public String[] stringSplit(String string){

    String[] splitArray = string.split("\\|\\|");
    return splitArray;
}

line breaks in a textarea

Some wrong answers are posted here. instead of replacing \n to <br />, they are replacing <br /> to \n

So here is a good answer to store <br /> in your mysql when you entered in textarea:

str_replace("\n", '<br />',  $textarea);

How get data from material-ui TextField, DropDownMenu components?

Add an onChange handler to each of your TextField and DropDownMenu elements. When it is called, save the new value of these inputs in the state of your Content component. In render, retrieve these values from state and pass them as the value prop. See Controlled Components.

var Content = React.createClass({

    getInitialState: function() {
        return {
            textFieldValue: ''
        };
    },

    _handleTextFieldChange: function(e) {
        this.setState({
            textFieldValue: e.target.value
        });
    },

    render: function() {
        return (
            <div>
                <TextField value={this.state.textFieldValue} onChange={this._handleTextFieldChange} />
            </div>
        )
    }

});

Now all you have to do in your _handleClick method is retrieve the values of all your inputs from this.state and send them to the server.

You can also use the React.addons.LinkedStateMixin to make this process easier. See Two-Way Binding Helpers. The previous code becomes:

var Content = React.createClass({

    mixins: [React.addons.LinkedStateMixin],

    getInitialState: function() {
        return {
            textFieldValue: ''
        };
    },

    render: function() {
        return (
            <div>
                <TextField valueLink={this.linkState('textFieldValue')} />
            </div>
        )
    }

});

Find most frequent value in SQL column

If you have an ID column and you want to find most repetitive category from another column for each ID then you can use below query,

Table:

Table content

Query:

SELECT ID, CATEGORY, COUNT(*) AS FREQ
FROM TABLE
GROUP BY 1,2
QUALIFY ROW_NUMBER() OVER(PARTITION BY ID ORDER BY FREQ DESC) = 1;

Result:

Query result

What's the difference between JPA and Hibernate?

JPA is Java Persistence API. Which Specifies only the specifications for APIs. Means that the set of rules and guidelines for creating the APIs. If says another context, It is set of standards which provides the wrapper for creating those APIs , can be use for accessing entity object from database. JPA is provided by oracle.When we are going to do database access , we definitely needs its implementation. Means JPA specifies only guidelines for implementing APIs. Hibernate is a JPA provider/Vendor who responsible for implementing that APIs. Like Hibernate TopLink and Open JPA is some of examples of JPA API providers. So we uses JPA specified standard APIs through hibernate.

Check element exists in array

Look before you leap (LBYL):

if idx < len(array):
    array[idx]
else:
    # handle this

Easier to ask forgiveness than permission (EAFP):

try:
    array[idx]
except IndexError:
    # handle this

In Python, EAFP seems to be the popular and preferred style. It is generally more reliable, and avoids an entire class of bugs (time of check vs. time of use). All other things being equal, the try/except version is recommended - don't see it as a "last resort".

This excerpt is from the official docs linked above, endorsing using try/except for flow control:

This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements.

Create an Oracle function that returns a table

I think you want a pipelined table function.

Something like this:

CREATE OR REPLACE PACKAGE test AS

    TYPE measure_record IS RECORD(
       l4_id VARCHAR2(50), 
       l6_id VARCHAR2(50), 
       l8_id VARCHAR2(50), 
       year NUMBER, 
       period NUMBER,
       VALUE NUMBER);

    TYPE measure_table IS TABLE OF measure_record;

    FUNCTION get_ups(foo NUMBER)
        RETURN measure_table
        PIPELINED;
END;

CREATE OR REPLACE PACKAGE BODY test AS

    FUNCTION get_ups(foo number)
        RETURN measure_table
        PIPELINED IS

        rec            measure_record;

    BEGIN
        SELECT 'foo', 'bar', 'baz', 2010, 5, 13
          INTO rec
          FROM DUAL;

        -- you would usually have a cursor and a loop here   
        PIPE ROW (rec);

        RETURN;
    END get_ups;
END;

For simplicity I removed your parameters and didn't implement a loop in the function, but you can see the principle.

Usage:

SELECT *
  FROM table(test.get_ups(0));



L4_ID L6_ID L8_ID       YEAR     PERIOD      VALUE
----- ----- ----- ---------- ---------- ----------
foo   bar   baz         2010          5         13
1 row selected.

How to create windows service from java jar?

I've been experimenting with Apache Commons Daemon. It's supports windows (Procrun) and unix (Jsvc). Advanced Installer has a Java Service tutorial with an example project to download. If you get their javaservice.jar running as a windows service you can test it by using "telnet 4444". I used their example because my focus was on getting a java windows service running, not writing java.

How to remove foreign key constraint in sql server?

alter table <referenced_table_name> drop  primary key;

Foreign key constraint will be removed.

hibernate - get id after save object

The session.save(object) returns the id of the object, or you could alternatively call the id getter method after performing a save.

Save() return value:

Serializable save(Object object) throws HibernateException

Returns:

the generated identifier

Getter method example:

UserDetails entity:

@Entity
public class UserDetails {
    @Id
    @GeneratedValue
    private int id;
    private String name;

    // Constructor, Setters & Getters
}

Logic to test the id's :

Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.getTransaction().begin();
UserDetails user1 = new UserDetails("user1");
UserDetails user2 = new UserDetails("user2");

//int userId = (Integer) session.save(user1); // if you want to save the id to some variable

System.out.println("before save : user id's = "+user1.getId() + " , " + user2.getId());

session.save(user1);
session.save(user2);

System.out.println("after save : user id's = "+user1.getId() + " , " + user2.getId());

session.getTransaction().commit();

Output of this code:

before save : user id's = 0 , 0

after save : user id's = 1 , 2

As per this output, you can see that the id's were not set before we save the UserDetails entity, once you save the entities then Hibernate set's the id's for your objects - user1 and user2

Adding open/closed icon to Twitter Bootstrap collapsibles (accordions)

Added to @muffls answer so that this works with all twitter bootstrap collapse and makes the change to the arrow before the animatation starts.

$('.collapse').on('show', function(){
    $(this).parent().find(".icon-chevron-left").removeClass("icon-chevron-left").addClass("icon-chevron-down");
}).on('hide', function(){
    $(this).parent().find(".icon-chevron-down").removeClass("icon-chevron-down").addClass("icon-chevron-left");
});

Depending on your HTML structure you may need to modify the parent().

Drawing rotated text on a HTML5 canvas

Like others have mentioned, you probably want to look at reusing an existing graphing solution, but rotating text isn't too difficult. The somewhat confusing bit (to me) is that you rotate the whole context and then draw on it:

ctx.rotate(Math.PI*2/(i*6));

The angle is in radians. The code is taken from this example, which I believe was made for the transformations part of the MDC canvas tutorial.

Please see the answer below for a more complete solution.

How to check if keras tensorflow backend is GPU or CPU version?

According to the documentation.

If you are running on the TensorFlow or CNTK backends, your code will automatically run on GPU if any available GPU is detected.

You can check what all devices are used by tensorflow by -

from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())

Also as suggested in this answer

import tensorflow as tf
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))

This will print whether your tensorflow is using a CPU or a GPU backend. If you are running this command in jupyter notebook, check out the console from where you have launched the notebook.

If you are sceptic whether you have installed the tensorflow gpu version or not. You can install the gpu version via pip.

pip install tensorflow-gpu

Get file size before uploading

<script type="text/javascript">
function AlertFilesize(){
    if(window.ActiveXObject){
        var fso = new ActiveXObject("Scripting.FileSystemObject");
        var filepath = document.getElementById('fileInput').value;
        var thefile = fso.getFile(filepath);
        var sizeinbytes = thefile.size;
    }else{
        var sizeinbytes = document.getElementById('fileInput').files[0].size;
    }

    var fSExt = new Array('Bytes', 'KB', 'MB', 'GB');
    fSize = sizeinbytes; i=0;while(fSize>900){fSize/=1024;i++;}

    alert((Math.round(fSize*100)/100)+' '+fSExt[i]);
}
</script>

<input id="fileInput" type="file" onchange="AlertFilesize();" />

Work on IE and FF

Insert an element at a specific index in a list and return the updated list

The shortest I got: b = a[:2] + [3] + a[2:]

>>>
>>> a = [1, 2, 4]
>>> print a
[1, 2, 4]
>>> b = a[:2] + [3] + a[2:]
>>> print a
[1, 2, 4]
>>> print b
[1, 2, 3, 4]

Android emulator: How to monitor network traffic?

You can monitor network traffic from Android Studio. Go to Android Monitor and open Network tab.

http://developer.android.com/tools/debugging/ddms.html

UPDATE: ?? Android Device Monitor was deprecated in Android Studio 3.1. See more in https://developer.android.com/studio/profile/monitor

PDF to byte array and vice versa

The problem is that you are calling toString() on the InputStream object itself. This will return a String representation of the InputStream object not the actual PDF document.

You want to read the PDF only as bytes as PDF is a binary format. You will then be able to write out that same byte array and it will be a valid PDF as it has not been modified.

e.g. to read a file as bytes

File file = new File(sourcePath);
InputStream inputStream = new FileInputStream(file); 
byte[] bytes = new byte[file.length()];
inputStream.read(bytes);

Fixed footer in Bootstrap

Add z-index:-9999; to this method, or it will cover your top bar if you have 1.

How to upload, display and save images using node.js and express

First of all, you should make an HTML form containing a file input element. You also need to set the form's enctype attribute to multipart/form-data:

<form method="post" enctype="multipart/form-data" action="/upload">
    <input type="file" name="file">
    <input type="submit" value="Submit">
</form>

Assuming the form is defined in index.html stored in a directory named public relative to where your script is located, you can serve it this way:

const http = require("http");
const path = require("path");
const fs = require("fs");

const express = require("express");

const app = express();
const httpServer = http.createServer(app);

const PORT = process.env.PORT || 3000;

httpServer.listen(PORT, () => {
  console.log(`Server is listening on port ${PORT}`);
});

// put the HTML file containing your form in a directory named "public" (relative to where this script is located)
app.get("/", express.static(path.join(__dirname, "./public")));

Once that's done, users will be able to upload files to your server via that form. But to reassemble the uploaded file in your application, you'll need to parse the request body (as multipart form data).

In Express 3.x you could use express.bodyParser middleware to handle multipart forms but as of Express 4.x, there's no body parser bundled with the framework. Luckily, you can choose from one of the many available multipart/form-data parsers out there. Here, I'll be using multer:

You need to define a route to handle form posts:

const multer = require("multer");

const handleError = (err, res) => {
  res
    .status(500)
    .contentType("text/plain")
    .end("Oops! Something went wrong!");
};

const upload = multer({
  dest: "/path/to/temporary/directory/to/store/uploaded/files"
  // you might also want to set some limits: https://github.com/expressjs/multer#limits
});


app.post(
  "/upload",
  upload.single("file" /* name attribute of <file> element in your form */),
  (req, res) => {
    const tempPath = req.file.path;
    const targetPath = path.join(__dirname, "./uploads/image.png");

    if (path.extname(req.file.originalname).toLowerCase() === ".png") {
      fs.rename(tempPath, targetPath, err => {
        if (err) return handleError(err, res);

        res
          .status(200)
          .contentType("text/plain")
          .end("File uploaded!");
      });
    } else {
      fs.unlink(tempPath, err => {
        if (err) return handleError(err, res);

        res
          .status(403)
          .contentType("text/plain")
          .end("Only .png files are allowed!");
      });
    }
  }
);

In the example above, .png files posted to /upload will be saved to uploaded directory relative to where the script is located.

In order to show the uploaded image, assuming you already have an HTML page containing an img element:

<img src="/image.png" />

you can define another route in your express app and use res.sendFile to serve the stored image:

app.get("/image.png", (req, res) => {
  res.sendFile(path.join(__dirname, "./uploads/image.png"));
});

How do I iterate over a JSON structure?

this is a pure commented JavaScript example.

  <script language="JavaScript" type="text/javascript">
  function iterate_json(){
            // Create our XMLHttpRequest object
            var hr = new XMLHttpRequest();
            // Create some variables we need to send to our PHP file
            hr.open("GET", "json-note.php", true);//this is your php file containing json

            hr.setRequestHeader("Content-type", "application/json", true);
            // Access the onreadystatechange event for the XMLHttpRequest object
            hr.onreadystatechange = function() {
                if(hr.readyState == 4 && hr.status == 200) {
                    var data = JSON.parse(hr.responseText);
                    var results = document.getElementById("myDiv");//myDiv is the div id
                    for (var obj in data){
                    results.innerHTML += data[obj].id+ "is"+data[obj].class + "<br/>";
                    }
                }
            }

            hr.send(null); 
        }
</script>
<script language="JavaScript" type="text/javascript">iterate_json();</script>// call function here

Find files containing a given text

Just to include one more alternative, you could also use this:

find "/starting/path" -type f -regextype posix-extended -regex "^.*\.(php|html|js)$" -exec grep -EH '(document\.cookie|setcookie)' {} \;

Where:

  • -regextype posix-extended tells find what kind of regex to expect
  • -regex "^.*\.(php|html|js)$" tells find the regex itself filenames must match
  • -exec grep -EH '(document\.cookie|setcookie)' {} \; tells find to run the command (with its options and arguments) specified between the -exec option and the \; for each file it finds, where {} represents where the file path goes in this command.

    while

    • E option tells grep to use extended regex (to support the parentheses) and...
    • H option tells grep to print file paths before the matches.

And, given this, if you only want file paths, you may use:

find "/starting/path" -type f -regextype posix-extended -regex "^.*\.(php|html|js)$" -exec grep -EH '(document\.cookie|setcookie)' {} \; | sed -r 's/(^.*):.*$/\1/' | sort -u

Where

  • | [pipe] send the output of find to the next command after this (which is sed, then sort)
  • r option tells sed to use extended regex.
  • s/HI/BYE/ tells sed to replace every First occurrence (per line) of "HI" with "BYE" and...
  • s/(^.*):.*$/\1/ tells it to replace the regex (^.*):.*$ (meaning a group [stuff enclosed by ()] including everything [.* = one or more of any-character] from the beginning of the line [^] till' the first ':' followed by anything till' the end of line [$]) by the first group [\1] of the replaced regex.
  • u tells sort to remove duplicate entries (take sort -u as optional).

...FAR from being the most elegant way. As I said, my intention is to increase the range of possibilities (and also to give more complete explanations on some tools you could use).

How do I access command line arguments in Python?

First, You will need to import sys

sys - System-specific parameters and functions

This module provides access to certain variables used and maintained by the interpreter, and to functions that interact strongly with the interpreter. This module is still available. I will edit this post in case this module is not working anymore.

And then, you can print the numbers of arguments or what you want here, the list of arguments.

Follow the script below :

#!/usr/bin/python

import sys

print 'Number of arguments entered :' len(sys.argv)

print 'Your argument list :' str(sys.argv)

Then, run your python script :

$ python arguments_List.py chocolate milk hot_Chocolate

And you will have the result that you were asking :

Number of arguments entered : 4
Your argument list : ['arguments_List.py', 'chocolate', 'milk', 'hot_Chocolate']

Hope that helped someone.

Permission denied (publickey,keyboard-interactive)

You may want to double check the authorized_keys file permissions:

$ chmod 600 ~/.ssh/authorized_keys

Newer SSH server versions are very picky on this respect.

The service cannot accept control messages at this time

I kept having this problem whenever I tried to start an app pool more than once. Rather than rebooting, I simply run the Application Information Service. (Note: This service is set to run manually on my system, which may be the reason for the problem.) From its description, it seems obvious that it is somehow involved:

Facilitates the running of interactive applications with additional administrative privileges. If this service is stopped, users will be unable to launch applications with the additional administrative privileges they may require to perform desired user tasks.

Presumably, IIS manager (as well as most other processes running as an administrator) does not maintain admin privileges throughout the life of the process, but instead request admin rights from the Application Information service on a case-by-case basis.

Source: social.technech.microsoft.com

What is the optimal way to compare dates in Microsoft SQL server?

Converting to a DATE or using an open-ended date range in any case will yield the best performance. FYI, convert to date using an index are the best performers. More testing a different techniques in article: What is the most efficient way to trim time from datetime? Posted by Aaron Bertrand

From that article:

DECLARE @dateVar datetime = '19700204';

-- Quickest when there is an index on t.[DateColumn], 
-- because CONVERT can still use the index.
SELECT t.[DateColumn]
FROM MyTable t
WHERE = CONVERT(DATE, t.[DateColumn]) = CONVERT(DATE, @dateVar);

-- Quicker when there is no index on t.[DateColumn]
DECLARE @dateEnd datetime = DATEADD(DAY, 1, @dateVar);
SELECT t.[DateColumn] 
FROM MyTable t
WHERE t.[DateColumn] >= @dateVar AND 
      t.[DateColumn] < @dateEnd;

Also from that article: using BETWEEN, DATEDIFF or CONVERT(CHAR(8)... are all slower.

Amazon S3 and Cloudfront cache, how to clear cache or synchronize their cache

If you're looking for a minimal solution that invalidates the cache, this edited version of Dr Manhattan's solution should be sufficient. Note that I'm specifying the root / directory to indicate I want the whole site refreshed.

export AWS_ACCESS_KEY_ID=<Key>
export AWS_SECRET_ACCESS_KEY=<Secret>
export AWS_DEFAULT_REGION=eu-west-1

echo "Invalidating cloudfrond distribution to get fresh cache"
aws cloudfront create-invalidation --distribution-id=<distributionId> --paths / --profile=<awsprofile>

Region Codes can be found here

You'll also need to create a profile using the aws cli. Use the aws configure --profile option. Below is an example snippet from Amazon.

$ aws configure --profile user2
AWS Access Key ID [None]: AKIAI44QH8DHBEXAMPLE
AWS Secret Access Key [None]: je7MtGbClwBF/2Zp9Utk/h3yCo8nvbEXAMPLEKEY
Default region name [None]: us-east-1
Default output format [None]: text

Multiple selector chaining in jQuery?

like:

$('#Create .myClass, #Edit .myClass').plugin({ 
    options: here
});

You can specify any number of selectors to combine into a single result. This multiple expression combinator is an efficient way to select disparate elements. The order of the DOM elements in the returned jQuery object may not be identical, as they will be in document order. An alternative to this combinator is the .add() method.

Html.HiddenFor value property not getting set

A simple answer is to use @Html.TextboxFor but place it in a div that is hidden with style. Example: In View:

<div style="display:none"> @Html.TextboxFor(x=>x.CRN) </div>

Retrieving a Foreign Key value with django-rest-framework serializers

this worked fine for me:

class ItemSerializer(serializers.ModelSerializer):
    category_name = serializers.ReadOnlyField(source='category.name')
    class Meta:
        model = Item
        fields = "__all__"

How to update an "array of objects" with Firestore?

We can use arrayUnion({}) method to achive this.

Try this:

collectionRef.doc(ID).update({
    sharedWith: admin.firestore.FieldValue.arrayUnion({
       who: "[email protected]",
       when: new Date()
    })
});

Documentation can find here: https://firebase.google.com/docs/firestore/manage-data/add-data#update_elements_in_an_array

How to embed a PDF viewer in a page?

using bootstrap you can have a responsive and mobile first embeded file.

<div class="embed-responsive embed-responsive-16by9">
  <iframe class="embed-responsive-item" src="address of your file" allowfullscreen></iframe>
</div>

Aspect ratios can be customized with modifier classes.
<!-- 21:9 aspect ratio -->
<div class="embed-responsive embed-responsive-21by9">
  <iframe class="embed-responsive-item" src="..."></iframe>
</div>

<!-- 16:9 aspect ratio -->
<div class="embed-responsive embed-responsive-16by9">
  <iframe class="embed-responsive-item" src="..."></iframe>
</div>

<!-- 4:3 aspect ratio -->
<div class="embed-responsive embed-responsive-4by3">
  <iframe class="embed-responsive-item" src="..."></iframe>
</div>

<!-- 1:1 aspect ratio -->
<div class="embed-responsive embed-responsive-1by1">
  <iframe class="embed-responsive-item" src="..."></iframe>
</div>

How to use a BackgroundWorker?

I know this is a bit old, but in case another beginner is going through this, I'll share some code that covers a bit more of the basic operations, here is another example that also includes the option to cancel the process and also report to the user the status of the process. I'm going to add on top of the code given by Alex Aza in the solution above

public Form1()
{
    InitializeComponent();

    backgroundWorker1.DoWork += backgroundWorker1_DoWork;
    backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
    backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;  //Tell the user how the process went
    backgroundWorker1.WorkerReportsProgress = true;
    backgroundWorker1.WorkerSupportsCancellation = true; //Allow for the process to be cancelled
}

//Start Process
private void button1_Click(object sender, EventArgs e)
{
    backgroundWorker1.RunWorkerAsync();
}

//Cancel Process
private void button2_Click(object sender, EventArgs e)
{
    //Check if background worker is doing anything and send a cancellation if it is
    if (backgroundWorker1.IsBusy)
    {
        backgroundWorker1.CancelAsync();
    }

}

private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
    for (int i = 0; i < 100; i++)
    {
        Thread.Sleep(1000);
        backgroundWorker1.ReportProgress(i);

        //Check if there is a request to cancel the process
        if (backgroundWorker1.CancellationPending)
        {
            e.Cancel = true;
            backgroundWorker1.ReportProgress(0);
            return;
        }
    }
    //If the process exits the loop, ensure that progress is set to 100%
    //Remember in the loop we set i < 100 so in theory the process will complete at 99%
    backgroundWorker1.ReportProgress(100);
}

private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
    progressBar1.Value = e.ProgressPercentage;
}

private void backgroundWorker1_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
    if (e.Cancelled)
    {
         lblStatus.Text = "Process was cancelled";
    }
    else if (e.Error != null)
    {
         lblStatus.Text = "There was an error running the process. The thread aborted";
    }
    else
    {
       lblStatus.Text = "Process was completed";
    }
}

How can I get the list of files in a directory using C or C++?

you can get all direct of files in your root directory by using std::experimental:: filesystem::directory_iterator(). Then, read the name of these pathfiles.

#include <iostream>
#include <filesystem>
#include <string>
#include <direct.h>
using namespace std;
namespace fs = std::experimental::filesystem;
void ShowListFile(string path)
{
for(auto &p: fs::directory_iterator(path))  /*get directory */
     cout<<p.path().filename()<<endl;   // get file name
}

int main() {

ShowListFile("C:/Users/dell/Pictures/Camera Roll/");
getchar();
return 0;
}

Creating a timer in python

Your code's perfect except that you must do the following replacement:

minutes += 1 #instead of mins = minutes + 1

or

minutes = minutes + 1 #instead of mins = minutes + 1

but here's another solution to this problem:

def wait(time_in_seconds):
    time.sleep(time_in_seconds) #here it would be 1200 seconds (20 mins)

Downloading folders from aws s3, cp or sync?

In case you need to use another profile, especially cross account. you need to add the profile in the config file

[profile profileName]
region = us-east-1
role_arn = arn:aws:iam::XXX:role/XXXX
source_profile = default

and then if you are accessing only a single file

aws s3 cp s3://crossAccountBucket/dir localdir --profile profileName

Integrating MySQL with Python in Windows

If you are looking for Python 3.2 this seems the best solution I found so far

Source: http://wiki.python.org/moin/MySQL

Map enum in JPA with fixed values?

This is now possible with JPA 2.1:

@Column(name = "RIGHT")
@Enumerated(EnumType.STRING)
private Right right;

Further details:

Which is better: <script type="text/javascript">...</script> or <script>...</script>

With the latest Firefox, I must use:

<script type="text/javascript">...</script>

Or else the script may not run properly.

What is the difference between SQL Server 2012 Express versions?

Scroll down on that page and you'll see:

Express with Tools (with LocalDB) Includes the database engine and SQL Server Management Studio Express)
This package contains everything needed to install and configure SQL Server as a database server. Choose either LocalDB or Express depending on your needs above.

That's the SQLEXPRWT_x64_ENU.exe download.... (WT = with tools)


Express with Advanced Services (contains the database engine, Express Tools, Reporting Services, and Full Text Search)
This package contains all the components of SQL Express. This is a larger download than “with Tools,” as it also includes both Full Text Search and Reporting Services.

That's the SQLEXPRADV_x64_ENU.exe download ... (ADV = Advanced Services)


The SQLEXPR_x64_ENU.exe file is just the database engine - no tools, no Reporting Services, no fulltext-search - just barebones engine.

CSS transition effect makes image blurry / moves image 1px, in Chrome?

Just found another reason why an element goes blurry when being transformed. I was using transform: translate3d(-5.5px, -18px, 0); to re-position an element once it had been loaded in, however that element became blurry.

I tried all the suggestions above but it turned out that it was due to me using a decimal value for one of the translate values. Whole numbers don't cause the blur, and the further away I went from the whole number the worse the blur became.

i.e. 5.5px blurs the element the most, 5.1px the least.

Just thought I'd chuck this here in case it helps anybody.

Tricks to manage the available memory in an R session

I quite like the improved objects function developed by Dirk. Much of the time though, a more basic output with the object name and size is sufficient for me. Here's a simpler function with a similar objective. Memory use can be ordered alphabetically or by size, can be limited to a certain number of objects, and can be ordered ascending or descending. Also, I often work with data that are 1GB+, so the function changes units accordingly.

showMemoryUse <- function(sort="size", decreasing=FALSE, limit) {

  objectList <- ls(parent.frame())

  oneKB <- 1024
  oneMB <- 1048576
  oneGB <- 1073741824

  memoryUse <- sapply(objectList, function(x) as.numeric(object.size(eval(parse(text=x)))))

  memListing <- sapply(memoryUse, function(size) {
        if (size >= oneGB) return(paste(round(size/oneGB,2), "GB"))
        else if (size >= oneMB) return(paste(round(size/oneMB,2), "MB"))
        else if (size >= oneKB) return(paste(round(size/oneKB,2), "kB"))
        else return(paste(size, "bytes"))
      })

  memListing <- data.frame(objectName=names(memListing),memorySize=memListing,row.names=NULL)

  if (sort=="alphabetical") memListing <- memListing[order(memListing$objectName,decreasing=decreasing),] 
  else memListing <- memListing[order(memoryUse,decreasing=decreasing),] #will run if sort not specified or "size"

  if(!missing(limit)) memListing <- memListing[1:limit,]

  print(memListing, row.names=FALSE)
  return(invisible(memListing))
}

And here is some example output:

> showMemoryUse(decreasing=TRUE, limit=5)
      objectName memorySize
       coherData  713.75 MB
 spec.pgram_mine  149.63 kB
       stoch.reg  145.88 kB
      describeBy    82.5 kB
      lmBandpass   68.41 kB

How to show PIL Image in ipython notebook

You can open an image using the Image class from the package PIL and display it with plt.imshow directly.

# First import libraries.
from PIL import Image
import matplotlib.pyplot as plt

# The folliwing line is useful in Jupyter notebook
%matplotlib inline

# Open your file image using the path
img = Image.open(<path_to_image>)

# Since plt knows how to handle instance of the Image class, just input your loaded image to imshow method
plt.imshow(img)

How to sort an array in descending order in Ruby

Just a quick thing, that denotes the intent of descending order.

descending = -1
a.sort_by { |h| h[:bar] * descending }

(Will think of a better way in the mean time) ;)


a.sort_by { |h| h[:bar] }.reverse!

Using malloc for allocation of multi-dimensional arrays with different row lengths

2-D Array Dynamic Memory Allocation

int **a,i;

// for any number of rows & columns this will work
a = (int **)malloc(rows*sizeof(int *));
for(i=0;i<rows;i++)
    *(a+i) = (int *)malloc(cols*sizeof(int));