Programs & Examples On #Msitransform

error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’

12 is a compile-time constant which can not be changed unlike the data referenced by int&. What you can do is

const int& z = 12;

Select multiple elements from a list

mylist[c(5,7,9)] should do it.

You want the sublists returned as sublists of the result list; you don't use [[]] (or rather, the function is [[) for that -- as Dason mentions in comments, [[ grabs the element.

What's the best way to use R scripts on the command line (terminal)?

You might want to use python's rpy2 module. However, the "right" way to do this is with R CMD BATCH. You can modify this to write to STDOUT, but the default is to write to a .Rout file. See example below:

[ramanujan:~]$cat foo.R
print(rnorm(10))
[ramanujan:~]$R CMD BATCH foo.R
[ramanujan:~]$cat foo.Rout

R version 2.7.2 (2008-08-25)
Copyright (C) 2008 The R Foundation for Statistical Computing
ISBN 3-900051-07-0

R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.

R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.

Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.

[Previously saved workspace restored]


 ~/.Rprofile loaded.
Welcome at  Fri Apr 17 13:33:17 2009
> print(rnorm(10))
 [1]  1.5891276  1.1219071 -0.6110963  0.1579430 -0.3104579  1.0072677 -0.1303165  0.6998849  1.9918643 -1.2390156
>

Goodbye at  Fri Apr 17 13:33:17 2009
> proc.time()
   user  system elapsed
  0.614   0.050   0.721

Note: you'll want to try out the --vanilla and other options to remove all the startup cruft.

Anybody knows any knowledge base open source?

I heard of RTM (The RT FAQ Manager). Never used it, however.

How to force reloading a page when using browser back button?

Just use jquery :

jQuery( document ).ready(function( $ ) {

   //Use this inside your document ready jQuery 
   $(window).on('popstate', function() {
      location.reload(true);
   });

});

The above will work 100% when back or forward button has been clicked using ajax as well.

if it doesn't, there must be a misconfiguration in a different part of the script.

For example it might not reload if something like one of the example in the previous post is used window.history.pushState('', null, './');

so when you do use history.pushState(); make sure you use it properly.

Suggestion in most cases you will just need:

history.pushState(url, '', url); 

No window.history... and make sure url is defined.

Hope that helps..

Why should the static field be accessed in a static way?

Because when you access a static field, you should do so on the class (or in this case the enum). As in

MyUnits.MILLISECONDS;

Not on an instance as in

m.MILLISECONDS;

Edit To address the question of why: In Java, when you declare something as static, you are saying that it is a member of the class, not the object (hence why there is only one). Therefore it doesn't make sense to access it on the object, because that particular data member is associated with the class.

How to get device make and model on iOS?

A category for going getting away from the NSString description

In general, it is desirable to avoid arbitrary string comparisons throughout your code. It is better to update the strings in one place and hide the magic string from your app. I provide a category on UIDevice for that purpose.

For my specific needs I need to know which device I am using without the need to know specifics about networking capability that can be easily retrieved in other ways. So you will find a coarser grained enum than the ever growing list of devices.

Updating is a matter of adding the device to the enum and the lookup table.

UIDevice+NTNUExtensions.h

typedef NS_ENUM(NSUInteger, NTNUDeviceType) {
    DeviceAppleUnknown,
    DeviceAppleSimulator,
    DeviceAppleiPhone,
    DeviceAppleiPhone3G,
    DeviceAppleiPhone3GS,
    DeviceAppleiPhone4,
    DeviceAppleiPhone4S,
    DeviceAppleiPhone5,
    DeviceAppleiPhone5C,
    DeviceAppleiPhone5S,
    DeviceAppleiPhone6,
    DeviceAppleiPhone6_Plus,
    DeviceAppleiPhone6S,
    DeviceAppleiPhone6S_Plus,
    DeviceAppleiPhoneSE,
    DeviceAppleiPhone7,
    DeviceAppleiPhone7_Plus,
    DeviceAppleiPodTouch,
    DeviceAppleiPodTouch2G,
    DeviceAppleiPodTouch3G,
    DeviceAppleiPodTouch4G,
    DeviceAppleiPad,
    DeviceAppleiPad2,
    DeviceAppleiPad3G,
    DeviceAppleiPad4G,
    DeviceAppleiPad5G_Air,
    DeviceAppleiPadMini,
    DeviceAppleiPadMini2G,
    DeviceAppleiPadPro12,
    DeviceAppleiPadPro9
};



@interface UIDevice (NTNUExtensions)

- (NSString *)ntnu_deviceDescription;
- (NTNUDeviceType)ntnu_deviceType;

@end

UIDevice+NTNUExtensions.m

#import <sys/utsname.h>
#import "UIDevice+NTNUExtensions.h"

@implementation UIDevice (NTNUExtensions)

- (NSString *)ntnu_deviceDescription
{
    struct utsname systemInfo;
    uname(&systemInfo);

    return [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
}

- (NTNUDeviceType)ntnu_deviceType
{
    NSNumber *deviceType = [[self ntnu_deviceTypeLookupTable] objectForKey:[self ntnu_deviceDescription]];
    return [deviceType unsignedIntegerValue];
}

- (NSDictionary *)ntnu_deviceTypeLookupTable
{
    return @{
             @"i386": @(DeviceAppleSimulator),
             @"x86_64": @(DeviceAppleSimulator),
             @"iPod1,1": @(DeviceAppleiPodTouch),
             @"iPod2,1": @(DeviceAppleiPodTouch2G),
             @"iPod3,1": @(DeviceAppleiPodTouch3G),
             @"iPod4,1": @(DeviceAppleiPodTouch4G),
             @"iPhone1,1": @(DeviceAppleiPhone),
             @"iPhone1,2": @(DeviceAppleiPhone3G),
             @"iPhone2,1": @(DeviceAppleiPhone3GS),
             @"iPhone3,1": @(DeviceAppleiPhone4),
             @"iPhone3,3": @(DeviceAppleiPhone4),
             @"iPhone4,1": @(DeviceAppleiPhone4S),
             @"iPhone5,1": @(DeviceAppleiPhone5),
             @"iPhone5,2": @(DeviceAppleiPhone5),
             @"iPhone5,3": @(DeviceAppleiPhone5C),
             @"iPhone5,4": @(DeviceAppleiPhone5C),
             @"iPhone6,1": @(DeviceAppleiPhone5S),
             @"iPhone6,2": @(DeviceAppleiPhone5S),
             @"iPhone7,1": @(DeviceAppleiPhone6_Plus),
             @"iPhone7,2": @(DeviceAppleiPhone6),
             @"iPhone8,1" :@(DeviceAppleiPhone6S),
             @"iPhone8,2" :@(DeviceAppleiPhone6S_Plus),
             @"iPhone8,4" :@(DeviceAppleiPhoneSE),
             @"iPhone9,1" :@(DeviceAppleiPhone7),
             @"iPhone9,3" :@(DeviceAppleiPhone7),
             @"iPhone9,2" :@(DeviceAppleiPhone7_Plus),
             @"iPhone9,4" :@(DeviceAppleiPhone7_Plus),
             @"iPad1,1": @(DeviceAppleiPad),
             @"iPad2,1": @(DeviceAppleiPad2),
             @"iPad3,1": @(DeviceAppleiPad3G),
             @"iPad3,4": @(DeviceAppleiPad4G),
             @"iPad2,5": @(DeviceAppleiPadMini),
             @"iPad4,1": @(DeviceAppleiPad5G_Air),
             @"iPad4,2": @(DeviceAppleiPad5G_Air),
             @"iPad4,4": @(DeviceAppleiPadMini2G),
             @"iPad4,5": @(DeviceAppleiPadMini2G),
             @"iPad4,7":@(DeviceAppleiPadMini),
             @"iPad6,7":@(DeviceAppleiPadPro12),
             @"iPad6,8":@(DeviceAppleiPadPro12),
             @"iPad6,3":@(DeviceAppleiPadPro9),
             @"iPad6,4":@(DeviceAppleiPadPro9)
             };
}

@end

File Upload using AngularJS

I tried all alternatives that @Anoyz (Correct answer) gives... and the best solution is https://github.com/danialfarid/angular-file-upload

Some Features:

  • Progress
  • Multifiles
  • Fields
  • Old browsers (IE8-9)

It's work fine for me. You just have to pay attention to instructions.

In server-side i use NodeJs, Express 4 and Multer middleware to manage multipart request.

Maven Run Project

clean package exec:java -P Class_Containing_Main_Method command is also an option if you have only one Main method(PSVM) in the project, with the following Maven Setup.

Don't forget to mention the class in the <properties></properties> section of pom.xml :

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.main.class>com.test.service.MainTester</java.main.class>
</properties>

<plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>exec-maven-plugin</artifactId>
        <version>1.2.1</version>
        <configuration>
           <mainClass>${java.main.class}</mainClass>
        </configuration>
</plugin>

STS Run Configuration along with above Maven Setup:

enter image description here

What does "select count(1) from table_name" on any database tables mean?

Here is a link that will help answer your questions. In short:

count(*) is the correct way to write it and count(1) is OPTIMIZED TO BE count(*) internally -- since

a) count the rows where 1 is not null is less efficient than
b) count the rows

multiple packages in context:component-scan, spring config

<context:component-scan base-package="x.y.z"/>

will work since the rest of the packages are sub packages of "x.y.z". Thus, you dont need to mention each package individually.

Python Database connection Close

You can wrap the whole connection in a context manager, like the following:

from contextlib import contextmanager
import pyodbc
import sys

@contextmanager
def open_db_connection(connection_string, commit=False):
    connection = pyodbc.connect(connection_string)
    cursor = connection.cursor()
    try:
        yield cursor
    except pyodbc.DatabaseError as err:
        error, = err.args
        sys.stderr.write(error.message)
        cursor.execute("ROLLBACK")
        raise err
    else:
        if commit:
            cursor.execute("COMMIT")
        else:
            cursor.execute("ROLLBACK")
    finally:
        connection.close()

Then do something like this where ever you need a database connection:

with open_db_connection("...") as cursor:
    # Your code here

The connection will close when you leave the with block. This will also rollback the transaction if an exception occurs or if you didn't open the block using with open_db_connection("...", commit=True).

how to sort an ArrayList in ascending order using Collections and Comparator

This might work?

Comparator mycomparator = 
    Collections.reverseOrder(Collections.reverseOrder());

How to make Java honor the DNS Caching Timeout?

To expand on Byron's answer, I believe you need to edit the file java.security in the %JRE_HOME%\lib\security directory to effect this change.

Here is the relevant section:

#
# The Java-level namelookup cache policy for successful lookups:
#
# any negative value: caching forever
# any positive value: the number of seconds to cache an address for
# zero: do not cache
#
# default value is forever (FOREVER). For security reasons, this
# caching is made forever when a security manager is set. When a security
# manager is not set, the default behavior is to cache for 30 seconds.
#
# NOTE: setting this to anything other than the default value can have
#       serious security implications. Do not set it unless 
#       you are sure you are not exposed to DNS spoofing attack.
#
#networkaddress.cache.ttl=-1 

Documentation on the java.security file here.

How can I Insert data into SQL Server using VBNet

Imports System.Data

Imports System.Data.SqlClient

Public Class Form2

Dim myconnection As SqlConnection

Dim mycommand As SqlCommand

Dim dr As SqlDataReader

Dim dr1 As SqlDataReader

Dim ra As Integer


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click


    myconnection = New SqlConnection("server=localhost;uid=root;pwd=;database=simple")

    'you need to provide password for sql server

    myconnection.Open()

    mycommand = New SqlCommand("insert into tbl_cus([name],[class],[phone],[address]) values ('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "')", myconnection)

    mycommand.ExecuteNonQuery()

    MessageBox.Show("New Row Inserted" & ra)

    myconnection.Close()

End Sub

End Class

How do I append text to a file?

How about:

echo "hello" >> <filename>

Using the >> operator will append data at the end of the file, while using the > will overwrite the contents of the file if already existing.

You could also use printf in the same way:

printf "hello" >> <filename>

Note that it can be dangerous to use the above. For instance if you already have a file and you need to append data to the end of the file and you forget to add the last > all data in the file will be destroyed. You can change this behavior by setting the noclobber variable in your .bashrc:

set -o noclobber

Now when you try to do echo "hello" > file.txt you will get a warning saying cannot overwrite existing file.

To force writing to the file you must now use the special syntax:

echo "hello" >| <filename>

You should also know that by default echo adds a trailing new-line character which can be suppressed by using the -n flag:

echo -n "hello" >> <filename>

References

How to sort a collection by date in MongoDB?

This worked for me:

collection.find({}, {"sort" : [['datefield', 'asc']]}, function (err, docs) { ... });

Using Node.js, Express.js, and Monk

Authentication plugin 'caching_sha2_password' is not supported

I uninstalled mysql-connector (I installed following tutorial on w3schools tutorial) and installed mysql-connector-python instead. It worked.

Disable nginx cache for JavaScript files

I know this question is a bit old but i would suggest to use some cachebraking hash in the url of the javascript. This works perfectly in production as well as during development because you can have both infinite cache times and intant updates when changes occur.

Lets assume you have a javascript file /js/script.min.js, but in the referencing html/php file you do not use the actual path but:

<script src="/js/script.<?php echo md5(filemtime('/js/script.min.js')); ?>.min.js"></script>

So everytime the file is changed, the browser gets a different url, which in turn means it cannot be cached, be it locally or on any proxy inbetween.

To make this work you need nginx to rewrite any request to /js/script.[0-9a-f]{32}.min.js to the original filename. In my case i use the following directive (for css also):

location ~* \.(css|js)$ {
                expires max;
                add_header Pragma public;
                etag off;
                add_header Cache-Control "public";
                add_header Last-Modified "";
                rewrite  "^/(.*)\/(style|script)\.min\.([\d\w]{32})\.(js|css)$" /$1/$2.min.$4 break;
        }

I would guess that the filemtime call does not even require disk access on the server as it should be in linux's file cache. If you have doubts or static html files you can also use a fixed random value (or incremental or content hash) that is updated when your javascript / css preprocessor has finished or let one of your git hooks change it.

In theory you could also use a cachebreaker as a dummy parameter (like /js/script.min.js?cachebreak=0123456789abcfef), but then the file is not cached at least by some proxies because of the "?".

Why "no projects found to import"?

Reason : your ID is not able to find the .project file. This happens in git commit where many time people don't push .project file

Solution : If you have maven install then use following stapes

  1. mvn eclipse:clean
  2. mvn eclipse:eclipse

Enjoy!

How to store file name in database, with other info while uploading image to server using PHP?

Here is the answer for those of you looking like I did all over the web trying to find out how to do this task. Uploading a photo to a server with the file name stored in a mysql database and other form data you want in your Database. Please let me know if it helped.

Firstly the form you need:

    <form method="post" action="addMember.php" enctype="multipart/form-data">
    <p>
              Please Enter the Band Members Name.
            </p>
            <p>
              Band Member or Affiliates Name:
            </p>
            <input type="text" name="nameMember"/>
            <p>
              Please Enter the Band Members Position. Example:Drums.
            </p>
            <p>
              Band Position:
            </p>
            <input type="text" name="bandMember"/>
            <p>
              Please Upload a Photo of the Member in gif or jpeg format. The file name should be named after the Members name. If the same file name is uploaded twice it will be overwritten! Maxium size of File is 35kb.
            </p>
            <p>
              Photo:
            </p>
            <input type="hidden" name="size" value="350000">
            <input type="file" name="photo"> 
            <p>
              Please Enter any other information about the band member here.
            </p>
            <p>
              Other Member Information:
            </p>
<textarea rows="10" cols="35" name="aboutMember">
</textarea>
            <p>
              Please Enter any other Bands the Member has been in.
            </p>
            <p>
              Other Bands:
            </p>
            <input type="text" name="otherBands" size=30 />
            <br/>
            <br/>
            <input TYPE="submit" name="upload" title="Add data to the Database" value="Add Member"/>
          </form>

Then this code processes you data from the form:

   <?php

// This is the directory where images will be saved
$target = "your directory";
$target = $target . basename( $_FILES['photo']['name']);

// This gets all the other information from the form
$name=$_POST['nameMember'];
$bandMember=$_POST['bandMember'];
$pic=($_FILES['photo']['name']);
$about=$_POST['aboutMember'];
$bands=$_POST['otherBands'];


// Connects to your Database
mysqli_connect("yourhost", "username", "password") or die(mysqli_error()) ;
mysqli_select_db("dbName") or die(mysqli_error()) ;

// Writes the information to the database
mysqli_query("INSERT INTO tableName (nameMember,bandMember,photo,aboutMember,otherBands)
VALUES ('$name', '$bandMember', '$pic', '$about', '$bands')") ;

// Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{

// Tells you if its all ok
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory";
}
else {

// Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?> 

Code edited from www.about.com

How to merge multiple dicts with same key or different key?

def merge(d1, d2, merge):
    result = dict(d1)
    for k,v in d2.iteritems():
        if k in result:
            result[k] = merge(result[k], v)
        else:
            result[k] = v
    return result

d1 = {'a': 1, 'b': 2}
d2 = {'a': 1, 'b': 3, 'c': 2}
print merge(d1, d2, lambda x, y:(x,y))

{'a': (1, 1), 'c': 2, 'b': (2, 3)}

Align items in a stack panel?

for windows 10 use relativePanel instead of stack panel, and use

relativepanel.alignrightwithpanel="true"

for the contained elements.

Exclude Blank and NA in R

A good idea is to set all of the "" (blank cells) to NA before any further analysis.

If you are reading your input from a file, it is a good choice to cast all "" to NAs:

foo <- read.table(file="Your_file.txt", na.strings=c("", "NA"), sep="\t") # if your file is tab delimited

If you have already your table loaded, you can act as follows:

foo[foo==""] <- NA

Then to keep only rows with no NA you may just use na.omit():

foo <- na.omit(foo)

Or to keep columns with no NA:

foo <- foo[, colSums(is.na(foo)) == 0] 

Simple way to query connected USB devices info in Python?

When I run your code, I get the following output for example.

<usb.Device object at 0xef38c0>
Device: 001
  idVendor: 7531 (0x1d6b)
  idProduct: 1 (0x0001)
Manufacturer: 3
Serial: 1
Product: 2

Noteworthy are that a) I have usb.Device objects whereas you have usb.legacy.Device objects, and b) I have device filenames.

Each usb.Bus has a dirname field and each usb.Device has the filename. As you can see, the filename is something like 001, and so is the dirname. You can combine these to get the bus file. For dirname=001 and filname=001, it should be something like /dev/bus/usb/001/001.

You should first, though figure out what this "usb.legacy" situation is. I'm running the latest version and I don't even have a legacy sub-module.

Finally, you should use the idVendor and idProduct fields to uniquely identify the device when it's plugged in.

'invalid value encountered in double_scalars' warning, possibly numpy

Whenever you are working with csv imports, try to use df.dropna() to avoid all such warnings or errors.

How to process POST data in Node.js?

You can use the express middleware, which now has body-parser built into it. This means all you need to do is the following:

import express from 'express'

const app = express()

app.use(express.json())

app.post('/thing', (req, res) => {
  console.log(req.body) // <-- this will access the body of the post
  res.sendStatus(200)
})

That code example is ES6 with Express 4.16.x

How to read if a checkbox is checked in PHP?

You can check the corresponding value as being set and non-empty in either the $_POST or $_GET array depending on your form's action.

i.e.: With a POST form using a name of "test" (i.e.: <input type="checkbox" name="test"> , you'd use:

if(isset($_POST['test']) {
   // The checkbox was enabled...

}

Cloning an Object in Node.js

Looking for a true clone option, I stumbled across ridcully's link to here:

http://my.opera.com/GreyWyvern/blog/show.dml/1725165

I modified the solution on that page so that the function attached to the Object prototype is not enumerable. Here is my result:

Object.defineProperty(Object.prototype, 'clone', {
    enumerable: false,
    value: function() {
        var newObj = (this instanceof Array) ? [] : {};
        for (i in this) {
        if (i == 'clone') continue;
            if (this[i] && typeof this[i] == "object") {
                newObj[i] = this[i].clone();
            } else newObj[i] = this[i]
        } return newObj;
    }
});

Hopefully this helps someone else as well. Note that there are some caveats... particularly with properties named "clone". This works well for me. I don't take any credit for writing it. Again, I only changed how it was being defined.

Create timestamp variable in bash script

If you want to get unix timestamp, then you need to use:

timestamp=$(date +%s)

%T will give you just the time; same as %H:%M:%S (via http://www.cyberciti.biz/faq/linux-unix-formatting-dates-for-display/)

How do I remove blank pages coming between two chapters in Appendix?

it is very easy:

add \documentclass[oneside]{book} and youre fine ;)

Finding CN of users in Active Directory

You could try my Beavertail ADSI browser - it should show you the current AD tree, and from it, you should be able to figure out the path and all.

alt text

Or if you're on .NET 3.5, using the System.DirectoryServices.AccountManagement namespace, you could also do it programmatically:

PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

This would create a basic, default domain context and you should be able to peek at its properties and find a lot of stuff from it.

Or:

UserPrincipal myself = UserPrincipal.Current;

This will give you a UserPrincipal object for yourself, again, with a ton of properties to inspect. I'm not 100% sure what you're looking for - but you most likely will be able to find it on the context or the user principal somewhere!

Why does 'git commit' not save my changes?

Maybe an obvious thing, but...

If you have problem with the index, use git-gui. You get a very good view how the index (staging area) actually works.

Another source of information that helped me understand the index was Scott Chacons "Getting Git" page 259 and forward.

I started off using the command line because most documentation only showed that...

I think git-gui and gitk actually make me work faster, and I got rid of bad habits like "git pull" for example... Now I always fetch first... See what the new changes really are before I merge.

Achieving white opacity effect in html/css

If you can't use rgba due to browser support, and you don't want to include a semi-transparent white PNG, you will have to create two positioned elements. One for the white box, with opacity, and one for the overlaid text, solid.

_x000D_
_x000D_
body { background: red; }_x000D_
_x000D_
.box { position: relative; z-index: 1; }_x000D_
.box .back {_x000D_
    position: absolute; z-index: 1;_x000D_
    top: 0; left: 0; width: 100%; height: 100%;_x000D_
    background: white; opacity: 0.75;_x000D_
}_x000D_
.box .text { position: relative; z-index: 2; }_x000D_
_x000D_
body.browser-ie8 .box .back { filter: alpha(opacity=75); }
_x000D_
<!--[if lt IE 9]><body class="browser-ie8"><![endif]-->_x000D_
<!--[if gte IE 9]><!--><body><!--<![endif]-->_x000D_
    <div class="box">_x000D_
        <div class="back"></div>_x000D_
        <div class="text">_x000D_
            Lorem ipsum dolor sit amet blah blah boogley woogley oo._x000D_
        </div>_x000D_
    </div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

How to change border color of textarea on :focus

Try out this probably it will work

input{
outline-color: #fff //your color
outline-style: none // it depend on you 
}

MySQL: update a field only if condition is met

Try this:

UPDATE test
SET
   field = 1
WHERE id = 123 and condition

Intro to GPU programming

Take a look at the ATI Stream Computing SDK. It is based on BrookGPU developed at Stanford.

In the future all GPU work will be standardized using OpenCL. It's an Apple-sponsored initiative that will be graphics card vendor neutral.

SQL Server Escape an Underscore

None of these worked for me in SSIS v18.0, so I would up doing something like this:

WHERE CHARINDEX('_', thingyoursearching) < 1

..where I am trying to ignore strings with an underscore in them. If you want to find things that have an underscore, just flip it around:

WHERE CHARINDEX('_', thingyoursearching) > 0

How to make an AlertDialog in Flutter?

Another easy option to show Dialog is to use stacked_services package

 _dialogService.showDialog(
      title: "Title",
      description: "Dialog message Tex",
         );
     });

Deploying just HTML, CSS webpage to Tomcat

There is no real need to create a war to run it from Tomcat. You can follow these steps

  1. Create a folder in webapps folder e.g. MyApp

  2. Put your html and css in that folder and name the html file, which you want to be the starting page for your application, index.html

  3. Start tomcat and point your browser to url "http://localhost:8080/MyApp". Your index.html page will pop up in the browser

Seedable JavaScript random number generator

If you don't need the seeding capability just use Math.random() and build helper functions around it (eg. randRange(start, end)).

I'm not sure what RNG you're using, but it's best to know and document it so you're aware of its characteristics and limitations.

Like Starkii said, Mersenne Twister is a good PRNG, but it isn't easy to implement. If you want to do it yourself try implementing a LCG - it's very easy, has decent randomness qualities (not as good as Mersenne Twister), and you can use some of the popular constants.

EDIT: consider the great options at this answer for short seedable RNG implementations, including an LCG option.

_x000D_
_x000D_
function RNG(seed) {_x000D_
  // LCG using GCC's constants_x000D_
  this.m = 0x80000000; // 2**31;_x000D_
  this.a = 1103515245;_x000D_
  this.c = 12345;_x000D_
_x000D_
  this.state = seed ? seed : Math.floor(Math.random() * (this.m - 1));_x000D_
}_x000D_
RNG.prototype.nextInt = function() {_x000D_
  this.state = (this.a * this.state + this.c) % this.m;_x000D_
  return this.state;_x000D_
}_x000D_
RNG.prototype.nextFloat = function() {_x000D_
  // returns in range [0,1]_x000D_
  return this.nextInt() / (this.m - 1);_x000D_
}_x000D_
RNG.prototype.nextRange = function(start, end) {_x000D_
  // returns in range [start, end): including start, excluding end_x000D_
  // can't modulu nextInt because of weak randomness in lower bits_x000D_
  var rangeSize = end - start;_x000D_
  var randomUnder1 = this.nextInt() / this.m;_x000D_
  return start + Math.floor(randomUnder1 * rangeSize);_x000D_
}_x000D_
RNG.prototype.choice = function(array) {_x000D_
  return array[this.nextRange(0, array.length)];_x000D_
}_x000D_
_x000D_
var rng = new RNG(20);_x000D_
for (var i = 0; i < 10; i++)_x000D_
  console.log(rng.nextRange(10, 50));_x000D_
_x000D_
var digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];_x000D_
for (var i = 0; i < 10; i++)_x000D_
  console.log(rng.choice(digits));
_x000D_
_x000D_
_x000D_

How do I kill an Activity when the Back button is pressed?

public boolean onKeyDown(int keycode, KeyEvent event) {
    if (keycode == KeyEvent.KEYCODE_BACK) {
        moveTaskToBack(true);
    }
    return super.onKeyDown(keycode, event);
}

My app closed with above code.

SSH SCP Local file to Remote in Terminal Mac Os X

Watch that your file name doesn't have : in them either. I found that I had to mv blah-07-08-17-02:69.txt no_colons.txt and then scp no-colons.txt server: then don't forget to mv back on the server. Just in case this was an issue.

Email & Phone Validation in Swift

Swift 4.2 and Xcode 10.1

//For mobile number validation
func isValidPhone(phone: String) -> Bool {

    let phoneRegex = "^((0091)|(\\+91)|0?)[6789]{1}\\d{9}$";
    let valid = NSPredicate(format: "SELF MATCHES %@", phoneRegex).evaluate(with: phone)
    return valid
}

//For email validation
func isValidEmail(candidate: String) -> Bool {

    let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
    var valid = NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluate(with: candidate)
    if valid {
        valid = !candidate.contains("..")
    }
    return valid
}

Use like this

//Button Action
@IBAction func onClickRegrBtn(_ sender: UIButton) {
    //Check net connection here
    let networkReachability = Reachability.forInternetConnection()
    let networkStatus:Int = (networkReachability?.currentReachabilityStatus())!.rawValue
    if networkStatus == NotReachable.rawValue {
        let msg = SharedClass.sharedInstance.noNetMsg
        SharedClass.sharedInstance.alert(view: self, title: "", message: msg)//Display alert message
    } else {

        let mobileTrimmedString = mobileNoTF.text?.trimmingCharacters(in: .whitespaces) //Trim white spaces

        if mobileTrimmedString != "" {
            if isValidPhone(phone: mobileTrimmedString!) == false {
                SharedClass.sharedInstance.alert(view: self, title: "", message: "Please enter valid mobile number")
            } else {
                UserDefaults.standard.set(mobileTrimmedString, forKey: "mobile") //setObject
                sendMobileNumber()//Call function...
            }

        } else {
            mobileNoTF.text = ""
            //Call alert function
            SharedClass.sharedInstance.alert(view: self, title: "", message: "Please enter mobile number")
        }
    }
}

How to print an unsigned char in C?

Declare your ch as

unsigned char ch = 212 ;

And your printf will work.

Spring RestTemplate GET with parameters

If your url is http://localhost:8080/context path?msisdn={msisdn}&email={email}

then

Map<String,Object> queryParams=new HashMap<>();
queryParams.put("msisdn",your value)
queryParams.put("email",your value)

works for resttemplate exchange method as described by you

Removing legend on charts with chart.js v2

The options object can be added to the chart when the new Chart object is created.

var chart1 = new Chart(canvas, {
    type: "pie",
    data: data,
    options: {
         legend: {
            display: false
         },
         tooltips: {
            enabled: false
         }
    }
});

How do I control how Emacs makes backup files?

The accepted answer is good, but it can be greatly improved by additionally backing up on every save and backing up versioned files.

First, basic settings as described in the accepted answer:

(setq version-control t     ;; Use version numbers for backups.
      kept-new-versions 10  ;; Number of newest versions to keep.
      kept-old-versions 0   ;; Number of oldest versions to keep.
      delete-old-versions t ;; Don't ask to delete excess backup versions.
      backup-by-copying t)  ;; Copy all files, don't rename them.

Next, also backup versioned files, which Emacs does not do by default (you don't commit on every save, right?):

(setq vc-make-backup-files t)

Finally, make a backup on each save, not just the first. We make two kinds of backups:

  1. per-session backups: once on the first save of the buffer in each Emacs session. These simulate Emac's default backup behavior.

  2. per-save backups: once on every save. Emacs does not do this by default, but it's very useful if you leave Emacs running for a long time.

The backups go in different places and Emacs creates the backup dirs automatically if they don't exist:

;; Default and per-save backups go here:
(setq backup-directory-alist '(("" . "~/.emacs.d/backup/per-save")))

(defun force-backup-of-buffer ()
  ;; Make a special "per session" backup at the first save of each
  ;; emacs session.
  (when (not buffer-backed-up)
    ;; Override the default parameters for per-session backups.
    (let ((backup-directory-alist '(("" . "~/.emacs.d/backup/per-session")))
          (kept-new-versions 3))
      (backup-buffer)))
  ;; Make a "per save" backup on each save.  The first save results in
  ;; both a per-session and a per-save backup, to keep the numbering
  ;; of per-save backups consistent.
  (let ((buffer-backed-up nil))
    (backup-buffer)))

(add-hook 'before-save-hook  'force-backup-of-buffer)

I became very interested in this topic after I wrote $< instead of $@ in my Makefile, about three hours after my previous commit :P

The above is based on an Emacs Wiki page I heavily edited.

Declaring a variable and setting its value from a SELECT query in Oracle

ORA-01422: exact fetch returns more than requested number of rows

if you don't specify the exact record by using where condition, you will get the above exception

DECLARE
     ID NUMBER;
BEGIN
     select eid into id from employee where salary=26500;
     DBMS_OUTPUT.PUT_LINE(ID);
END;

Javascript how to split newline

Good'ol javascript:

 var m = "Hello World";  
 var k = m.split(' ');  // I have used space, you can use any thing.
 for(i=0;i<k.length;i++)  
    alert(k[i]);  

Specify an SSH key for git push for a given domain

You can utilize git environment variable GIT_SSH_COMMAND. Run this in your terminal under your git repository:

GIT_SSH_COMMAND='ssh -i ~/.ssh/your_private_key' git submodule update --init

Replace ~/.ssh/your_private_key with the path of ssh private key you wanna use. And you can change the subsequent git command (in the example is git submodule update --init) to others like git pull, git fetch, etc.

How to play .mp4 video in videoview in android?

I'm not sure that is the problem but what worked for me is calling mVideoView.start(); inside the mVideoView.setOnPreparedListener event callback.

For example:

Uri uriVideo = Uri.parse(<your link here>);

MediaController mediaController = new MediaController(mContext);
mediaController.setAnchorView(mVideoView);
mVideoView.setMediaController(mediaController);
mVideoView.setVideoURI(uriVideo);
mVideoView.requestFocus();

mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener()
{
     @Override
     public void onPrepared(MediaPlayer mp)
     {
          mVideoViewPeekItem.start();
     }
});

Send email from localhost running XAMMP in PHP using GMAIL mail server

Don't forget to generate a second password for your Gmail account. You will use this new password in your code. Read this:

https://support.google.com/accounts/answer/185833

Under the section "How to generate an App password" click on "App passwords", then under "Select app" choose "Mail", select your device and click "Generate". Your second password will be printed on the screen.

Changing Locale within the app itself

This is for my comment on Andrey's answer but I cant include code in the comments.

Is you preference activity being called from you main activity? you could place this in the on resume...

@Override
protected void onResume() {
    if (!(PreferenceManager.getDefaultSharedPreferences(
            getApplicationContext()).getString("listLanguage", "en")
            .equals(langPreference))) {
        refresh();
    }
    super.onResume();
}

private void refresh() {
    finish();
    Intent myIntent = new Intent(Main.this, Main.class);
    startActivity(myIntent);
}

UITextField border color

If you use a TextField with rounded corners use this code:

    self.TextField.layer.cornerRadius=8.0f;
    self.TextField.layer.masksToBounds=YES;
    self.TextField.layer.borderColor=[[UIColor redColor]CGColor];
    self.TextField.layer.borderWidth= 1.0f;

To remove the border:

self.TextField.layer.masksToBounds=NO;
self.TextField.layer.borderColor=[[UIColor clearColor]CGColor];

How to escape strings in SQL Server using PHP?

function ms_escape_string($data) {
        if ( !isset($data) or empty($data) ) return '';
        if ( is_numeric($data) ) return $data;

        $non_displayables = array(
            '/%0[0-8bcef]/',            // url encoded 00-08, 11, 12, 14, 15
            '/%1[0-9a-f]/',             // url encoded 16-31
            '/[\x00-\x08]/',            // 00-08
            '/\x0b/',                   // 11
            '/\x0c/',                   // 12
            '/[\x0e-\x1f]/'             // 14-31
        );
        foreach ( $non_displayables as $regex )
            $data = preg_replace( $regex, '', $data );
        $data = str_replace("'", "''", $data );
        return $data;
    }

Some of the code here was ripped off from CodeIgniter. Works well and is a clean solution.

EDIT: There are plenty of issues with that code snippet above. Please don't use this without reading the comments to know what those are. Better yet, please don't use this at all. Parameterized queries are your friends: http://php.net/manual/en/pdo.prepared-statements.php

sending mail from Batch file

There are multiple methods for handling this problem.

My advice is to use the powerful Windows freeware console application SendEmail.

sendEmail.exe -f [email protected] -o message-file=body.txt -u subject message -t [email protected] -a attachment.zip -s smtp.gmail.com:446 -xu gmail.login -xp gmail.password

How can I create a simple index.html file which lists all files/directories?

There are enough valid reasons to explicitly disable automatic directory indexes in apache or other web servers. Or, for example, you might only want to include certain file types in the index. In such cases you might still want to have a statically generated index.html file for specific folders.

tree

tree is a minimalistic utility that is available on most unix-like systems (ubuntu/debian: sudo apt install tree, mac: brew install tree, windows: zip) and which can generate plain text, XML, JSON or HTML output.

Generate an HTML directory index one level deep:

tree -H '.' -L 1 --noreport --charset utf-8 > index.html

Only include specific file types that match a glob pattern, e.g. *.zip files:

tree -H '.' -L 1 --noreport --charset utf-8 -P "*.zip" > index.html

The argument to -H is what will be used as a base href, so you can pass either a relative path such as . or an absolute path from the web root, such as /files. -L 1 limits the listing to the current directory only.

Generator script with recursive traversal

I needed an index generator which I could style the way I want, and which would also include the file sizes, so ended up using this script — in addition to having customizable styling, the script can also recursively generate an index.html file in all the nested subdirectories.

Update: an updated version (python 3) of the index generation script that uses cleaner styling (inspired by caddyserver's file-server module), includes last modified times and is more responsive in mobile viewports.

PowerShell script to return members of multiple security groups

If you don't care what groups the users were in, and just want a big ol' list of users - this does the job:

$Groups = Get-ADGroup -Filter {Name -like "AB*"}

$rtn = @(); ForEach ($Group in $Groups) {
    $rtn += (Get-ADGroupMember -Identity "$($Group.Name)" -Recursive)
}

Then the results:

$rtn | ft -autosize

List directory in Go

You can try using the ReadDir function in the io/ioutil package. Per the docs:

ReadDir reads the directory named by dirname and returns a list of sorted directory entries.

The resulting slice contains os.FileInfo types, which provide the methods listed here. Here is a basic example that lists the name of everything in the current directory (folders are included but not specially marked - you can check if an item is a folder by using the IsDir() method):

package main

import (
    "fmt"
    "io/ioutil"
     "log"
)

func main() {
    files, err := ioutil.ReadDir("./")
    if err != nil {
        log.Fatal(err)
    }
 
    for _, f := range files {
            fmt.Println(f.Name())
    }
}

Jest spyOn function called

You were almost done without any changes besides how you spyOn. When you use the spy, you have two options: spyOn the App.prototype, or component component.instance().

const spy = jest.spyOn(Class.prototype, "method")

The order of attaching the spy on the class prototype and rendering (shallow rendering) your instance is important.

const spy = jest.spyOn(App.prototype, "myClickFn");
const instance = shallow(<App />);

The App.prototype bit on the first line there are what you needed to make things work. A JavaScript class doesn't have any of its methods until you instantiate it with new MyClass(), or you dip into the MyClass.prototype. For your particular question, you just needed to spy on the App.prototype method myClickFn.

jest.spyOn(component.instance(), "method")

const component = shallow(<App />);
const spy = jest.spyOn(component.instance(), "myClickFn");

This method requires a shallow/render/mount instance of a React.Component to be available. Essentially spyOn is just looking for something to hijack and shove into a jest.fn(). It could be:

A plain object:

const obj = {a: x => (true)};
const spy = jest.spyOn(obj, "a");

A class:

class Foo {
    bar() {}
}

const nope = jest.spyOn(Foo, "bar");
// THROWS ERROR. Foo has no "bar" method.
// Only an instance of Foo has "bar".
const fooSpy = jest.spyOn(Foo.prototype, "bar");
// Any call to "bar" will trigger this spy; prototype or instance

const fooInstance = new Foo();
const fooInstanceSpy = jest.spyOn(fooInstance, "bar");
// Any call fooInstance makes to "bar" will trigger this spy.

Or a React.Component instance:

const component = shallow(<App />);
/*
component.instance()
-> {myClickFn: f(), render: f(), ...etc}
*/
const spy = jest.spyOn(component.instance(), "myClickFn");

Or a React.Component.prototype:

/*
App.prototype
-> {myClickFn: f(), render: f(), ...etc}
*/
const spy = jest.spyOn(App.prototype, "myClickFn");
// Any call to "myClickFn" from any instance of App will trigger this spy.

I've used and seen both methods. When I have a beforeEach() or beforeAll() block, I might go with the first approach. If I just need a quick spy, I'll use the second. Just mind the order of attaching the spy.

EDIT: If you want to check the side effects of your myClickFn you can just invoke it in a separate test.

const app = shallow(<App />);
app.instance().myClickFn()
/*
Now assert your function does what it is supposed to do...
eg.
expect(app.state("foo")).toEqual("bar");
*/

EDIT: Here is an example of using a functional component. Keep in mind that any methods scoped within your functional component are not available for spying. You would be spying on function props passed into your functional component and testing the invocation of those. This example explores the use of jest.fn() as opposed to jest.spyOn, both of which share the mock function API. While it does not answer the original question, it still provides insight on other techniques that could suit cases indirectly related to the question.

function Component({ myClickFn, items }) {
   const handleClick = (id) => {
       return () => myClickFn(id);
   };
   return (<>
       {items.map(({id, name}) => (
           <div key={id} onClick={handleClick(id)}>{name}</div>
       ))}
   </>);
}

const props = { myClickFn: jest.fn(), items: [/*...{id, name}*/] };
const component = render(<Component {...props} />);
// Do stuff to fire a click event
expect(props.myClickFn).toHaveBeenCalledWith(/*whatever*/);

Styling the last td in a table with css

The :last-child selector should do it, but it's not supported in any version of IE.

I'm afraid you have no choice but to use a class.

Sending and Parsing JSON Objects in Android

I am surprised these have not been mentioned: but instead of using bare-bones rather manual process with json.org's little package, GSon and Jackson are much more convenient to use. So:

So you can actually bind to your own POJOs, not some half-assed tree nodes or Lists and Maps. (and at least Jackson allows binding to such things too (perhaps GSON as well, not sure), JsonNode, Map, List, if you really want these instead of 'real' objects)

EDIT 19-MAR-2014:

Another new contender is Jackson jr library: it uses same fast Streaming parser/generator as Jackson (jackson-core), but data-binding part is tiny (50kB). Functionality is more limited (no annotations, just regular Java Beans), but performance-wise should be fast, and initialization (first-call) overhead very low as well. So it just might be good choice, especially for smaller apps.

What values can I pass to the event attribute of the f:ajax tag?

The event attribute of <f:ajax> can hold at least all supported DOM events of the HTML element which is been generated by the JSF component in question. An easy way to find them all out is to check all on* attribues of the JSF input component of interest in the JSF tag library documentation and then remove the "on" prefix. For example, the <h:inputText> component which renders <input type="text"> lists the following on* attributes (of which I've already removed the "on" prefix so that it ultimately becomes the DOM event type name):

  • blur
  • change
  • click
  • dblclick
  • focus
  • keydown
  • keypress
  • keyup
  • mousedown
  • mousemove
  • mouseout
  • mouseover
  • mouseup
  • select

Additionally, JSF has two more special event names for EditableValueHolder and ActionSource components, the real HTML DOM event being rendered depends on the component type:

  • valueChange (will render as change on text/select inputs and as click on radio/checkbox inputs)
  • action (will render as click on command links/buttons)

The above two are the default events for the components in question.

Some JSF component libraries have additional customized event names which are generally more specialized kinds of valueChange or action events, such as PrimeFaces <p:ajax> which supports among others tabChange, itemSelect, itemUnselect, dateSelect, page, sort, filter, close, etc depending on the parent <p:xxx> component. You can find them all in the "Ajax Behavior Events" subsection of each component's chapter in PrimeFaces Users Guide.

How to get input type using jquery?

The best place to start looking is http://api.jquery.com/category/selectors/

This will give you a good set of examples.

Ultamatly the selecting of elements in the DOM is achived using CSS selectors so if you think about getting an element by id you will want to use $('#elementId'), if you want all the input tags use $('input') and finaly the part i think you'll want if you want all input tags with a type of checkbox use $('input, [type=checkbox])

Note: You'll find most of the values you want are on attributes so the css selector for attributes is: [attributeName=value]

Just because you asked for the dropdown as aposed to a listbox try the following:


$('select, [size]).each(function(){
  var selectedItem = $('select, [select]', this).first();
});

The code was from memory so please accound for small errors

How to debug Spring Boot application with Eclipse?

How to debug a remote staging or production Spring Boot application

Server-side

Let's assume you have successfully followed Spring Boot's guide on setting up your Spring Boot application as a service. Your application artifact resides in /srv/my-app/my-app.war, accompanied by a configuration file /srv/my-app/my-app.conf:

# This is file my-app.conf
# What can you do in this .conf file? The my-app.war is prepended with a SysV init.d script
# (yes, take a look into the war file with a text editor). As my-app.war is symlinked in the init.d directory, that init.d script
# gets executed. One of its step is actually `source`ing this .conf file. Therefore we can do anything in this .conf file that
# we can also do in a regular shell script.

JAVA_OPTS="-agentlib:jdwp=transport=dt_socket,address=localhost:8002,server=y,suspend=n"
export SPRING_PROFILES_ACTIVE=staging

When you restart your Spring Boot application with sudo service my-app restart, then in its log file located at /var/log/my-app.log should be a line saying Listening for transport dt_socket at address: 8002.

Client-side (developer machine)

Open an SSH port-forwarding tunnel to the server: ssh -L 8002:localhost:8002 [email protected]. Keep this SSH session running.

In Eclipse, from the toolbar, select Run -> Debug Configurations -> select Remote Java Application -> click the New button -> select as Connection Type Standard (Socket Attach), as Host localhost, and as Port 8002 (or whatever you have configured in the steps before). Click Apply and then Debug.

The Eclipse debugger should now connect to the remote server. Switching to the Debug perspective should show the connected JVM and its threads. Breakpoints should fire as soon as they are remotely triggered.

When do I need a fb:app_id or fb:admins?

Including the fb:app_id tag in your HTML HEAD will allow the Facebook scraper to associate the Open Graph entity for that URL with an application. This will allow any admins of that app to view Insights about that URL and any social plugins connected with it.

The fb:admins tag is similar, but allows you to just specify each user ID that you would like to give the permission to do the above.

You can include either of these tags or both, depending on how many people you want to admin the Insights, etc. A single as fb:admins is pretty much a minimum requirement. The rest of the Open Graph tags will still be picked up when people share and like your URL, however it may cause problems in the future, so please include one of the above.

fb:admins is specified like this:
<meta property="fb:admins" content="USER_ID"/>
OR
<meta property="fb:admins" content="USER_ID,USER_ID2,USER_ID3"/>

and fb:app_id like this:
<meta property="fb:app_id" content="APPID"/>

Changing all files' extensions in a folder with one command on Windows

What worked for me is this one(cd to the folder first):

Get-ChildItem -Filter *.old | Rename-Item -NewName {[System.IO.Path]::ChangeExtension($_.Name, ".new")}

Spark difference between reduceByKey vs groupByKey vs aggregateByKey vs combineByKey

  • groupByKey() is just to group your dataset based on a key. It will result in data shuffling when RDD is not already partitioned.
  • reduceByKey() is something like grouping + aggregation. We can say reduceBykey() equvelent to dataset.group(...).reduce(...). It will shuffle less data unlike groupByKey().
  • aggregateByKey() is logically same as reduceByKey() but it lets you return result in different type. In another words, it lets you have a input as type x and aggregate result as type y. For example (1,2),(1,4) as input and (1,"six") as output. It also takes zero-value that will be applied at the beginning of each key.

Note : One similarity is they all are wide operations.

How can I get a list of all classes within current module in Python?

If you want to have all the classes, that belong to the current module, you could use this :

import sys, inspect
def print_classes():
    is_class_member = lambda member: inspect.isclass(member) and member.__module__ == __name__
    clsmembers = inspect.getmembers(sys.modules[__name__], is_class_member)

If you use Nadia's answer and you were importing other classes on your module, that classes will be being imported too.

So that's why member.__module__ == __name__ is being added to the predicate used on is_class_member. This statement checks that the class really belongs to the module.

A predicate is a function (callable), that returns a boolean value.

Windows service start failure: Cannot start service from the command line or debugger

Goto App.config

Find

<setting name="RunAsWindowsService" serializeAs="String">
    <value>True</value>
  </setting>

Set to False

Replace the single quote (') character from a string

Do you mean like this?

>>> mystring = "This isn't the right place to have \"'\" (single quotes)"
>>> mystring
'This isn\'t the right place to have "\'" (single quotes)'
>>> newstring = mystring.replace("'", "")
>>> newstring
'This isnt the right place to have "" (single quotes)'

Convert InputStream to JSONObject

This code works

BufferedReader bR = new BufferedReader(  new InputStreamReader(inputStream));
String line = "";

StringBuilder responseStrBuilder = new StringBuilder();
while((line =  bR.readLine()) != null){

    responseStrBuilder.append(line);
}
inputStream.close();

JSONObject result= new JSONObject(responseStrBuilder.toString());       

Save ArrayList to SharedPreferences

Use this custom class:

public class SharedPreferencesUtil {

    public static void pushStringList(SharedPreferences sharedPref, 
                                      List<String> list, String uniqueListName) {

        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putInt(uniqueListName + "_size", list.size());

        for (int i = 0; i < list.size(); i++) {
            editor.remove(uniqueListName + i);
            editor.putString(uniqueListName + i, list.get(i));
        }
        editor.apply();
    }

    public static List<String> pullStringList(SharedPreferences sharedPref, 
                                              String uniqueListName) {

        List<String> result = new ArrayList<>();
        int size = sharedPref.getInt(uniqueListName + "_size", 0);

        for (int i = 0; i < size; i++) {
            result.add(sharedPref.getString(uniqueListName + i, null));
        }
        return result;
    }
}

How to use:

SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferencesUtil.pushStringList(sharedPref, list, getString(R.string.list_name));
List<String> list = SharedPreferencesUtil.pullStringList(sharedPref, getString(R.string.list_name));

How to remove class from all elements jquery

try: $(".highlight").removeClass("highlight");. By selecting $(".edgetoedge") you are only running functions at that level.

How to reload/refresh jQuery dataTable?

reinitialise datatable with init and write retrieve as true ..done..so simple

eg.

TableAjax.init();
retrieve: true,

Simple C example of doing an HTTP POST and consuming the response

Handle added.
Added Host header.
Added linux / windows support, tested (XP,WIN7).
WARNING: ERROR : "segmentation fault" if no host,path or port as argument.

#include <stdio.h> /* printf, sprintf */
#include <stdlib.h> /* exit, atoi, malloc, free */
#include <unistd.h> /* read, write, close */
#include <string.h> /* memcpy, memset */
#ifdef __linux__ 
    #include <sys/socket.h> /* socket, connect */
    #include <netdb.h> /* struct hostent, gethostbyname */
    #include <netinet/in.h> /* struct sockaddr_in, struct sockaddr */
#elif _WIN32
    #include <winsock2.h>
    #include <ws2tcpip.h>
    #include <windows.h>
    #pragma comment(lib,"ws2_32.lib") //Winsock Library

#else

#endif

void error(const char *msg) { perror(msg); exit(0); }

int main(int argc,char *argv[])
{

    int i;
    struct hostent *server;
    struct sockaddr_in serv_addr;
    int bytes, sent, received, total, message_size;
    char *message, response[4096];
    int portno = atoi(argv[2])>0?atoi(argv[2]):80;
    char *host = strlen(argv[1])>0?argv[1]:"localhost";
    char *path = strlen(argv[4])>0?argv[4]:"/";
    if (argc < 5) { puts("Parameters: <host> <port> <method> <path> [<data> [<headers>]]"); exit(0); }
    /* How big is the message? */
    message_size=0;
    if(!strcmp(argv[3],"GET"))
    {
                printf("Process 1\n");
        message_size+=strlen("%s %s%s%s HTTP/1.0\r\nHost: %s\r\n");        /* method         */
        message_size+=strlen(argv[3]);                         /* path           */
        message_size+=strlen(path);                         /* headers        */
        if(argc>5)
            message_size+=strlen(argv[5]);                     /* query string   */
        for(i=6;i<argc;i++)                                    /* headers        */
            message_size+=strlen(argv[i])+strlen("\r\n");
        message_size+=strlen("\r\n");                          /* blank line     */
    }
    else
    {
                printf("Process 2\n");
        message_size+=strlen("%s %s HTTP/1.0\r\nHost: %s\r\n");
        message_size+=strlen(argv[3]);                         /* method         */
        message_size+=strlen(path);                            /* path           */
        for(i=6;i<argc;i++)                                    /* headers        */
            message_size+=strlen(argv[i])+strlen("\r\n");
        if(argc>5)
            message_size+=strlen("Content-Length: %d\r\n")+10; /* content length */
        message_size+=strlen("\r\n");                          /* blank line     */
        if(argc>5)
            message_size+=strlen(argv[5]);                     /* body           */
    }
            printf("Allocating...\n");
    /* allocate space for the message */
    message=malloc(message_size);

    /* fill in the parameters */
    if(!strcmp(argv[3],"GET"))
    {
        if(argc>5)
            sprintf(message,"%s %s%s%s HTTP/1.0\r\nHost: %s\r\n",
                strlen(argv[3])>0?argv[3]:"GET",               /* method         */
                path,                                          /* path           */
                strlen(argv[5])>0?"?":"",                      /* ?              */
                strlen(argv[5])>0?argv[5]:"",host);            /* query string   */
        else
            sprintf(message,"%s %s HTTP/1.0\r\nHost: %s\r\n",
                strlen(argv[3])>0?argv[3]:"GET",               /* method         */
                path,host);                                    /* path           */
        for(i=6;i<argc;i++)                                    /* headers        */
            {strcat(message,argv[i]);strcat(message,"\r\n");}
        strcat(message,"\r\n");                                /* blank line     */
    }
    else
    {
        sprintf(message,"%s %s HTTP/1.0\r\nHost: %s\r\n",
            strlen(argv[3])>0?argv[3]:"POST",                  /* method         */
            path,host);                                        /* path           */
        for(i=6;i<argc;i++)                                    /* headers        */
            {strcat(message,argv[i]);strcat(message,"\r\n");}
        if(argc>5)
            sprintf(message+strlen(message),"Content-Length: %d\r\n",(int)strlen(argv[5]));
        strcat(message,"\r\n");                                /* blank line     */
        if(argc>5)
            strcat(message,argv[5]);                           /* body           */
    }
    printf("Processed\n");
    /* What are we going to send? */
    printf("Request:\n%s\n",message);
        /* lookup the ip address */

    total = strlen(message);
    /* create the socket */
    #ifdef _WIN32
WSADATA wsa;
SOCKET s;

printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
{
    printf("Failed. Error Code : %d",WSAGetLastError());
    return 1;
}

printf("Initialised.\n");

//Create a socket
if((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
{
    printf("Could not create socket : %d" , WSAGetLastError());
}

printf("Socket created.\n");

server = gethostbyname(host);
serv_addr.sin_addr.s_addr = inet_addr(server->h_addr);
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(portno);
memset(&serv_addr,0,sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(portno);
memcpy(&serv_addr.sin_addr.s_addr,server->h_addr,server->h_length);
//Connect to remote server
if (connect(s , (struct sockaddr *)&serv_addr , sizeof(serv_addr)) < 0)
{
    printf("connect failed with error code : %d" , WSAGetLastError());
    return 1;
}

puts("Connected");
if( send(s , message , strlen(message) , 0) < 0)
{
    printf("Send failed with error code : %d" , WSAGetLastError());
    return 1;
}
puts("Data Send\n");

//Receive a reply from the server
if((received = recv(s , response , 2000 , 0)) == SOCKET_ERROR)
{
    printf("recv failed with error code : %d" , WSAGetLastError());
}

puts("Reply received\n");

//Add a NULL terminating character to make it a proper string before printing
response[received] = '\0';
puts(response);

closesocket(s);
WSACleanup();
    #endif
    #ifdef __linux__ 
    int sockfd;
    server = gethostbyname(host);
    if (server == NULL) error("ERROR, no such host");
        sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0) error("ERROR opening socket");
        /* fill in the structure */
        memset(&serv_addr,0,sizeof(serv_addr));
        serv_addr.sin_family = AF_INET;
        serv_addr.sin_port = htons(portno);
        memcpy(&serv_addr.sin_addr.s_addr,server->h_addr,server->h_length);
                /* connect the socket */
        if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
            error("ERROR connecting");
                /* send the request */

    sent = 0;
    do {
        bytes = write(sockfd,message+sent,total-sent);
        if (bytes < 0)
            error("ERROR writing message to socket");
        if (bytes == 0)
            break;
        sent+=bytes;
    } while (sent < total);
    /* receive the response */
    memset(response, 0, sizeof(response));
    total = sizeof(response)-1;
    received = 0;
    printf("Response: \n");
    do {
       printf("%s", response);
       memset(response, 0, sizeof(response));
       bytes = recv(sockfd, response, 1024, 0);
        if (bytes < 0)
           printf("ERROR reading response from socket");
       if (bytes == 0)
           break;
       received+=bytes;
    } while (1);

    if (received == total)
        error("ERROR storing complete response from socket");

    /* close the socket */
    close(sockfd);
    #endif


    free(message);

    return 0;
}

COUNT DISTINCT with CONDITIONS

Try the following statement:

select  distinct A.[Tag],
     count(A.[Tag]) as TAG_COUNT,
     (SELECT count(*) FROM [TagTbl] AS B WHERE A.[Tag]=B.[Tag] AND B.[ID]>0)
     from [TagTbl] AS A GROUP BY A.[Tag]

The first field will be the tag the second will be the whole count the third will be the positive ones count.

How to make ConstraintLayout work with percentage values?

As of "ConstraintLayout1.1.0-beta1" you can use percent to define widths & heights.

android:layout_width="0dp"
app:layout_constraintWidth_default="percent"
app:layout_constraintWidth_percent=".4"

This will define the width to be 40% of the width of the screen. A combination of this and guidelines in percent allows you to create any percent-based layout you want.

Combine multiple Collections into a single logical Collection?

You could create a new List and addAll() of your other Lists to it. Then return an unmodifiable list with Collections.unmodifiableList().

How to find unused/dead code in java projects

One thing I've been known to do in Eclipse, on a single class, is change all of its methods to private and then see what complaints I get. For methods that are used, this will provoke errors, and I return them to the lowest access level I can. For methods that are unused, this will provoke warnings about unused methods, and those can then be deleted. And as a bonus, you often find some public methods that can and should be made private.

But it's very manual.

How can I get the order ID in WooCommerce?

As of woocommerce 3.0

$order->id;

will not work, it will generate notice, use getter function:

$order->get_id();

The same applies for other woocommerce objects like procut.

Converting an integer to a string in PHP

There's many ways to do this.

Two examples:

 $str = (string) $int;
 $str = "$int";     

See the PHP Manual on Types Juggling for more.

document.all vs. document.getElementById

Specifically, document.all was introduced for IE4 BEFORE document.getElementById had been introduced.

So, the presence of document.all means that the code is intended to support IE4, or is trying to identify the browser as IE4 (though it could have been Opera), or the person who wrote (or copied and pasted) the code wasn't up on the latest.

In the highly unlikely event that you need to support IE4, then, you do need document.all (or a library that handles these ancient IE specs).

How to change color of ListView items on focus and on click

In your main.xml include the following in your ListView:

android:drawSelectorOnTop="false"

android:listSelector="@android:color/darker_gray"

Is it possible to get a list of files under a directory of a website? How?

If a website's directory does NOT have an "index...." file, AND .htaccess has NOT been used to block access to the directory itself, then Apache will create an "index of" page for that directory. You can save that page, and its icons, using "Save page as..." along with the "Web page, complete" option (Firefox example). If you own the website, temporarily rename any "index...." file, and reference the directory locally. Then restore your "index...." file.

Python idiom to return first item or None

Out of curiosity, I ran timings on two of the solutions. The solution which uses a return statement to prematurely end a for loop is slightly more costly on my machine with Python 2.5.1, I suspect this has to do with setting up the iterable.

import random
import timeit

def index_first_item(some_list):
    if some_list:
        return some_list[0]


def return_first_item(some_list):
    for item in some_list:
        return item


empty_lists = []
for i in range(10000):
    empty_lists.append([])

assert empty_lists[0] is not empty_lists[1]

full_lists = []
for i in range(10000):
    full_lists.append(list([random.random() for i in range(10)]))

mixed_lists = empty_lists[:50000] + full_lists[:50000]
random.shuffle(mixed_lists)

if __name__ == '__main__':
    ENV = 'import firstitem'
    test_data = ('empty_lists', 'full_lists', 'mixed_lists')
    funcs = ('index_first_item', 'return_first_item')
    for data in test_data:
        print "%s:" % data
        for func in funcs:
            t = timeit.Timer('firstitem.%s(firstitem.%s)' % (
                func, data), ENV)
            times = t.repeat()
            avg_time = sum(times) / len(times)
            print "  %s:" % func
            for time in times:
                print "    %f seconds" % time
            print "    %f seconds avg." % avg_time

These are the timings I got:

empty_lists:
  index_first_item:
    0.748353 seconds
    0.741086 seconds
    0.741191 seconds
    0.743543 seconds avg.
  return_first_item:
    0.785511 seconds
    0.822178 seconds
    0.782846 seconds
    0.796845 seconds avg.
full_lists:
  index_first_item:
    0.762618 seconds
    0.788040 seconds
    0.786849 seconds
    0.779169 seconds avg.
  return_first_item:
    0.802735 seconds
    0.878706 seconds
    0.808781 seconds
    0.830074 seconds avg.
mixed_lists:
  index_first_item:
    0.791129 seconds
    0.743526 seconds
    0.744441 seconds
    0.759699 seconds avg.
  return_first_item:
    0.784801 seconds
    0.785146 seconds
    0.840193 seconds
    0.803380 seconds avg.

Importing class from another file

Your problem is basically that you never specified the right path to the file.

Try instead, from your main script:

from folder.file import Klasa

Or, with from folder import file:

from folder import file
k = file.Klasa()

Or again:

import folder.file as myModule
k = myModule.Klasa()

Check object empty

This can be done with java reflection,This method returns false if any one attribute value is present for the object ,hope it helps some one

public boolean isEmpty()  {

    for (Field field : this.getClass().getDeclaredFields()) {
        try {
            field.setAccessible(true);
            if (field.get(this)!=null) {
                return false;
            }
        } catch (Exception e) {
          System.out.println("Exception occured in processing");
        }
    }
    return true;
}

Make: how to continue after a command fails?

To get make to actually ignore errors on a single line, you can simply suffix it with ; true, setting the return value to 0. For example:

rm .lambda .lambda_t .activity .activity_t_lambda 2>/dev/null; true

This will redirect stderr output to null, and follow the command with true (which always returns 0, causing make to believe the command succeeded regardless of what actually happened), allowing program flow to continue.

Transform only one axis to log10 scale with ggplot2

Another solution using scale_y_log10 with trans_breaks, trans_format and annotation_logticks()

library(ggplot2)

m <- ggplot(diamonds, aes(y = price, x = color))

m + geom_boxplot() +
  scale_y_log10(
    breaks = scales::trans_breaks("log10", function(x) 10^x),
    labels = scales::trans_format("log10", scales::math_format(10^.x))
  ) +
  theme_bw() +
  annotation_logticks(sides = 'lr') +
  theme(panel.grid.minor = element_blank())

Convert JSONArray to String Array

A ready-to-use method:

/**
* Convert JSONArray to ArrayList<String>.
* 
* @param jsonArray JSON array.
* @return String array.
*/
public static ArrayList<String> toStringArrayList(JSONArray jsonArray) {

  ArrayList<String> stringArray = new ArrayList<String>();
  int arrayIndex;
  JSONObject jsonArrayItem;
  String jsonArrayItemKey;

  for (
    arrayIndex = 0;
    arrayIndex < jsonArray.length();
    arrayIndex++) {

    try {
      jsonArrayItem =
        jsonArray.getJSONObject(
          arrayIndex);

      jsonArrayItemKey =
        jsonArrayItem.getString(
          "name");

      stringArray.add(
        jsonArrayItemKey);
    } catch (JSONException e) {
      e.printStackTrace();
    }
  }

  return stringArray;
}

The pipe ' ' could not be found angular2 custom pipe

If you see this error when running tests, make sure you have imported the module the pipe belongs to, e.g.:

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            imports: [CustomPipeModule],
            declarations: [...],
            providers: [...],
            ...
        }).compileComponents();
    }));

Error: Expression must have integral or unscoped enum type

Your variable size is declared as: float size;

You can't use a floating point variable as the size of an array - it needs to be an integer value.

You could cast it to convert to an integer:

float *temp = new float[(int)size];

Your other problem is likely because you're writing outside of the bounds of the array:

   float *temp = new float[size];

    //Getting input from the user
    for (int x = 1; x <= size; x++){
        cout << "Enter temperature " << x << ": ";

        // cin >> temp[x];
        // This should be:
        cin >> temp[x - 1];
    }

Arrays are zero based in C++, so this is going to write beyond the end and never write the first element in your original code.

How do I check for a network connection?

Microsoft windows vista and 7 use NCSI (Network Connectivity Status Indicator) technic:

  1. NCSI performs a DNS lookup on www.msftncsi.com, then requests http://www.msftncsi.com/ncsi.txt. This file is a plain-text file and contains only the text 'Microsoft NCSI'.
  2. NCSI sends a DNS lookup request for dns.msftncsi.com. This DNS address should resolve to 131.107.255.255. If the address does not match, then it is assumed that the internet connection is not functioning correctly.

Using CSS :before and :after pseudo-elements with inline CSS?

you can use

parent.style.setProperty("--padding-top", (height*100/width).toFixed(2)+"%");

in css

el:after{
  ....
  padding-top:var(--padding-top, 0px);
}

What is the difference between <%, <%=, <%# and -%> in ERB in Rails?

  • <% %> : Executes the ruby code
  • <%= %> : Prints into Erb file. Or browser
  • <% -%> : Avoids line break after expression.
  • <%# %> : ERB comment

Install npm (Node.js Package Manager) on Windows (w/o using Node.js MSI)

Download the latest Node.js MSI (4.x or 5.x) installer and run the following via command line:

msiexec /a node-v4.4.3-x64.msi /qb TARGETDIR="C:\Node.js"

This will extract the binaries into C:\Node.js\nodejs.

Then you will want to add C:\Node.js\nodejs PATH environment variable.

To update NPM, do the following:

cd C:\Node.js\nodejs
npm install npm@latest

After that completes, you should be able to check the versions:

node --version
npm --version

Node should be 4.4.3+ (whichever you installed) and npm should be 3.8.7+.

Multiple radio button groups in one form

in input field make name same like

<input type="radio" name="option" value="option1">
<input type="radio" name="option" value="option2" >
<input type="radio" name="option" value="option3" >
<input type="radio" name="option" value="option3" >

Iterate over array of objects in Typescript

In Typescript and ES6 you can also use for..of:

for (var product of products) {
     console.log(product.product_desc)
}

which will be transcoded to javascript:

for (var _i = 0, products_1 = products; _i < products_1.length; _i++) {
    var product = products_1[_i];
    console.log(product.product_desc);
}

Why do I always get the same sequence of random numbers with rand()?

If I remember the quote from Knuth's seminal work "The Art of Computer Programming" at the beginning of the chapter on Random Number Generation, it goes like this:

"Anyone who attempts to generate random numbers by mathematical means is, technically speaking, in a state of sin".

Simply put, the stock random number generators are algorithms, mathematical and 100% predictable. This is actually a good thing in a lot of situations, where a repeatable sequence of "random" numbers is desirable - for example for certain statistical exercises, where you don't want the "wobble" in results that truly random data introduces thanks to clustering effects.

Although grabbing bits of "random" data from the computer's hardware is a popular second alternative, it's not truly random either - although the more complex the operating environment, the more possibilities for randomness - or at least unpredictability.

Truly random data generators tend to look to outside sources. Radioactive decay is a favorite, as is the behavior of quasars. Anything whose roots are in quantum effects is effectively random - much to Einstein's annoyance.

How do I generate sourcemaps when using babel and webpack?

Minimal webpack config for jsx with sourcemaps:

var path = require('path');
var webpack = require('webpack');

module.exports = {
  entry: `./src/index.jsx` ,
  output: {
    path:  path.resolve(__dirname,"build"),
    filename: "bundle.js"
  },
  devtool: 'eval-source-map',
  module: {
    loaders: [
      {
        test: /.jsx?$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        query: {
          presets: ['es2015', 'react']
        }
      }
    ]
  },
};

Running it:

Jozsefs-MBP:react-webpack-babel joco$ webpack -d
Hash: c75d5fb365018ed3786b
Version: webpack 1.13.2
Time: 3826ms
        Asset     Size  Chunks             Chunk Names
    bundle.js   1.5 MB       0  [emitted]  main
bundle.js.map  1.72 MB       0  [emitted]  main
    + 221 hidden modules
Jozsefs-MBP:react-webpack-babel joco$

How to split a string in Ruby and get all items except the first one?

Since you've got an array, what you really want is Array#slice, not split.

rest = ex.slice(1 .. -1)
# or
rest = ex[1 .. -1]

Rails create or update magic?

Old question but throwing my solution into the ring for completeness. I needed this when I needed a specific find but a different create if it doesn't exist.

def self.find_by_or_create_with(args, attributes) # READ CAREFULLY! args for finding, attributes for creating!
        obj = self.find_or_initialize_by(args)
        return obj if obj.persisted?
        return obj if obj.update_attributes(attributes) 
end

MySQL user DB does not have password columns - Installing MySQL on OSX

Root Cause: root has no password, and your python connect statement should reflect that.

To solve error 1698, change your python connect password to ''.

note: manually updating the user's password will not solve the problem, you will still get error 1698

Using a Glyphicon as an LI bullet point (Bootstrap 3)

If anyone is coming here looking to do this with Font Awesome Icons (like I was) view here: https://fontawesome.com/how-to-use/on-the-web/styling/icons-in-a-list

<ul class="fa-ul">
  <li><i class="fa-li fa fa-check-square"></i>List icons</li>
  <li><i class="fa-li fa fa-check-square"></i>can be used</li>
  <li><i class="fa-li fa fa-spinner fa-spin"></i>as bullets</li>
  <li><i class="fa-li fa fa-square"></i>in lists</li>
</ul>

The fa-ul and fa-li classes easily replace default bullets in unordered lists.

MySQL - how to front pad zip code with "0"?

Ok, so you've switched the column from Number to VARCHAR(5). Now you need to update the zipcode field to be left-padded. The SQL to do that would be:

UPDATE MyTable
SET ZipCode = LPAD( ZipCode, 5, '0' );

This will pad all values in the ZipCode column to 5 characters, adding '0's on the left.

Of course, now that you've got all of your old data fixed, you need to make sure that your any new data is also zero-padded. There are several schools of thought on the correct way to do that:

  • Handle it in the application's business logic. Advantages: database-independent solution, doesn't involve learning more about the database. Disadvantages: needs to be handled everywhere that writes to the database, in all applications.

  • Handle it with a stored procedure. Advantages: Stored procedures enforce business rules for all clients. Disadvantages: Stored procedures are more complicated than simple INSERT/UPDATE statements, and not as portable across databases. A bare INSERT/UPDATE can still insert non-zero-padded data.

  • Handle it with a trigger. Advantages: Will work for Stored Procedures and bare INSERT/UPDATE statements. Disadvantages: Least portable solution. Slowest solution. Triggers can be hard to get right.

In this case, I would handle it at the application level (if at all), and not the database level. After all, not all countries use a 5-digit Zipcode (not even the US -- our zipcodes are actually Zip+4+2: nnnnn-nnnn-nn) and some allow letters as well as digits. Better NOT to try and force a data format and to accept the occasional data error, than to prevent someone from entering the correct value, even though it's format isn't quite what you expected.

java.lang.ClassNotFoundException: org.springframework.boot.SpringApplication Maven

Your jar does not contain the dependencies such as spring-boot which it is looking for during runtime. You can build a consolidated jar with all the dependencies as outlined in this question.

How to delete a record by id in Flask-SQLAlchemy

You can do this,

User.query.filter_by(id=123).delete()

or

User.query.filter(User.id == 123).delete()

Make sure to commit for delete() to take effect.

Get cursor position (in characters) within a text Input field

There is now a nice plugin for this: The Caret Plugin

Then you can get the position using $("#myTextBox").caret() or set it via $("#myTextBox").caret(position)

How do I express "if value is not empty" in the VBA language?

Alexphi's suggestion is good. You can also hard code this by first creating a variable as a Variant and then assigning it to Empty. Then do an if/then with to possibly fill it. If it gets filled, it's not empty, if it doesn't, it remains empty. You check this then with IsEmpty.

Sub TestforEmpty()

    Dim dt As Variant
    dt = Empty

    Dim today As Date
    today = Date
    If today = Date Then
        dt = today
    End If

    If IsEmpty(dt) Then
        MsgBox "It not is today"
    Else
        MsgBox "It is today"
    End If

End Sub

python location on mac osx

which python3 simply result in a path in which the interpreter settles down.

How do you check in python whether a string contains only numbers?

Use str.isdigit:

>>> "12345".isdigit()
True
>>> "12345a".isdigit()
False
>>>

ImportError: No module named 'google'

Use this both installation and then go ahead with your python code

pip install google-cloud    
pip install google-cloud-vision

Capitalize or change case of an NSString in Objective-C

Here ya go:

viewNoteDateMonth.text  = [[displayDate objectAtIndex:2] uppercaseString];

Btw:
"april" is lowercase ? [NSString lowercaseString]
"APRIL" is UPPERCASE ? [NSString uppercaseString]
"April May" is Capitalized/Word Caps ? [NSString capitalizedString]
"April may" is Sentence caps ? (method missing; see workaround below)

Hence what you want is called "uppercase", not "capitalized". ;)

As for "Sentence Caps" one has to keep in mind that usually "Sentence" means "entire string". If you wish for real sentences use the second method, below, otherwise the first:

@interface NSString ()

- (NSString *)sentenceCapitalizedString; // sentence == entire string
- (NSString *)realSentenceCapitalizedString; // sentence == real sentences

@end

@implementation NSString

- (NSString *)sentenceCapitalizedString {
    if (![self length]) {
        return [NSString string];
    }
    NSString *uppercase = [[self substringToIndex:1] uppercaseString];
    NSString *lowercase = [[self substringFromIndex:1] lowercaseString];
    return [uppercase stringByAppendingString:lowercase];
}

- (NSString *)realSentenceCapitalizedString {
    __block NSMutableString *mutableSelf = [NSMutableString stringWithString:self];
    [self enumerateSubstringsInRange:NSMakeRange(0, [self length])
                             options:NSStringEnumerationBySentences
                          usingBlock:^(NSString *sentence, NSRange sentenceRange, NSRange enclosingRange, BOOL *stop) {
        [mutableSelf replaceCharactersInRange:sentenceRange withString:[sentence sentenceCapitalizedString]];
    }];
    return [NSString stringWithString:mutableSelf]; // or just return mutableSelf.
}

@end

PostgreSQL: How to make "case-insensitive" query

using ILIKE instead of LIKE

SELECT id FROM groups WHERE name ILIKE 'Administrator'

Python: finding lowest integer

number_list = [99.5,1.2,-0.3]

number_list.sort()

print number_list[0]

Returning from a void function

An old question, but I'll answer anyway. The answer to the actual question asked is that the bare return is redundant and should be left out.

Furthermore, the suggested value is false for the following reason:

if (ret<0) return;

Redefining a C reserved word as a macro is a bad idea on the face of it, but this particular suggestion is simply unsupportable, both as an argument and as code.

Remove a string from the beginning of a string

This will remove first match wherever it is found i.e., start or middle or end.

$str = substr($str, 0, strpos($str, $prefix)).substr($str, strpos($str, $prefix)+strlen($prefix));

Difference between dict.clear() and assigning {} in Python

In addition to the differences mentioned in other answers, there also is a speed difference. d = {} is over twice as fast:

python -m timeit -s "d = {}" "for i in xrange(500000): d.clear()"
10 loops, best of 3: 127 msec per loop

python -m timeit -s "d = {}" "for i in xrange(500000): d = {}"
10 loops, best of 3: 53.6 msec per loop

Set value of hidden field in a form using jQuery's ".val()" doesn't work

In my case, I was using a non-string (integer) as the parameter of val() which doesn't work, the trick is just as simple as

$("#price").val('' + price);

Handling optional parameters in javascript

I think you want to use typeof() here:

function f(id, parameters, callback) {
  console.log(typeof(parameters)+" "+typeof(callback));
}

f("hi", {"a":"boo"}, f); //prints "object function"
f("hi", f, {"a":"boo"}); //prints "function object"

Update multiple values in a single statement

Have you tried with a sub-query for every field:

UPDATE
    MasterTbl
SET
    TotalX = (SELECT SUM(X) from DetailTbl where DetailTbl.MasterID = MasterTbl.ID),
    TotalY = (SELECT SUM(Y) from DetailTbl where DetailTbl.MasterID = MasterTbl.ID),
    TotalZ = (SELECT SUM(Z) from DetailTbl where DetailTbl.MasterID = MasterTbl.ID)
WHERE
    ....

Is there a color code for transparent in HTML?

Yeah I think the best way to transparent the background colour (make opacity only for the background) is using

.style{
        background-color: rgba(100, 100, 100, 0.5);
}

Above statement 0.5 is the opacity value.

It only apply the opacity changes to the background colour (not all elements')

The "opacity" attribute in the CSS will transparent all the elements in the block.

JSON array get length

have you tried size() ? Something like :

jar.size();

Hope it helps.

failed to find target with hash string 'android-22'

I think you should install API 18 from android sdk if not already installed, otherwise you can try "invalidate caches and restart" (Find: File->invalidate caches and restart).

Writing new lines to a text file in PowerShell

Try this;

Add-Content -path $logpath @"
$((get-date).tostring()) Error $keyPath $value
key $key expected: $policyValue
local value is:  $localValue
"@

Get the latest date from grouped MySQL data

Are you looking for the max date for each model?

SELECT model, max(date) FROM doc
GROUP BY model

If you're looking for all models matching the max date of the entire table...

SELECT model, date FROM doc
WHERE date IN (SELECT max(date) FROM doc)

[--- Added ---]

For those who want to display details from every record matching the latest date within each model group (not summary data, as asked for in the OP):

SELECT d.model, d.date, d.color, d.etc FROM doc d
WHERE d.date IN (SELECT max(d2.date) FROM doc d2 WHERE d2.model=d.model)

MySQL 8.0 and newer supports the OVER clause, producing the same results a bit faster for larger data sets.

SELECT model, date, color, etc FROM (SELECT model, date, color, etc, 
  max(date) OVER (PARTITION BY model) max_date FROM doc) predoc 
WHERE date=max_date;

How to make Bootstrap 4 cards the same height in card-columns?

If anyone is interested, there is a jquery plugin called: jquery.matchHeight.js

https://github.com/liabru/jquery-match-height

matchHeight makes the height of all selected elements exactly equal. It handles many edge cases that cause similar plugins to fail.

For a row of cards, I use:

<div class="row match-height">

Then enable site-wide:

$('.row.match-height').each(function() {
   $(this).find('.card').not('.card .card').matchHeight(); // Not .card .card prevents collapsible cards from taking height
});

Convert Data URI to File then append to FormData

Here is an ES6 version of Stoive's answer:

export class ImageDataConverter {
  constructor(dataURI) {
    this.dataURI = dataURI;
  }

  getByteString() {
    let byteString;
    if (this.dataURI.split(',')[0].indexOf('base64') >= 0) {
      byteString = atob(this.dataURI.split(',')[1]);
    } else {
      byteString = decodeURI(this.dataURI.split(',')[1]);
    }
    return byteString;
  }

  getMimeString() {
    return this.dataURI.split(',')[0].split(':')[1].split(';')[0];
  }

  convertToTypedArray() {
    let byteString = this.getByteString();
    let ia = new Uint8Array(byteString.length);
    for (let i = 0; i < byteString.length; i++) {
      ia[i] = byteString.charCodeAt(i);
    }
    return ia;
  }

  dataURItoBlob() {
    let mimeString = this.getMimeString();
    let intArray = this.convertToTypedArray();
    return new Blob([intArray], {type: mimeString});
  }
}

Usage:

const dataURL = canvas.toDataURL('image/jpeg', 0.5);
const blob = new ImageDataConverter(dataURL).dataURItoBlob();
let fd = new FormData(document.forms[0]);
fd.append("canvasImage", blob);

Disabling contextual LOB creation as createClob() method threw error

In order to hide the exception:

For Hibernate 5.2 (and Spring Boot 2.0), you can either use the use_jdbc_metadata_defaults property that the others pointed out:

# Meant to hide HHH000424: Disabling contextual LOB creation as createClob() method threw error 
spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults: false

Or, if you want to not have any side effects from the above setting (there's a comment warning us about some Oracle side effects, I don't know if it's valid or not), you can just disable the logging of the exception like this:

logging:
   level: 
      # Hides HHH000424: Disabling contextual LOB creation as createClob() method threw error 
      org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl: WARN

Making a <button> that's a link in HTML

<a href="#"><button>Link Text</button></a>

You asked for a link that looks like a button, so use a link and a button :-) This will preserve default browser button styling. The button by itself does nothing, but clicking it activates its parent link.

Demo:

_x000D_
_x000D_
<a href="http://stackoverflow.com"><button>Link Text</button></a>
_x000D_
_x000D_
_x000D_

Django: How can I call a view function from template?

How about this:

<a class="btn btn-primary" href="{% url 'url-name'%}">Button-Text</a>

The class is including bootstrap styles for primary button.

Error:(9, 5) error: resource android:attr/dialogCornerRadius not found

In my case, this error ocurred while i was using the

implementation 'com.android.support:appcompat-v7:+'
implementation 'com.android.support:design:+'

libraries together with googles

implementation 'com.google.android.material:material-components:+'

library. If this is the case in your project, i highly recommend to fully remove the google material components library from your project.

file_get_contents("php://input") or $HTTP_RAW_POST_DATA, which one is better to get the body of JSON request?

file_get_contents(php://input) - gets the raw POST data and you need to use this when you write APIs and need XML/JSON/... input that cannot be decoded to $_POST by PHP some example :

send by post JSON string

<input type="button" value= "click" onclick="fn()">
<script>
 function fn(){


    var js_obj = {plugin: 'jquery-json', version: 2.3};

    var encoded = JSON.stringify( js_obj );

var data= encoded


    $.ajax({
  type: "POST",
  url: '1.php',
  data: data,
  success: function(data){
    console.log(data);
  }

});

    }
</script>

1.php

//print_r($_POST); //empty!!! don't work ... 
var_dump( file_get_contents('php://input'));

.gitignore is ignored by Git

Even if you haven't tracked the files so far, Git seems to be able to "know" about them even after you add them to .gitignore.

WARNING: First commit or stash your current changes, or you will lose them.

Then run the following commands from the top folder of your Git repository:

git rm -r --cached .
git add .
git commit -m "fixed untracked files"

Setting a spinner onClickListener() in Android

Personally, I use that:

    final Spinner spinner = (Spinner) (view.findViewById(R.id.userList));
    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {                

            userSelectedIndex = position;
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });  

Force youtube embed to start in 720p

I've managed to get this working by the following fix:

//www.youtube.com/embed/_YOUR_VIDEO_CODE_/?vq=hd720

You video should have the hd720 resolution to do so.

I was using the embedding via iframe, BTW. Hope someone will find this helpful.

if else in a list comprehension

Make a list from items in an iterable

It seems best to first generalize all the possible forms rather than giving specific answers to questions. Otherwise, the reader won't know how the answer was determined. Here are a few generalized forms I thought up before I got a headache trying to decide if a final else' clause could be used in the last form.

[expression1(item)                                        for item in iterable]

[expression1(item) if conditional1                        for item in iterable]

[expression1(item) if conditional1 else expression2(item) for item in iterable]

[expression1(item) if conditional1 else expression2(item) for item in iterable if conditional2]

The value of item doesn't need to be used in any of the conditional clauses. A conditional3 can be used as a switch to either add or not add a value to the output list.

For example, to create a new list that eliminates empty strings or whitespace strings from the original list of strings:

newlist = [s for s in firstlist if s.strip()]

Prevent flicker on webkit-transition of webkit-transform

I had to use:

-webkit-perspective: 1000;
-webkit-backface-visibility: hidden;    

on the element, or I would still get a flickr the first time a transition occurred after page load

C# difference between == and Equals()

==

The == operator can be used to compare two variables of any kind, and it simply compares the bits.

int a = 3;
byte b = 3;
if (a == b) { // true }

Note : there are more zeroes on the left side of the int but we don't care about that here.

int a (00000011) == byte b (00000011)

Remember == operator cares only about the pattern of the bits in the variable.

Use == If two references (primitives) refers to the same object on the heap.

Rules are same whether the variable is a reference or primitive.

Foo a = new Foo();
Foo b = new Foo();
Foo c = a;

if (a == b) { // false }
if (a == c) { // true }
if (b == c) { // false }

a == c is true a == b is false

the bit pattern are the same for a and c, so they are equal using ==.

Equal():

Use the equals() method to see if two different objects are equal.

Such as two different String objects that both represent the characters in "Jane"

How to use performSelector:withObject:afterDelay: with primitive types in Cocoa?

I also wanted to do this, but with a method that receives a BOOL parameter. Wrapping the bool value with NSNumber, FAILED TO PASS THE VALUE. I have no idea why.

So I ended up doing a simple hack. I put the required parameter in another dummy function and call that function using the performSelector, where withObject = nil;

[self performSelector:@selector(dummyCaller:) withObject:nil afterDelay:5.0];

-(void)dummyCaller {

[self myFunction:YES];

}

Spring Boot: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean

if you experience this exception while using intellij and you are trying to start the application with the run button. Try starting the application from the command line instead. E.g. ensure that you are in the correct directory (directory with your pom file) assuming this is a springboot application run mvn spring-boot:run this did the trick for me.

Additionally I have also seen this error occur when your spring application depends on another application. In this case I had to start the other application first then run.

How do I force Maven to use my local repository rather than going out to remote repos to retrieve artifacts?

Follow below steps:

    1. Ensure to delete all the contents of the jar folder located in your local except the jar that you want to keep.
      For example files like .repositories, .pom, .sha1, .lastUpdated etc.
    1. Execute mvn clean install -o command

This will help to use local repository jar files rather than connecting to any repository.

jquery equivalent for JSON.stringify

There is no such functionality in jQuery. Use JSON.stringify or alternatively any jQuery plugin with similar functionality (e.g jquery-json).

JavaScript TypeError: Cannot read property 'style' of null

I met the same problem, the situation is I need to download flash game by embed tag and H5 game by iframe, I need a loading box there, when the flash or H5 download done, let the loading box display none. well, the flash one work well but when things go to iframe, I cannot find the property 'style' of null , so I add a clock to it , and it works

let clock = setInterval(() => {
        clearInterval(clock)
        clock = null
        document.getElementById('loading-box').style.display = 'none'
    }, 200)

What is causing ERROR: there is no unique constraint matching given keys for referenced table?

You should have name column as a unique constraint. here is a 3 lines of code to change your issues

  1. First find out the primary key constraints by typing this code

    \d table_name
    

    you are shown like this at bottom "some_constraint" PRIMARY KEY, btree (column)

  2. Drop the constraint:

    ALTER TABLE table_name DROP CONSTRAINT some_constraint
    
  3. Add a new primary key column with existing one:

    ALTER TABLE table_name ADD CONSTRAINT some_constraint PRIMARY KEY(COLUMN_NAME1,COLUMN_NAME2);
    

That's All.

How to compile without warnings being treated as errors?

Sure, find where -Werror is set and remove that flag. Then warnings will be only warnings.

Preventing console window from closing on Visual Studio C/C++ Console application

Here is a way for C/C++:

#include <stdlib.h>

#ifdef _WIN32
    #define WINPAUSE system("pause")
#endif

Put this at the top of your program, and IF it is on a Windows system (#ifdef _WIN32), then it will create a macro called WINPAUSE. Whenever you want your program to pause, call WINPAUSE; and it will pause the program, using the DOS command. For other systems like Unix/Linux, the console should not quit on program exit anyway.

How to link an input button to a file select window?

You could use JavaScript and trigger the hidden file input when the button input has been clicked.

http://jsfiddle.net/gregorypratt/dhyzV/ - simple

http://jsfiddle.net/gregorypratt/dhyzV/1/ - fancier with a little JQuery

Or, you could style a div directly over the file input and set pointer-events in CSS to none to allow the click events to pass through to the file input that is "behind" the fancy div. This only works in certain browsers though; http://caniuse.com/pointer-events

import module from string variable

I developed these 3 useful functions:

def loadModule(moduleName):
    module = None
    try:
        import sys
        del sys.modules[moduleName]
    except BaseException as err:
        pass
    try:
        import importlib
        module = importlib.import_module(moduleName)
    except BaseException as err:
        serr = str(err)
        print("Error to load the module '" + moduleName + "': " + serr)
    return module

def reloadModule(moduleName):
    module = loadModule(moduleName)
    moduleName, modulePath = str(module).replace("' from '", "||").replace("<module '", '').replace("'>", '').split("||")
    if (modulePath.endswith(".pyc")):
        import os
        os.remove(modulePath)
        module = loadModule(moduleName)
    return module

def getInstance(moduleName, param1, param2, param3):
    module = reloadModule(moduleName)
    instance = eval("module." + moduleName + "(param1, param2, param3)")
    return instance

And everytime I want to reload a new instance I just have to call getInstance() like this:

myInstance = getInstance("MyModule", myParam1, myParam2, myParam3)

Finally I can call all the functions inside the new Instance:

myInstance.aFunction()

The only specificity here is to customize the params list (param1, param2, param3) of your instance.

JQuery Ajax - How to Detect Network Connection error when making Ajax call

// start snippet
error: function(XMLHttpRequest, textStatus, errorThrown) {
        if (XMLHttpRequest.readyState == 4) {
            // HTTP error (can be checked by XMLHttpRequest.status and XMLHttpRequest.statusText)
        }
        else if (XMLHttpRequest.readyState == 0) {
            // Network error (i.e. connection refused, access denied due to CORS, etc.)
        }
        else {
            // something weird is happening
        }
    }
//end snippet

mysqldump & gzip commands to properly create a compressed file of a MySQL database using crontab

You can use the tee command to redirect output:

/usr/bin/mysqldump -u user -pupasswd my-database | \
tee >(gzip -9 -c > /home/user/backup/mydatabase-backup-`date +\%m\%d_\%Y`.sql.gz)  | \
gzip> /home/user/backup2/mydatabase-backup-`date +\%m\%d_\%Y`.sql.gz 2>&1

see documentation here

How to transfer paid android apps from one google account to another google account

You should be able to transfer the Application to another Username. You would need all your old user information to transfer it. The application would remove it's self from old account to new account. Also you could put a limit on how many times you where allowed to transfer it. If you transfer it to the application could expire after a year and force to buy update.

React onClick and preventDefault() link refresh/redirect?

I've had some troubles with anchor tags and preventDefault in the past and I always forget what I'm doing wrong, so here's what I figured out.

The problem I often have is that I try to access the component's attributes by destructuring them directly as with other React components. This will not work, the page will reload, even with e.preventDefault():

function (e, { href }) {
  e.preventDefault();
  // Do something with href
}
...
<a href="/foobar" onClick={clickHndl}>Go to Foobar</a>

It seems the destructuring causes an error (Cannot read property 'href' of undefined) that is not displayed to the console, probably due to the page complete reload. Since the function is in error, the preventDefault doesn't get called. If the href is #, the error is displayed properly since there's no actual reload.

I understand now that I can only access attributes as a second handler argument on custom React components, not on native HTML tags. So of course, to access an HTML tag attribute in an event, this would be the way:

function (e) {
  e.preventDefault();
  const { href } = e.target;
  // Do something with href
}
...
<a href="/foobar" onClick={clickHndl}>Go to Foobar</a>

I hope this helps other people like me puzzled by not shown errors!

How do I install cURL on Windows?

I recently installed Curl on PHP5 for Windows Vista. I did not enable the CURL library when I initially installed PHP5, so nothing about Curl was showing up in phpinfo() or php.ini.

I installed CURL by re-running the PHP5 installer (php-5.2.8-win32-installer.msi for me) and choosing "Change". Then, I added the CURL component. Restart Apache, and CURL should work. CURL will show up in phpinfo(). Also, here is a sample script you can run to verify it works. It displays an RSS feed from Google:

    <?php
    error_reporting(E_ALL);
    ini_set('display_errors', '1');
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,
    'http://news.google.com/news?hl=en&topic=t&output=rss');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $contents = curl_exec ($ch);
    echo $contents;
    curl_close ($ch);
    ?>

.m2 , settings.xml in Ubuntu

Quoted from http://maven.apache.org/settings.html:

There are two locations where a settings.xml file may live:

The Maven install: $M2_HOME/conf/settings.xml

A user's install: ${user.home}/.m2/settings.xml

So, usually for a specific user you edit

/home/*username*/.m2/settings.xml

To set environment for all local users, you might think about changing the first path.

echo key and value of an array without and with loop

If you must not use a loop (why?), you could use array_walk,

function printer($v, $k) {
   echo "$k is at $v\n";
}

array_walk($page, "printer");

See http://www.ideone.com/aV5X6.

jQuery: serialize() form and other parameters

Alternatively you could use form.serialize() with $.param(object) if you store your params in some object variable. The usage would be:

var data = form.serialize() + '&' + $.param(object)

See http://api.jquery.com/jQuery.param for further reference.

Changing Java Date one hour back

It worked for me instead using format .To work with time just use parse and toString() methods

String localTime="6:11"; LocalTime localTime = LocalTime.parse(localtime)

LocalTime lt = 6:11; localTime = lt.toString()

How to get the IP address of the server on which my C# application is running on?

If you want to avoid using DNS:

List<IPAddress> ipList = new List<IPAddress>();
foreach (var netInterface in NetworkInterface.GetAllNetworkInterfaces())
{
    foreach (var address in netInterface.GetIPProperties().UnicastAddresses)
    {
        if (address.Address.AddressFamily == AddressFamily.InterNetwork)
        {
            Console.WriteLine("found IP " + address.Address.ToString());
            ipList.Add(address.Address);
        }
    }
}

jQuery.inArray(), how to use it right?

The answer comes from the first paragraph of the documentation check if the results is greater than -1, not if it's true or false.

The $.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0.

Because JavaScript treats 0 as loosely equal to false (i.e. 0 == false, but 0 !== false), if we're checking for the presence of value within array, we need to check if it's not equal to (or greater than) -1.

What generates the "text file busy" message in Unix?

If you are running the .sh from a ssh connection with a tool like MobaXTerm, and if said tool has an autosave utility to edit remote file from local machine, that will lock the file.

Closing and reopening the SSH session solves it.

How to Sort a List<T> by a property in the object

Make use of LiNQ OrderBy

List<Order> objListOrder=new List<Order> ();
    objListOrder=GetOrderList().OrderBy(o=>o.orderid).ToList();

How to sanity check a date in Java

setLenient to false if you like a strict validation

public boolean isThisDateValid(String dateToValidate, String dateFromat){

    if(dateToValidate == null){
        return false;
    }

    SimpleDateFormat sdf = new SimpleDateFormat(dateFromat);
    sdf.setLenient(false);

    try {

        //if not valid, it will throw ParseException
        Date date = sdf.parse(dateToValidate);
        System.out.println(date);

    } catch (ParseException e) {

        e.printStackTrace();
        return false;
    }

    return true;
}

Flask at first run: Do not use the development server in a production environment

When running the python file, you would normally do this

python app.py
This will display these messages.

To avoid these messsages. Inside the CLI (Command Line Interface), run these commands.

export FLASK_APP=app.py
export FLASK_RUN_HOST=127.0.0.1
export FLASK_ENV=development
export FLASK_DEBUG=0
flask run

This should work perfectlly. :) :)

Disabling submit button until all fields have values

Grave digging... I like a different approach:

elem = $('form')
elem.on('keyup','input', checkStatus)
elem.on('change', 'select', checkStatus)

checkStatus = (e) =>
  elems = $('form').find('input:enabled').not('input[type=hidden]').map(-> $(this).val())
  filled = $.grep(elems, (n) -> n)
  bool = elems.size() != $(filled).size()
  $('input:submit').attr('disabled', bool)

How to execute a raw update sql with dynamic binding in rails

Why use raw SQL for this?

If you have a model for it use where:

f1 = 'foo'
f2 = 'bar'
f3 = 'buzz'
YourModel.where('f1 = ? and f2 = ?', f1, f2).each do |ym|
  # or where(f1: f1, f2: f2).each do (...)
  ym.update(f3: f3) 
end

If you don't have a model for it (just the table), you can create a file and model that will inherit from ActiveRecord::Base

class YourTable < ActiveRecord::Base
  self.table_name = 'your_table' # specify explicitly if needed
end

and again use where the same as above:

Getting multiple keys of specified value of a generic Dictionary?

Dictionaries aren't really meant to work like this, because while uniqueness of keys is guaranteed, uniqueness of values isn't. So e.g. if you had

var greek = new Dictionary<int, string> { { 1, "Alpha" }, { 2, "Alpha" } };

What would you expect to get for greek.WhatDoIPutHere("Alpha")?

Therefore you can't expect something like this to be rolled into the framework. You'd need your own method for your own unique uses---do you want to return an array (or IEnumerable<T>)? Do you want to throw an exception if there are multiple keys with the given value? What about if there are none?

Personally I'd go for an enumerable, like so:

IEnumerable<TKey> KeysFromValue<TKey, TValue>(this Dictionary<TKey, TValue> dict, TValue val)
{
    if (dict == null)
    {
        throw new ArgumentNullException("dict");
    }
    return dict.Keys.Where(k => dict[k] == val);
}

var keys = greek.KeysFromValue("Beta");
int exceptionIfNotExactlyOne = greek.KeysFromValue("Beta").Single();

How to format x-axis time scale values in Chart.js v2

I had a different use case, I want different formats based how long between start and end time of data in graph. I found this to be simplest approach

    xAxes = {
        type: "time",
        time: {
            displayFormats: {
                hour: "hA"
            }
        },
        display: true,
        ticks: {
            reverse: true
        },
        gridLines: {display: false}
    }
    // if more than two days between start and end of data,  set format to show date,  not hrs
    if ((parseInt(Cookies.get("epoch_max")) - parseInt(Cookies.get("epoch_min"))) > (1000*60*60*24*2)) {
        xAxes.time.displayFormats.hour = "MMM D";
    }

Import cycle not allowed

This is a circular dependency issue. Golang programs must be acyclic. In Golang cyclic imports are not allowed (That is its import graph must not contain any loops)

Lets say your project go-circular-dependency have 2 packages "package one" & it has "one.go" & "package two" & it has "two.go" So your project structure is as follows

+--go-circular-dependency    
      +--one    
         +-one.go
      +--two        
         +-two.go

This issue occurs when you try to do something like following.

Step 1 - In one.go you import package two (Following is one.go)

package one

import (
    "go-circular-dependency/two"
)

//AddOne is
func AddOne() int {
    a := two.Multiplier()
    return a + 1
}

Step 2 - In two.go you import package one (Following is two.go)

package two

import (
    "fmt"
    "go-circular-dependency/one"
)

//Multiplier is going to be used in package one
func Multiplier() int {
    return 2
}

//Total is
func Total() {
    //import AddOne from "package one"
    x := one.AddOne()
    fmt.Println(x)
}

In Step 2, you will receive an error "can't load package: import cycle not allowed" (This is called "Circular Dependency" error)

Technically speaking this is bad design decision and you should avoid this as much as possible, but you can "Break Circular Dependencies via implicit interfaces" (I personally don't recommend, and highly discourage this practise, because by design Go programs must be acyclic)

Try to keep your import dependency shallow. When the dependency graph becomes deeper (i.e package x imports y, y imports z, z imports x) then circular dependencies become more likely.

Sometimes code repetition is not bad idea, which is exactly opposite of DRY (don't repeat yourself)

So in Step 2 that is in two.go you should not import package one. Instead in two.go you should actually replicate the functionality of AddOne() written in one.go as follows.

package two

import (
    "fmt"
)

//Multiplier is going to be used in package one
func Multiplier() int {
    return 2
}

//Total is
func Total() {
    // x := one.AddOne()
    x := Multiplier() + 1
    fmt.Println(x)
}

How can I restart a Java application?

Windows

public void restartApp(){

    // This launches a new instance of application dirctly, 
    // remember to add some sleep to the start of the cmd file to make sure current instance is
    // completely terminated, otherwise 2 instances of the application can overlap causing strange
    // things:)

    new ProcessBuilder("cmd","/c start /min c:/path/to/script/that/launches/my/application.cmd ^& exit").start();
    System.exit(0);
}

/min to start script in minimized window

^& exit to close cmd window after finish

a sample cmd script could be

@echo off
rem add some sleep (e.g. 10 seconds) to allow the preceding application instance to release any open resources (like ports) and exit gracefully, otherwise the new instance could fail to start
sleep 10   
set path=C:\someFolder\application_lib\libs;%path%
java -jar application.jar

sleep 10 sleep for 10 seconds

Load view from an external xib file in storyboard

My full example is here, but I will provide a summary below.

Layout

Add a .swift and .xib file each with the same name to your project. The .xib file contains your custom view layout (using auto layout constraints preferably).

Make the swift file the xib file's owner.

enter image description here Code

Add the following code to the .swift file and hook up the outlets and actions from the .xib file.

import UIKit
class ResuableCustomView: UIView {

    let nibName = "ReusableCustomView"
    var contentView: UIView?

    @IBOutlet weak var label: UILabel!
    @IBAction func buttonTap(_ sender: UIButton) {
        label.text = "Hi"
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        guard let view = loadViewFromNib() else { return }
        view.frame = self.bounds
        self.addSubview(view)
        contentView = view
    }

    func loadViewFromNib() -> UIView? {
        let bundle = Bundle(for: type(of: self))
        let nib = UINib(nibName: nibName, bundle: bundle)
        return nib.instantiate(withOwner: self, options: nil).first as? UIView
    }
}

Use it

Use your custom view anywhere in your storyboard. Just add a UIView and set the class name to your custom class name.

enter image description here


For a while Christopher Swasey's approach was the best approach I had found. I asked a couple of the senior devs on my team about it and one of them had the perfect solution! It satisfies every one of the concerns that Christopher Swasey so eloquently addressed and it doesn't require boilerplate subclass code(my main concern with his approach). There is one gotcha, but other than that it is fairly intuitive and easy to implement.

  1. Create a custom UIView class in a .swift file to control your xib. i.e. MyCustomClass.swift
  2. Create a .xib file and style it as you want. i.e. MyCustomClass.xib
  3. Set the File's Owner of the .xib file to be your custom class (MyCustomClass)
  4. GOTCHA: leave the class value (under the identity Inspector) for your custom view in the .xib file blank. So your custom view will have no specified class, but it will have a specified File's Owner.
  5. Hook up your outlets as you normally would using the Assistant Editor.
    • NOTE: If you look at the Connections Inspector you will notice that your Referencing Outlets do not reference your custom class (i.e. MyCustomClass), but rather reference File's Owner. Since File's Owner is specified to be your custom class, the outlets will hook up and work propery.
  6. Make sure your custom class has @IBDesignable before the class statement.
  7. Make your custom class conform to the NibLoadable protocol referenced below.
    • NOTE: If your custom class .swift file name is different from your .xib file name, then set the nibName property to be the name of your .xib file.
  8. Implement required init?(coder aDecoder: NSCoder) and override init(frame: CGRect) to call setupFromNib() like the example below.
  9. Add a UIView to your desired storyboard and set the class to be your custom class name (i.e. MyCustomClass).
  10. Watch IBDesignable in action as it draws your .xib in the storyboard with all of it's awe and wonder.

Here is the protocol you will want to reference:

public protocol NibLoadable {
    static var nibName: String { get }
}

public extension NibLoadable where Self: UIView {

    public static var nibName: String {
        return String(describing: Self.self) // defaults to the name of the class implementing this protocol.
    }

    public static var nib: UINib {
        let bundle = Bundle(for: Self.self)
        return UINib(nibName: Self.nibName, bundle: bundle)
    }

    func setupFromNib() {
        guard let view = Self.nib.instantiate(withOwner: self, options: nil).first as? UIView else { fatalError("Error loading \(self) from nib") }
        addSubview(view)
        view.translatesAutoresizingMaskIntoConstraints = false
        view.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor, constant: 0).isActive = true
        view.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true
        view.trailingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.trailingAnchor, constant: 0).isActive = true
        view.bottomAnchor.constraint(equalTo: self.safeAreaLayoutGuide.bottomAnchor, constant: 0).isActive = true
    }
}

And here is an example of MyCustomClass that implements the protocol (with the .xib file being named MyCustomClass.xib):

@IBDesignable
class MyCustomClass: UIView, NibLoadable {

    @IBOutlet weak var myLabel: UILabel!

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupFromNib()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupFromNib()
    }

}

NOTE: If you miss the Gotcha and set the class value inside your .xib file to be your custom class, then it will not draw in the storyboard and you will get a EXC_BAD_ACCESS error when you run the app because it gets stuck in an infinite loop of trying to initialize the class from the nib using the init?(coder aDecoder: NSCoder) method which then calls Self.nib.instantiate and calls the init again.

Split text file into smaller multiple text file using command line

I know the question has been asked a long time ago, but I am surprised that nobody has given the most straightforward unix answer:

split -l 5000 -d --additional-suffix=.txt $FileName file
  • -l 5000: split file into files of 5,000 lines each.
  • -d: numerical suffix. This will make the suffix go from 00 to 99 by default instead of aa to zz.
  • --additional-suffix: lets you specify the suffix, here the extension
  • $FileName: name of the file to be split.
  • file: prefix to add to the resulting files.

As always, check out man split for more details.

For Mac, the default version of split is apparently dumbed down. You can install the GNU version using the following command. (see this question for more GNU utils)

brew install coreutils

and then you can run the above command by replacing split with gsplit. Check out man gsplit for details.

How to rotate x-axis tick labels in Pandas barplot

Pass param rot=0 to rotate the xticks:

import matplotlib
matplotlib.style.use('ggplot')
import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({ 'celltype':["foo","bar","qux","woz"], 's1':[5,9,1,7], 's2':[12,90,13,87]})
df = df[["celltype","s1","s2"]]
df.set_index(["celltype"],inplace=True)
df.plot(kind='bar',alpha=0.75, rot=0)
plt.xlabel("")
plt.show()

yields plot:

enter image description here

Git error: src refspec master does not match any error: failed to push some refs

It doesn't recognize that you have a master branch, but I found a way to get around it. I found out that there's nothing special about a master branch, you can just create another branch and call it master branch and that's what I did.

To create a master branch:

git checkout -b master

And you can work off of that.

How to Execute a Python File in Notepad ++?

I usually prefer running my python scripts on python native IDLE interactive shell rather than from command prompt or something like that. I've tried it, and it works for me. Just open "Run > Run...", then paste the code below

python  -m idlelib.idle -r "$(FULL_CURRENT_PATH)"

After that, you can save it with your hotkey.

You must ensure your desired python is added and registered in your environment variables.

HTTP requests and JSON parsing in Python

Try this:

import requests
import json

# Goole Maps API.
link = 'http://maps.googleapis.com/maps/api/directions/json?origin=Chicago,IL&destination=Los+Angeles,CA&waypoints=Joplin,MO|Oklahoma+City,OK&sensor=false'

# Request data from link as 'str'
data = requests.get(link).text

# convert 'str' to Json
data = json.loads(data)

# Now you can access Json 
for i in data['routes'][0]['legs'][0]['steps']:
    lattitude = i['start_location']['lat']
    longitude = i['start_location']['lng']
    print('{}, {}'.format(lattitude, longitude))

Why doesn't GCC optimize a*a*a*a*a*a to (a*a*a)*(a*a*a)?

I would not have expected this case to be optimized at all. It can't be very often where an expression contains subexpressions that can be regrouped to remove entire operations. I would expect compiler writers to invest their time in areas which would be more likely to result in noticeable improvements, rather than covering a rarely encountered edge case.

I was surprised to learn from the other answers that this expression could indeed be optimized with the proper compiler switches. Either the optimization is trivial, or it is an edge case of a much more common optimization, or the compiler writers were extremely thorough.

There's nothing wrong with providing hints to the compiler as you've done here. It's a normal and expected part of the micro-optimization process to rearrange statements and expressions to see what differences they will bring.

While the compiler may be justified in considering the two expressions to deliver inconsistent results (without the proper switches), there's no need for you to be bound by that restriction. The difference will be incredibly tiny - so much so that if the difference matters to you, you should not be using standard floating point arithmetic in the first place.

select the TOP N rows from a table

Assuming your page size is 20 record, and you wanna get page number 2, here is how you would do it:

SQL Server, Oracle:

SELECT *   -- <-- pick any columns here from your table, if you wanna exclude the RowNumber
FROM (SELECT ROW_NUMBER OVER(ORDER BY ID DESC) RowNumber, * 
      FROM Reflow  
      WHERE ReflowProcessID = somenumber) t
WHERE RowNumber >= 20 AND RowNumber <= 40    

MySQL:

SELECT * 
FROM Reflow  
WHERE ReflowProcessID = somenumber
ORDER BY ID DESC
LIMIT 20 OFFSET 20

How can I create a war file of my project in NetBeans?

This worked for me:

1.Right click pom.xml
2.Run Maven > Goals
3.Edit maven goals

enter image description here


Edit maven goals

Results: war build in /target folder

   Packaging webapp
    Assembling webapp [WeatherDashboard] in [C:\Users\julian.mojico\Documents\NetBeansProjects\WeatherDashboard\target\WeatherDashboard-1.0-SNAPSHOT]
    Processing war project
    Webapp assembled in [672 msecs]
    Building war: C:\Users\julian.mojico\Documents\NetBeansProjects\WeatherDashboard\target\WeatherDashboard-1.0-SNAPSHOT.war
    ------------------------------------------------------------------------
    BUILD SUCCESS
    ------------------------------------------------------------------------
    Total time: 1:41.633s
    Finished at: Tue Sep 05 09:41:27 ART 2017
    Final Memory: 18M/97M
    ------------------------------------------------------------------------

Could not read JSON: Can not deserialize instance of hello.Country[] out of START_OBJECT token

If you want to avoid using an extra Class and List<Object> genomes you could simply use a Map.

The data structure translates into Map<String, List<Country>>

String resourceEndpoint = "http://api.geonames.org/countryInfoJSON?username=volodiaL";

Map<String, List<Country>> geonames = restTemplate.getForObject(resourceEndpoint, Map.class);

List<Country> countries = geonames.get("geonames");

Composer - the requested PHP extension mbstring is missing from your system

I set the PHPRC variable and uncommented zend_extension=php_opcache.dll in php.ini and all works well.

What is the difference between task and thread?

I usually use Task to interact with Winforms and simple background worker to make it not freezing the UI. here an example when I prefer using Task

private async void buttonDownload_Click(object sender, EventArgs e)
{
    buttonDownload.Enabled = false;
    await Task.Run(() => {
        using (var client = new WebClient())
        {
            client.DownloadFile("http://example.com/file.mpeg", "file.mpeg");
        }
    })
    buttonDownload.Enabled = true;
}

VS

private void buttonDownload_Click(object sender, EventArgs e)
{
    buttonDownload.Enabled = false;
    Thread t = new Thread(() =>
    {
        using (var client = new WebClient())
        {
            client.DownloadFile("http://example.com/file.mpeg", "file.mpeg");
        }
        this.Invoke((MethodInvoker)delegate()
        {
            buttonDownload.Enabled = true;
        });
    });
    t.IsBackground = true;
    t.Start();
}

the difference is you don't need to use MethodInvoker and shorter code.

Pass Javascript Variable to PHP POST

There is a lot of ways to achieve this. In regards to the way you are asking, with a hidden form element.

create this form element inside your form:

<input type="hidden" name="total" value="">

So your form like this:

<form id="sampleForm" name="sampleForm" method="post" action="phpscript.php">
<input type="hidden" name="total" id="total" value="">
<a href="#" onclick="setValue();">Click to submit</a>
</form>

Then your javascript something like this:

<script>
function setValue(){
    document.sampleForm.total.value = 100;
    document.forms["sampleForm"].submit();
}
</script>

Changing an element's ID with jQuery

I'm not sure what your goal is, but might it be better to use addClass instead? I mean an objects ID in my opinion should be static and specific to that object. If you are just trying to change it from showing on the page or something like that I would put those details in a class and then add it to the object rather then trying to change it's ID. Again, I'm saying that without understand your underlining goal.

How to replace substrings in windows batch file

Expanding from Andriy M, and yes you can do this from a file, even one with multiple lines

@echo off
setlocal EnableExtensions EnableDelayedExpansion
set "INTEXTFILE=test.txt"
set "OUTTEXTFILE=test_out.txt"
set "SEARCHTEXT=bath"
set "REPLACETEXT=hello"

for /f "delims=" %%A in ('type "%INTEXTFILE%"') do (
    set "string=%%A"
    set "modified=!string:%SEARCHTEXT%=%REPLACETEXT%!"
    echo !modified!>>"%OUTTEXTFILE%"
)

del "%INTEXTFILE%"
rename "%OUTTEXTFILE%" "%INTEXTFILE%"
endlocal

EDIT

Thanks David Nelson, I have updated the script so it doesn't have the hard coded values anymore.

Using getline() in C++

int main(){
.... example with file
     //input is a file
    if(input.is_open()){
        cin.ignore(1,'\n'); //it ignores everything after new line
        cin.getline(buffer,255); // save it in buffer
        input<<buffer; //save it in input(it's a file)
        input.close();
    }
}

What is the meaning of "this" in Java?

this refers to the current object.

Each non-static method runs in the context of an object. So if you have a class like this:

public class MyThisTest {
  private int a;

  public MyThisTest() {
    this(42); // calls the other constructor
  }

  public MyThisTest(int a) {
    this.a = a; // assigns the value of the parameter a to the field of the same name
  }

  public void frobnicate() {
    int a = 1;

    System.out.println(a); // refers to the local variable a
    System.out.println(this.a); // refers to the field a
    System.out.println(this); // refers to this entire object
  }

  public String toString() {
    return "MyThisTest a=" + a; // refers to the field a
  }
}

Then calling frobnicate() on new MyThisTest() will print

1
42
MyThisTest a=42

So effectively you use it for multiple things:

  • clarify that you are talking about a field, when there's also something else with the same name as a field
  • refer to the current object as a whole
  • invoke other constructors of the current class in your constructor

Passing data between view controllers

I have seen a lot of people over complicating this using the didSelectRowAtPath method. I am using Core Data in my example.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    // This solution is for using Core Data
    YourCDEntityName * value = (YourCDEntityName *)[[self fetchedResultsController] objectAtIndexPath: indexPath];

    YourSecondViewController * details = [self.storyboard instantiateViewControllerWithIdentifier:@"nameOfYourSecondVC"]; // Make sure in storyboards you give your second VC an identifier

    // Make sure you declare your value in the second view controller
    details.selectedValue = value;

    // Now that you have said to pass value all you need to do is change views
    [self.navigationController pushViewController: details animated:YES];

}

Four lines of code inside the method and you are done.

Placeholder in UITextView

It is not possible to create placeholder in UITextView but you can generate effect like place holder by this.

  - (void)viewDidLoad{      
              commentTxtView.text = @"Comment";
              commentTxtView.textColor = [UIColor lightGrayColor];
              commentTxtView.delegate = self;

     }
       - (BOOL) textViewShouldBeginEditing:(UITextView *)textView
     {
         commentTxtView.text = @"";
         commentTxtView.textColor = [UIColor blackColor];
         return YES;
     }

     -(void) textViewDidChange:(UITextView *)textView
     {

    if(commentTxtView.text.length == 0){
        commentTxtView.textColor = [UIColor lightGrayColor];
        commentTxtView.text = @"Comment";
        [commentTxtView resignFirstResponder];
    }
    }

OR you can add label in textview just like

       lbl = [[UILabel alloc] initWithFrame:CGRectMake(10.0, 0.0,textView.frame.size.width - 10.0, 34.0)];


[lbl setText:kDescriptionPlaceholder];
[lbl setBackgroundColor:[UIColor clearColor]];
[lbl setTextColor:[UIColor lightGrayColor]];
textView.delegate = self;

[textView addSubview:lbl];

and set

- (void)textViewDidEndEditing:(UITextView *)theTextView
{
     if (![textView hasText]) {
     lbl.hidden = NO;
}
}

- (void) textViewDidChange:(UITextView *)textView
{
    if(![textView hasText]) {
      lbl.hidden = NO;
}
else{
    lbl.hidden = YES;
 }  
}

What is NODE_ENV and how to use it in Express?

NODE_ENV is an environmental variable that stands for node environment in express server.

It's how we set and detect which environment we are in.

It's very common using production and development.

Set:

export NODE_ENV=production

Get:

You can get it using app.get('env')

How do I count the number of occurrences of a char in a String?

I see a lot of tricks and such being used. Now I'm not against beautiful tricks but personally I like to simply call the methods that are meant to do the work, so I've created yet another answer.

Note that if performance is any issue, use Jon Skeet's answer instead. This one is a bit more generalized and therefore slightly more readable in my opinion (and of course, reusable for strings and patterns).

public static int countOccurances(char c, String input) {
    return countOccurancesOfPattern(Pattern.quote(Character.toString(c)), input);
}

public static int countOccurances(String s, String input) {
    return countOccurancesOfPattern(Pattern.quote(s), input);
}

public static int countOccurancesOfPattern(String pattern, String input) {
    Matcher m = Pattern.compile(pattern).matcher(input);
    int count = 0;
    while (m.find()) {
        count++;
    }
    return count;
}

How to enter in a Docker container already running with a new TTY

I started powershell on a running microsoft/iis run as daemon using

docker exec -it <nameOfContainer> powershell