Programs & Examples On #Nsdictionary

A member of Apple's Objective-C framework Cocoa. NSDictionary objects manage associations of keys and values.

How to append elements into a dictionary in Swift?

SWIFT 3 - XCODE 8.1

var dictionary =  [Int:String]() 

dictionary.updateValue(value: "Hola", forKey: 1)
dictionary.updateValue(value: "Hello", forKey: 2)
dictionary.updateValue(value: "Aloha", forKey: 3)

So, your dictionary contains:

dictionary[1: Hola, 2: Hello, 3: Aloha]

adding multiple entries to a HashMap at once in one statement

    boolean x;
    for (x = false, 
        map.put("One", new Integer(1)), 
        map.put("Two", new Integer(2)),      
        map.put("Three", new Integer(3)); x;);

Ignoring the declaration of x (which is necessary to avoid an "unreachable statement" diagnostic), technically it's only one statement.

for each loop in Objective-C for accessing NSMutable dictionary

You can use -[NSDictionary allKeys] to access all the keys and loop through it.

How can we store into an NSDictionary? What is the difference between NSDictionary and NSMutableDictionary?

NSDictionary   *dict = [NSDictionary dictionaryWithObject: @"String" forKey: @"Test"];
NSMutableDictionary *anotherDict = [NSMutableDictionary dictionary];

[anotherDict setObject: dict forKey: "sub-dictionary-key"];
[anotherDict setObject: @"Another String" forKey: @"another test"];

NSLog(@"Dictionary: %@, Mutable Dictionary: %@", dict, anotherDict);

// now we can save these to a file
NSString   *savePath = [@"~/Documents/Saved.data" stringByExpandingTildeInPath];
[anotherDict writeToFile: savePath atomically: YES];

//and restore them
NSMutableDictionary  *restored = [NSDictionary dictionaryWithContentsOfFile: savePath];

Converting NSString to NSDictionary / JSON

I think you get the array from response so you have to assign response to array.

NSError *err = nil;
NSArray *array = [NSJSONSerialization JSONObjectWithData:[string dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];
NSDictionary *dictionary = [array objectAtIndex:0];
NSString *test = [dictionary objectForKey:@"ID"];
NSLog(@"Test is %@",test);

NSDictionary - Need to check whether dictionary contains key-value pair or not

Just ask it for the objectForKey:@"b". If it returns nil, no object is set at that key.

if ([xyz objectForKey:@"b"]) {
    NSLog(@"There's an object set for key @\"b\"!");
} else {
    NSLog(@"No object set for key @\"b\"");
}

Edit: As to your edited second question, it's simply NSUInteger mCount = [xyz count];. Both of these answers are documented well and easily found in the NSDictionary class reference ([1] [2]).

How to use NSJSONSerialization

The following code fetches a JSON object from a webserver, and parses it to an NSDictionary. I have used the openweathermap API that returns a simple JSON response for this example. For keeping it simple, this code uses synchronous requests.

   NSString *urlString   = @"http://api.openweathermap.org/data/2.5/weather?q=London,uk"; // The Openweathermap JSON responder
   NSURL *url            = [[NSURL alloc]initWithString:urlString];
   NSURLRequest *request = [NSURLRequest requestWithURL:url];
   NSURLResponse *response;
   NSData *GETReply      = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
   NSDictionary *res     = [NSJSONSerialization JSONObjectWithData:GETReply options:NSJSONReadingMutableLeaves|| NSJSONReadingMutableContainers error:nil];
   Nslog(@"%@",res);

Is there a way to iterate over a dictionary?

The block approach avoids running the lookup algorithm for every key:

[dict enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL* stop) {
  NSLog(@"%@ => %@", key, value);
}];

Even though NSDictionary is implemented as a hashtable (which means that the cost of looking up an element is O(1)), lookups still slow down your iteration by a constant factor.

My measurements show that for a dictionary d of numbers ...

NSMutableDictionary* dict = [NSMutableDictionary dictionary];
for (int i = 0; i < 5000000; ++i) {
  NSNumber* value = @(i);
  dict[value.stringValue] = value;
}

... summing up the numbers with the block approach ...

__block int sum = 0;
[dict enumerateKeysAndObjectsUsingBlock:^(NSString* key, NSNumber* value, BOOL* stop) {
  sum += value.intValue;
}];

... rather than the loop approach ...

int sum = 0;
for (NSString* key in dict)
  sum += [dict[key] intValue];

... is about 40% faster.

EDIT: The new SDK (6.1+) appears to optimise loop iteration, so the loop approach is now about 20% faster than the block approach, at least for the simple case above.

convert NSDictionary to NSString

You can call [aDictionary description], or anywhere you would need a format string, just use %@ to stand in for the dictionary:

[NSString stringWithFormat:@"my dictionary is %@", aDictionary];

or

NSLog(@"My dictionary is %@", aDictionary);

How to add to an NSDictionary

By setting you'd use setValue:(id)value forKey:(id)key method of NSMutableDictionary object:

NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setValue:[NSNumber numberWithInt:5] forKey:@"age"];

Or in modern Objective-C:

NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
dict[@"age"] = @5;

The difference between mutable and "normal" is, well, mutability. I.e. you can alter the contents of NSMutableDictionary (and NSMutableArray) while you can't do that with "normal" NSDictionary and NSArray

How can I convert NSDictionary to NSData and vice versa?

NSDictionary -> NSData:

NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:yourDictionary forKey:@"Some Key Value"];
[archiver finishEncoding];
[archiver release];

// Here, data holds the serialized version of your dictionary
// do what you need to do with it before you:
[data release];

NSData -> NSDictionary

NSData *data = [[NSMutableData alloc] initWithContentsOfFile:[self dataFilePath]];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
NSDictionary *myDictionary = [[unarchiver decodeObjectForKey:@"Some Key Value"] retain];
[unarchiver finishDecoding];
[unarchiver release];
[data release];

You can do that with any class that conforms to NSCoding.

source

How do I deserialize a JSON string into an NSDictionary? (For iOS 5+)

Using Abizern code for swift 2.2

let objectData = responseString!.dataUsingEncoding(NSUTF8StringEncoding)
let json = try NSJSONSerialization.JSONObjectWithData(objectData!, options: NSJSONReadingOptions.MutableContainers)

NSDictionary to NSArray?

Leaving aside the technical issues with the code you posted, you asked this:

To use this Dictionary Items in a Table View i have to transfer it to a NSArray, am i right?

The answer to which is: not necessarily. There's nothing intrinsic to the machinery of UITableView, UITableViewDataSource, or UITableViewDelegate that means that your data has to be in an array. You will need to implement various methods to tell the system how many rows are in your table, and what data appears in each row. Many people find it much more natural and efficient to answer those questions with an ordered data structure like an array. But there's no requirement that you do so. If you can write the code to implement those methods with the dictionary you started with, feel free!

Using NSPredicate to filter an NSArray based on NSDictionary keys

It should work - as long as the data variable is actually an array containing a dictionary with the key SPORT

NSArray *data = [NSArray arrayWithObject:[NSMutableDictionary dictionaryWithObject:@"foo" forKey:@"BAR"]];    
NSArray *filtered = [data filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(BAR == %@)", @"foo"]];

Filtered in this case contains the dictionary.

(the %@ does not have to be quoted, this is done when NSPredicate creates the object.)

error: cast from 'void*' to 'int' loses precision

//new_fd is a int
pthread_create(&threads[threads_in_use] , NULL, accept_request, (void*)((long)new_fd));

//inside the method I then have
int client;
client = (long)new_fd;

Hope this helps

XPath: How to select elements based on their value?

The condition below:

//Element[@attribute1="abc" and @attribute2="xyz" and Data]

checks for the existence of the element Data within Element and not for element value Data.

Instead you can use

//Element[@attribute1="abc" and @attribute2="xyz" and text()="Data"]

How can I use jQuery in Greasemonkey?

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

The Completest Cocos2d-x Tutorial & Guide List

Good list. The Angry Ninjas Starter Kit will have a Cocos2d-X update soon.

iPhone app could not be installed at this time

I had the same problem as @mohitum007. In my case the developer of this App included an expiry date in it.

As workaround I set the date backwards to a past date (e.g. last month). Then I could install it and use it.

Also when I set the date back to normal, the already installed App didn't start up anymore. I contacted the company of this App to send me an updated version.

Sidenote: I found out that users from other Apps had the same problem but reversed: it won't install or start before a certain date.

Jquery- Get the value of first td in table

If you need to get all td's inside tr without defining id for them, you can use the code below :

var items = new Array();

$('#TABLE_ID td:nth-child(1)').each(function () {
      items.push($(this).html());
});

The code above will add all first cells inside the Table into an Array variable.

you can change nth-child(1) which means the first cell to any cell number you need.

hope this code helps you.

css to make bootstrap navbar transparent

What you people are doing is unnecessary.

For transparent background, simply do:

_x000D_
_x000D_
<div class="navbar">_x000D_
// your navbar content_x000D_
</div>
_x000D_
_x000D_
_x000D_

without class navbar-default or navbar-inverse.

Group by with multiple columns using lambda

I came up with a mix of defining a class like David's answer, but not requiring a Where class to go with it. It looks something like:

var resultsGroupings = resultsRecords.GroupBy(r => new { r.IdObj1, r.IdObj2, r.IdObj3})
                                    .Select(r => new ResultGrouping {
                                        IdObj1= r.Key.IdObj1,
                                        IdObj2= r.Key.IdObj2,
                                        IdObj3= r.Key.IdObj3,
                                        Results = r.ToArray(),
                                        Count = r.Count()
                                    });



private class ResultGrouping
        {
            public short IdObj1{ get; set; }
            public short IdObj2{ get; set; }
            public int IdObj3{ get; set; }

            public ResultCsvImport[] Results { get; set; }
            public int Count { get; set; }
        }

Where resultRecords is my initial list I'm grouping, and its a List<ResultCsvImport>. Note that the idea here to is that, I'm grouping by 3 columns, IdObj1 and IdObj2 and IdObj3

jquery beforeunload when closing (not leaving) the page?

Try this, loading data via ajax and displaying through return statement.

<script type="text/javascript">
function closeWindow(){

    var Data = $.ajax({
        type : "POST",
        url : "file.txt",  //loading a simple text file for sample.
        cache : false,
        global : false,
        async : false,
        success : function(data) {
            return data;
        }

    }).responseText;


    return "Are you sure you want to leave the page? You still have "+Data+" items in your shopping cart";
}

window.onbeforeunload = closeWindow;
</script>

How can I create a dynamically sized array of structs?

Your code in the last update should not compile, much less run. You're passing &x to LoadData. &x has the type of **words, but LoadData expects words* . Of course it crashes when you call realloc on a pointer that's pointing into stack.

The way to fix it is to change LoadData to accept words** . Thi sway, you can actually modify the pointer in main(). For example, realloc call would look like

*x = (words*) realloc(*x, sizeof(words)*2);

It's the same principlae as in "num" being int* rather than int.

Besides this, you need to really figure out how the strings in words ere stored. Assigning a const string to char * (as in str2 = "marley\0") is permitted, but it's rarely the right solution, even in C.

Another point: non need to have "marley\0" unless you really need two 0s at the end of string. Compiler adds 0 tho the end of every string literal.

warning: implicit declaration of function

You are using a function for which the compiler has not seen a declaration ("prototype") yet.

For example:

int main()
{
    fun(2, "21"); /* The compiler has not seen the declaration. */       
    return 0;
}

int fun(int x, char *p)
{
    /* ... */
}

You need to declare your function before main, like this, either directly or in a header:

int fun(int x, char *p);

How do I use jQuery to redirect?

I found out why this happening.

After looking at my settings on my wamp, i did not check http headers, since activated this, it now works.

Thank you everyone for trying to solve this. :)

Setting attribute disabled on a SPAN element does not prevent click events

The best method is to wrap the span inside a button and disable the button

_x000D_
_x000D_
$("#buttonD").click(function(){_x000D_
  alert("button clicked");_x000D_
})_x000D_
_x000D_
$("#buttonS").click(function(){_x000D_
  alert("span clicked");_x000D_
})
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" />
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" />_x000D_
_x000D_
_x000D_
<button class="btn btn-success" disabled="disabled" id="buttonD">_x000D_
    <span>Disabled button</span>_x000D_
</button>_x000D_
_x000D_
<br>_x000D_
<br>_x000D_
_x000D_
 <span class="btn btn-danger" disabled="disabled" id="buttonS">Disabled span</span>
_x000D_
_x000D_
_x000D_

Difference between /res and /assets directories

Both are pretty similar. The real main difference between the two is that in the res directory each file is given a pre-compiled ID which can be accessed easily through R.id.[res id]. This is useful to quickly and easily access images, sounds, icons...

The assets directory is more like a filesystem and provides more freedom to put any file you would like in there. You then can access each of the files in that system as you would when accessing any file in any file system through Java. This directory is good for things such as game details, dictionaries,...etc. Hope that helps.

Use of alloc init instead of new

Very old question, but I've written some example just for fun — maybe you'll find it useful ;)

#import "InitAllocNewTest.h"

@implementation InitAllocNewTest

+(id)alloc{
    NSLog(@"Allocating...");
    return [super alloc];
}

-(id)init{
    NSLog(@"Initializing...");
    return [super init];
}

@end

In main function both statements:

[[InitAllocNewTest alloc] init];

and

[InitAllocNewTest new];

result in the same output:

2013-03-06 16:45:44.125 XMLTest[18370:207] Allocating...
2013-03-06 16:45:44.128 XMLTest[18370:207] Initializing...

How can I align YouTube embedded video in the center in bootstrap

<center><div class="video">
<iframe width="560" height="315" src="https://www.youtube.com/embed/ig3qHRVZRvM" frameborder="0" allowfullscreen=""></iframe>
</div></center>

It seems to work, is this all you were asking for? I guess you could go about taking longer more involved routes, but this seemed simple enough.

Detect all Firefox versions in JS

the best solution for me:

_x000D_
_x000D_
function GetIEVersion() {_x000D_
  var sAgent = window.navigator.userAgent;_x000D_
  var Idx = sAgent.indexOf("MSIE");_x000D_
  // If IE, return version number._x000D_
  if (Idx > 0)_x000D_
    return parseInt(sAgent.substring(Idx+ 5, sAgent.indexOf(".", Idx)));_x000D_
_x000D_
  // If IE 11 then look for Updated user agent string._x000D_
  else if (!!navigator.userAgent.match(/Trident\/7\./))_x000D_
    return 11;_x000D_
_x000D_
  else_x000D_
    return 0; //It is not IE_x000D_
_x000D_
}_x000D_
if (GetIEVersion() > 0){_x000D_
    alert("This is IE " + GetIEVersion());_x000D_
  }else {_x000D_
    alert("This no is IE ");_x000D_
  }  
_x000D_
_x000D_
_x000D_

MVC - Set selected value of SelectList

Further to @Womp answer, it's worth noting that the "Where" Can be dropped, and the predicate can be put into the "First" call directly, like this:

list.First(x => x.Value == "selectedValue").Selected = true;

Why doesn't TFS get latest get the latest?

Every time this happens to me (so far) is because I have local edits pending on the .csproj project file. That file seems to keep a list of all the files included in the project. Any new files added by somebody else are "not downloaded" because they are not in my locally edited (now stale) project file. To get all the files I first have to undo pending changes to the .csproj file first then "get all". I do not have to undo other changes I have made, but I may have to go back and include my new files again (and then the next guy gets the same problem when he tries to "get all"...)

It seems to me there is some fundamental kludginess when multiple people are adding new files at the same time.

(this is in .Net Framework projects, maybe the other frameworks like Core behave differently)

NoClassDefFoundError - Eclipse and Android

Try this:-

Step 1

Add all the libraries to build pat in Eclipse( means make all libraries referenced libraries)

Step 2

Delete R.java file and again build the project. Don't worry, R.java will automatically get recreated.

Chill :)

How to strip all whitespace from string

If optimal performance is not a requirement and you just want something dead simple, you can define a basic function to test each character using the string class's built in "isspace" method:

def remove_space(input_string):
    no_white_space = ''
    for c in input_string:
        if not c.isspace():
            no_white_space += c
    return no_white_space

Building the no_white_space string this way will not have ideal performance, but the solution is easy to understand.

>>> remove_space('strip my spaces')
'stripmyspaces'

If you don't want to define a function, you can convert this into something vaguely similar with list comprehension. Borrowing from the top answer's join solution:

>>> "".join([c for c in "strip my spaces" if not c.isspace()])
'stripmyspaces'

source command not found in sh shell

Bourne shell (sh) uses PATH to locate in source <file>. If the file you are trying to source is not in your path, you get the error 'file not found'.

Try:

source ./<filename>

IF-THEN-ELSE statements in postgresql

In general, an alternative to case when ... is coalesce(nullif(x,bad_value),y) (that cannot be used in OP's case). For example,

select coalesce(nullif(y,''),x), coalesce(nullif(x,''),y), *
from (     (select 'abc' as x, '' as y)
 union all (select 'def' as x, 'ghi' as y)
 union all (select '' as x, 'jkl' as y)
 union all (select null as x, 'mno' as y)
 union all (select 'pqr' as x, null as y)
) q

gives:

 coalesce | coalesce |  x  |  y  
----------+----------+-----+-----
 abc      | abc      | abc | 
 ghi      | def      | def | ghi
 jkl      | jkl      |     | jkl
 mno      | mno      |     | mno
 pqr      | pqr      | pqr | 
(5 rows)

init-param and context-param

<init-param> will be used if you want to initialize some parameter for a particular servlet. When request come to servlet first its init method will be called then doGet/doPost whereas if you want to initialize some variable for whole application you will need to use <context-param> . Every servlet will have access to the context variable.

Get Today's date in Java at midnight time

    Calendar c = new GregorianCalendar();
    c.set(Calendar.HOUR_OF_DAY, 0); //anything 0 - 23
    c.set(Calendar.MINUTE, 0);
    c.set(Calendar.SECOND, 0);
    Date d1 = c.getTime(); //the midnight, that's the first second of the day.

should be Fri Mar 09 00:00:00 IST 2012

Understanding the grid classes ( col-sm-# and col-lg-# ) in Bootstrap 3

"If I want two columns for anything over 768px, should I apply both classes?"

This should be as simple as:

<div class="row">
      <div class="col-sm-6"></div>
      <div class="col-sm-6"></div>    
</div>

No need to add the col-lg-6 too.

Demo: http://www.bootply.com/73119

Case Function Equivalent in Excel

Try this;

=IF(B1>=0, B1, OFFSET($X$1, MATCH(B1, $X:$X, Z) - 1, Y)

WHERE
X = The columns you are indexing into
Y = The number of columns to the left (-Y) or right (Y) of the indexed column to get the value you are looking for
Z = 0 if exact-match (if you want to handle errors)

submit form on click event using jquery

it's because the name of the submit button is named "submit", change it to anything but "submit", try "submitme" and retry it. It should then work.

How do I inject a controller into another controller in AngularJS

use typescript for your coding, because it's object oriented, strictly typed and easy to maintain the code ...

for more info about typescipt click here

Here one simple example I have created to share data between two controller using Typescript...

module Demo {
//create only one module for single Applicaiton
angular.module('app', []);
//Create a searvie to share the data
export class CommonService {
    sharedData: any;
    constructor() {
        this.sharedData = "send this data to Controller";
    }
}
//add Service to module app
angular.module('app').service('CommonService', CommonService);

//Create One controller for one purpose
export class FirstController {
    dataInCtrl1: any;
    //Don't forget to inject service to access data from service
    static $inject = ['CommonService']
    constructor(private commonService: CommonService) { }
    public getDataFromService() {
        this.dataInCtrl1 = this.commonService.sharedData;
    }
}
//add controller to module app
angular.module('app').controller('FirstController', FirstController);
export class SecondController {
    dataInCtrl2: any;
    static $inject = ['CommonService']
    constructor(private commonService: CommonService) { }
    public getDataFromService() {
        this.dataInCtrl2 = this.commonService.sharedData;
    }
}
angular.module('app').controller('SecondController', SecondController);

}

MYSQL query between two timestamps

Try this its worked for me

SELECT * from bookedroom
    WHERE UNIX_TIMESTAMP('2020-8-07 5:31')
        between UNIX_TIMESTAMP('2020-8-07 5:30') and
        UNIX_TIMESTAMP('2020-8-09 5:30')

How to add bootstrap in angular 6 project?

npm install bootstrap --save

and add relevent files into angular.json file under the style property for css files and under scripts for JS files.

 "styles": [
  "../node_modules/bootstrap/dist/css/bootstrap.min.css",
   ....
]

How can I access each element of a pair in a pair list?

You can access the members by their index in the tuple.

lst = [(1,'on'),(2,'onn'),(3,'onnn'),(4,'onnnn'),(5,'onnnnn')]

def unFld(x):

    for i in x:
        print(i[0],' ',i[1])

print(unFld(lst))

Output :

1    on

2    onn

3    onnn

4    onnnn

5    onnnnn

How do I add a new sourceset to Gradle?

If you're using

To get IntelliJ to recognize custom sourceset as test sources root:

plugin {
    idea
}

idea {
    module {
        testSourceDirs = testSourceDirs + sourceSets["intTest"].allJava.srcDirs
        testResourceDirs = testResourceDirs + sourceSets["intTest"].resources.srcDirs
    }
}

Reflection: How to Invoke Method with parameters

The provided solution does not work for instances of types loaded from a remote assembly. To do that, here is a solution that works in all situations, which involves an explicit type re-mapping of the type returned through the CreateInstance call.

This is how I need to create my classInstance, as it was located in a remote assembly.

// sample of my CreateInstance call with an explicit assembly reference
object classInstance = Activator.CreateInstance(assemblyName, type.FullName); 

However, even with the answer provided above, you'd still get the same error. Here is how to go about:

// first, create a handle instead of the actual object
ObjectHandle classInstanceHandle = Activator.CreateInstance(assemblyName, type.FullName);
// unwrap the real slim-shady
object classInstance = classInstanceHandle.Unwrap(); 
// re-map the type to that of the object we retrieved
type = classInstace.GetType(); 

Then do as the other users mentioned here.

Invariant Violation: _registerComponent(...): Target container is not a DOM element

If you use webpack for rendering your react and use HtmlWebpackPlugin in your react,this plugin builds its blank index.html by itself and injects js file in it,so it does not contain div element,as HtmlWebpackPlugin docs you can build your own index.html and give its address to this plugin, in my webpack.config.js

plugins: [            
    new HtmlWebpackPlugin({
        title: 'dev',
        template: 'dist/index.html'
    })
],

and this is my index.html file

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="shortcut icon" href="">
    <meta name="viewport" content="width=device-width">
    <title>Epos report</title>
</head>
<body>
   <div id="app"></div>
   <script src="./bundle.js"></script>
</body>
</html>

get UTC time in PHP

As previously answered here, since PHP 5.2.0 you can use the DateTime class and specify the UTC timezone with an instance of DateTimeZone.

The DateTime __construct() documentation suggests passing "now" as the first parameter when creating a DateTime instance and specifying a timezone to get the current time.

$date_utc = new \DateTime("now", new \DateTimeZone("UTC"));

echo $date_utc->format(\DateTime::RFC850); # Saturday, 18-Apr-15 03:23:46 UTC

How to write files to assets folder or raw folder in android?

Why not update the files on the local file system instead? You can read/write files into your applications sandboxed area.

http://developer.android.com/guide/topics/data/data-storage.html#filesInternal

Other alternatives you may want to look into are Shared Perferences and using Cache Files (all described at the link above)

Purpose of __repr__ method?

__repr__ is used by the standalone Python interpreter to display a class in printable format. Example:

~> python3.5
Python 3.5.1 (v3.5.1:37a07cee5969, Dec  5 2015, 21:12:44) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> class StackOverflowDemo:
...     def __init__(self):
...         pass
...     def __repr__(self):
...         return '<StackOverflow demo object __repr__>'
... 
>>> demo = StackOverflowDemo()
>>> demo
<StackOverflow demo object __repr__>

In cases where a __str__ method is not defined in the class, it will call the __repr__ function in an attempt to create a printable representation.

>>> str(demo)
'<StackOverflow demo object __repr__>'

Additionally, print()ing the class will call __str__ by default.


Documentation, if you please

What's the difference between commit() and apply() in SharedPreferences

  • commit() is synchronously, apply() is asynchronous

  • apply() is void function.

  • commit() returns true if the new values were successfully written to persistent storage.

  • apply() guarantees complete before switching states , you don't need to worry about Android component lifecycles

If you dont use value returned from commit() and you're using commit() from main thread, use apply() instead of commit()

Command copy exited with code 4 when building - Visual Studio restart solves it

If you are running Windows 7 onward, you can try the new 'robocopy' command:

robocopy "$(SolutionDir)Solution Items\References\*.dll" "$(TargetDir)"

More information about robocopy can be found here.

optional parameters in SQL Server stored proc?

Yes, it is. Declare parameter as so:

@Sort varchar(50) = NULL

Now you don't even have to pass the parameter in. It will default to NULL (or whatever you choose to default to).

Last element in .each() set

A shorter answer from here, adapted to this question:

var arr = $('.requiredText');
arr.each(function(index, item) {
   var is_last_item = (index == (arr.length - 1));
});

Just for completeness.

Inserting code in this LaTeX document with indentation

Here is how to add inline code:

You can add inline code with {\tt code } or \texttt{ code }. If you want to format the inline code, then it would be best to make your own command

\newcommand{\code}[1]{\texttt{#1}}

Also, note that code blocks can be loaded from other files with

\lstinputlisting[breaklines]{source.c}

breaklines isn't required, but I find it useful. Be aware that you'll have to specify \usepackage{ listings } for this one.

Update: The listings package also includes the \lstinline command, which has the same syntax highlighting features as the \lstlisting and \lstinputlisting commands (see Cloudanger's answer for configuration details). As mentioned in a few other answers, there's also the minted package, which provides the \mintinline command. Like \lstinline, \mintinline provides the same syntax highlighting as a regular minted code block:

\documentclass{article}

\usepackage{minted}

\begin{document}
  This is a sentence with \mintinline{python}{def inlineCode(a="ipsum)}
\end{document}

printing a value of a variable in postgresql

You can raise a notice in Postgres as follows:

raise notice 'Value: %', deletedContactId;

Read here

"A referral was returned from the server" exception when accessing AD from C#

Had the same issue and managed to resolve it.

In my case, I had an AD group in the current logon domain with members (users) from a sub domain. The server that I was running the code on could not access the domain controller of the sub domain (the server had never needed to access the sub domain before).

I struggled for a while as my desktop PC could access the domain so everything looked OK in the MMC plugin (Active Directory Users & Computers).

Hope that helps someone else.

How to have conditional elements and keep DRY with Facebook React's JSX?

Personally, I really think the ternary expressions show in (JSX In Depth) are the most natural way that conforms with the ReactJs standards.

See the following example. It's a little messy at first sight but works quite well.

<div id="page">
  {this.state.banner ? (
    <div id="banner">
     <div class="another-div">
       {this.state.banner}
     </div>
    </div>
  ) : 
  null} 
  <div id="other-content">
    blah blah blah...
  </div>
</div>

Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)

Below is the native PowerShell command for the most up-voted solution. Instead of: netsh advfirewall firewall set rule group="Windows Management Instrumentation (WMI)" new enable=yes

Use could use the slightly simpler syntax of:

Enable-NetFirewallRule -DisplayGroup "Windows Management Instrumentation (WMI-In)"

Resize svg when window is resized in d3.js

Use window.onresize:

function updateWindow(){
    x = w.innerWidth || e.clientWidth || g.clientWidth;
    y = w.innerHeight|| e.clientHeight|| g.clientHeight;

    svg.attr("width", x).attr("height", y);
}
d3.select(window).on('resize.updatesvg', updateWindow);

http://jsfiddle.net/Zb85u/1/

How to generate .json file with PHP?

You can simply use json_encode function of php and save file with file handling functions such as fopen and fwrite.

How to return a struct from a function in C++?

studentType newStudent() // studentType doesn't exist here
{   
    struct studentType // it only exists within the function
    {
        string studentID;
        string firstName;
        string lastName;
        string subjectName;
        string courseGrade;

        int arrayMarks[4];

        double avgMarks;

    } newStudent;
...

Move it outside the function:

struct studentType
{
    string studentID;
    string firstName;
    string lastName;
    string subjectName;
    string courseGrade;

    int arrayMarks[4];

    double avgMarks;

};

studentType newStudent()
{
    studentType newStudent
    ...
    return newStudent;
}

Why does AngularJS include an empty option in select?

Simple solution

<select ng-model='form.type' required><options>
<option ng-repeat="tp in typeOptions" ng-selected="    
{{form.type==tp.value?true:false}}" value="{{tp.value}}">{{tp.name}}</option>

PHP Fatal error: Using $this when not in object context

It seems to me to be a bug in PHP. The error

'Fatal error: Uncaught Error: Using $this when not in object context in'

appears in the function using $this, but the error is that the calling function is using non-static function as a static. I.e:

Class_Name
{
    function foo()
    {
        $this->do_something(); // The error appears there.
    }
    function do_something()
    {
        ///
    }
}

While the error is here:

Class_Name::foo();

check the null terminating character in char*

To make this complete: while others now solved your problem :) I would like to give you a piece of good advice: don't reinvent the wheel.

size_t forward_length = strlen(forward);

using BETWEEN in WHERE condition

$this->db->where('accommodation BETWEEN '' . $sdate . '' AND '' . $edate . ''');

this is my solution

Mongoose's find method with $or condition does not work properly

According to mongoDB documentation: "...That is, for MongoDB to use indexes to evaluate an $or expression, all the clauses in the $or expression must be supported by indexes."

So add indexes for your other fields and it will work. I had a similar problem and this solved it.

You can read more here: https://docs.mongodb.com/manual/reference/operator/query/or/

AndroidStudio: Failed to sync Install build tools

Go to File > Project Structure > Select Module > Properties you will landing to this screenenter image description here

Select Build Tools Version same as version selected in Compile Sdk Version.

Hope this will resolve your issue.

Check last modified date of file in C#

Be aware that the function File.GetLastWriteTime does not always work as expected, the values are sometimes not instantaneously updated by the OS. You may get an old Timestamp, even if the file has been modified right before.

The behaviour may vary between OS versions. For example, this unit test worked well every time on my developer machine, but it always fails on our build server.

  [TestMethod]
  public void TestLastModifiedTimeStamps()
  {
     var tempFile = Path.GetTempFileName();
     var lastModified = File.GetLastWriteTime(tempFile);
     using (new FileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.None))
     {

     }
     Assert.AreNotEqual(lastModified, File.GetLastWriteTime(tempFile));
  }

See File.GetLastWriteTime seems to be returning 'out of date' value

Your options:

a) live with the occasional omissions.

b) Build up an active component realising the observer pattern (eg. a tcp server client structure), communicating the changes directly instead of writing / reading files. Fast and flexible, but another dependency and a possible point of failure (and some work, of course).

c) Ensure the signalling process by replacing the content of a dedicated signal file that other processes regularly read. It´s not that smart as it´s a polling procedure and has a greater overhead than calling File.GetLastWriteTime, but if not checking the content from too many places too often, it will do the work.

/// <summary>
/// type to set signals or check for them using a central file 
/// </summary>
public class FileSignal
{
    /// <summary>
    /// path to the central file for signal control
    /// </summary>
    public string FilePath { get; private set; }

    /// <summary>
    /// numbers of retries when not able to retrieve (exclusive) file access
    /// </summary>
    public int MaxCollisions { get; private set; }

    /// <summary>
    /// timespan to wait until next try
    /// </summary>
    public TimeSpan SleepOnCollisionInterval { get; private set; }

    /// <summary>
    /// Timestamp of the last signal
    /// </summary>
    public DateTime LastSignal { get; private set; }

    /// <summary>
    /// constructor
    /// </summary>
    /// <param name="filePath">path to the central file for signal control</param>
    /// <param name="maxCollisions">numbers of retries when not able to retrieve (exclusive) file access</param>
    /// <param name="sleepOnCollisionInterval">timespan to wait until next try </param>
    public FileSignal(string filePath, int maxCollisions, TimeSpan sleepOnCollisionInterval)
    {
        FilePath = filePath;
        MaxCollisions = maxCollisions;
        SleepOnCollisionInterval = sleepOnCollisionInterval;
        LastSignal = GetSignalTimeStamp();
    }

    /// <summary>
    /// constructor using a default value of 50 ms for sleepOnCollisionInterval
    /// </summary>
    /// <param name="filePath">path to the central file for signal control</param>
    /// <param name="maxCollisions">numbers of retries when not able to retrieve (exclusive) file access</param>        
    public FileSignal(string filePath, int maxCollisions): this (filePath, maxCollisions, TimeSpan.FromMilliseconds(50))
    {
    }

    /// <summary>
    /// constructor using a default value of 50 ms for sleepOnCollisionInterval and a default value of 10 for maxCollisions
    /// </summary>
    /// <param name="filePath">path to the central file for signal control</param>        
    public FileSignal(string filePath) : this(filePath, 10)
    {
    }

    private Stream GetFileStream(FileAccess fileAccess)
    {
        var i = 0;
        while (true)
        {
            try
            {
                return new FileStream(FilePath, FileMode.Create, fileAccess, FileShare.None);
            }
            catch (Exception e)
            {
                i++;
                if (i >= MaxCollisions)
                {
                    throw e;
                }
                Thread.Sleep(SleepOnCollisionInterval);
            };
        };
    }

    private DateTime GetSignalTimeStamp()
    {
        if (!File.Exists(FilePath))
        {
            return DateTime.MinValue;
        }
        using (var stream = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.None))
        {
            if(stream.Length == 0)
            {
                return DateTime.MinValue;
            }
            using (var reader = new BinaryReader(stream))
            {
                return DateTime.FromBinary(reader.ReadInt64());
            };                
        }
    }

    /// <summary>
    /// overwrites the existing central file and writes the current time into it.
    /// </summary>
    public void Signal()
    {
        LastSignal = DateTime.Now;
        using (var stream = new FileStream(FilePath, FileMode.Create, FileAccess.Write, FileShare.None))
        {
            using (var writer = new BinaryWriter(stream))
            {
                writer.Write(LastSignal.ToBinary());
            }
        }
    }

    /// <summary>
    /// returns true if the file signal has changed, otherwise false.
    /// </summary>        
    public bool CheckIfSignalled()
    {
        var signal = GetSignalTimeStamp();
        var signalTimestampChanged = LastSignal != signal;
        LastSignal = signal;
        return signalTimestampChanged;
    }
}

Some tests for it:

    [TestMethod]
    public void TestSignal()
    {
        var fileSignal = new FileSignal(Path.GetTempFileName());
        var fileSignal2 = new FileSignal(fileSignal.FilePath);
        Assert.IsFalse(fileSignal.CheckIfSignalled());
        Assert.IsFalse(fileSignal2.CheckIfSignalled());
        Assert.AreEqual(fileSignal.LastSignal, fileSignal2.LastSignal);
        fileSignal.Signal();
        Assert.IsFalse(fileSignal.CheckIfSignalled());
        Assert.AreNotEqual(fileSignal.LastSignal, fileSignal2.LastSignal);
        Assert.IsTrue(fileSignal2.CheckIfSignalled());
        Assert.AreEqual(fileSignal.LastSignal, fileSignal2.LastSignal);
        Assert.IsFalse(fileSignal2.CheckIfSignalled());
    }

How do I skip a header from CSV files in Spark?

Working in 2018 (Spark 2.3)

Python

df = spark.read
    .option("header", "true")
    .format("csv")
    .schema(myManualSchema)
    .load("mycsv.csv")

Scala

val myDf = spark.read
  .option("header", "true")
  .format("csv")
  .schema(myManualSchema)
  .load("mycsv.csv")

PD1: myManualSchema is a predefined schema written by me, you could skip that part of code

UPDATE 2021 The same code works for Spark 3.x

df = spark.read
    .option("header", "true")
    .option("inferSchema", "true")
    .format("csv")
    .csv("mycsv.csv")

Add swipe to delete UITableViewCell

func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]?
{

    let delete = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "DELETE"){(UITableViewRowAction,NSIndexPath) -> Void in

        print("What u want while Pressed delete")
    }
    let edit = UITableViewRowAction(style: UITableViewRowActionStyle.Normal, title: "EDIT"){(UITableViewRowAction,NSIndexPath) -> Void in

        print("What u want while Pressed Edit")
    }

    edit.backgroundColor = UIColor.blackColor()
    return [delete,edit]
}

Plotting in a non-blocking way with Matplotlib

The Python package drawnow allows to update a plot in real time in a non blocking way.
It also works with a webcam and OpenCV for example to plot measures for each frame.
See the original post.

CSS: Position loading indicator in the center of the screen

use position:fixed instead of position:absolute

The first one is relative to your screen window. (not affected by scrolling)

The second one is relative to the page. (affected by scrolling)

Note : IE6 doesn't support position:fixed.

How do I pick randomly from an array?

arr = [1,9,5,2,4,9,5,8,7,9,0,8,2,7,5,8,0,2,9]
arr[rand(arr.count)]

This will return a random element from array.

If You will use the line mentioned below

arr[1+rand(arr.count)]

then in some cases it will return 0 or nil value.

The line mentioned below

rand(number)

always return the value from 0 to number-1.

If we use

1+rand(number)

then it may return number and arr[number] contains no element.

php get values from json encode

json_decode will return the same array that was originally encoded. For instanse, if you

$array = json_decode($json, true);
echo $array['countryId'];

OR

$obj= json_decode($json);

echo $obj->countryId;

These both will echo 84. I think json_encode and json_decode function names are self-explanatory...

What can be the reasons of connection refused errors?

Check at the server side that it is listening at the port 2080. First try to confirm it on the server machine by issuing telnet to that port:

telnet localhost 2080

If it is listening, it is able to respond.

wget can't download - 404 error

Wget 404 error also always happens if you want to download the pages from Wordpress-website by typing

wget -r http://somewebsite.com

If this website is built using Wordpress you'll get such an error:

ERROR 404: Not Found.

There's no way to mirror Wordpress-website because the website content is stored in the database and wget is not able to grab .php files. That's why you get Wget 404 error.

I know it's not this question's case, because Sam only wants to download a single picture, but it can be helpful for others.

Finding the type of an object in C++

Because your class is not polymorphic. Try:

struct BaseClas { int base; virtual ~BaseClas(){} };
class Derived1 : public BaseClas { int derived1; };

Now BaseClas is polymorphic. I changed class to struct because the members of a struct are public by default.

Java 8 Iterable.forEach() vs foreach loop

I feel that I need to extend my comment a bit...

About paradigm\style

That's probably the most notable aspect. FP became popular due to what you can get avoiding side-effects. I won't delve deep into what pros\cons you can get from this, since this is not related to the question.

However, I will say that the iteration using Iterable.forEach is inspired by FP and rather result of bringing more FP to Java (ironically, I'd say that there is no much use for forEach in pure FP, since it does nothing except introducing side-effects).

In the end I would say that it is rather a matter of taste\style\paradigm you are currently writing in.

About parallelism.

From performance point of view there is no promised notable benefits from using Iterable.forEach over foreach(...).

According to official docs on Iterable.forEach :

Performs the given action on the contents of the Iterable, in the order elements occur when iterating, until all elements have been processed or the action throws an exception.

... i.e. docs pretty much clear that there will be no implicit parallelism. Adding one would be LSP violation.

Now, there are "parallell collections" that are promised in Java 8, but to work with those you need to me more explicit and put some extra care to use them (see mschenk74's answer for example).

BTW: in this case Stream.forEach will be used, and it doesn't guarantee that actual work will be done in parallell (depends on underlying collection).

UPDATE: might be not that obvious and a little stretched at a glance but there is another facet of style and readability perspective.

First of all - plain old forloops are plain and old. Everybody already knows them.

Second, and more important - you probably want to use Iterable.forEach only with one-liner lambdas. If "body" gets heavier - they tend to be not-that readable. You have 2 options from here - use inner classes (yuck) or use plain old forloop. People often gets annoyed when they see the same things (iteratins over collections) being done various vays/styles in the same codebase, and this seems to be the case.

Again, this might or might not be an issue. Depends on people working on code.

Removing underline with href attribute

Add a style with the attribute text-decoration:none;:

There are a number of different ways of doing this.

Inline style:

<a href="xxx.html" style="text-decoration:none;">goto this link</a>

Inline stylesheet:

<html>
<head>
<style type="text/css">
   a {
      text-decoration:none;
   }
</style>
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>

External stylesheet:

<html>
<head>
<link rel="Stylesheet" href="stylesheet.css" />
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>

stylesheet.css:

a {
      text-decoration:none;
   }

How to round the corners of a button

I tried the following solution with the UITextArea and I expect this will work with UIButton as well.

First of all import this in your .m file -

#import <QuartzCore/QuartzCore.h>

and then in your loadView method add following lines

    yourButton.layer.cornerRadius = 10; // this value vary as per your desire
    yourButton.clipsToBounds = YES;

MySQL compare DATE string with string from DATETIME field

You can cast the DATETIME field into DATE as:

SELECT * FROM `calendar` WHERE CAST(startTime AS DATE) = '2010-04-29'

This is very much efficient.

C# Pass Lambda Expression as Method Parameter

If I understand you need following code. (passing expression lambda by parameter) The Method

public static void Method(Expression<Func<int, bool>> predicate) { 
    int[] number={1,2,3,4,5,6,7,8,9,10};
    var newList = from x in number
                  .Where(predicate.Compile()) //here compile your clausuly
                  select x;
                newList.ToList();//return a new list
    }

Calling method

Method(v => v.Equals(1));

You can do the same in their class, see this is example.

public string Name {get;set;}

public static List<Class> GetList(Expression<Func<Class, bool>> predicate)
    {
        List<Class> c = new List<Class>();
        c.Add(new Class("name1"));
        c.Add(new Class("name2"));

        var f = from g in c.
                Where (predicate.Compile())
                select g;
        f.ToList();

       return f;
    }

Calling method

Class.GetList(c=>c.Name=="yourname");

I hope this is useful

Assigning the return value of new by reference is deprecated

Upgrade your pear/MDB2 from console:

# pear upgrade MDB2-beta
# pear upgrade MDB2_Driver_Mysql-beta

Problem solved at version 2.5.0b3

CSS Outside Border

I think you've got your understanding of the two properties off a little. Border affects the outside edge of the element, making the element different in size. Outline will not change the size or position of the element (takes up no space) and goes outside the border. From your description you want to use the border property.

Look at the simple example below in your browser:

_x000D_
_x000D_
<div style="height: 100px; width: 100px; background: black; color: white; outline: thick solid #00ff00">SOME TEXT HERE</div>_x000D_
_x000D_
<div style="height: 100px; width: 100px; background: black; color: white; border-left: thick solid #00ff00">SOME TEXT HERE</div>
_x000D_
_x000D_
_x000D_

Notice how the border pushes the bottom div over, but the outline doesn't move the top div and the outline actually overlaps the bottom div.

You can read more about it here:
Border
Outline

How to get size in bytes of a CLOB column in Oracle?

NVL(length(clob_col_name),0) works for me.

How to sort two lists (which reference each other) in the exact same way

Another approach to retaining the order of a string list when sorting against another list is as follows:

list1 = [3,2,4,1, 1]
list2 = ['three', 'two', 'four', 'one', 'one2']

# sort on list1 while retaining order of string list
sorted_list1 = [y for _,y in sorted(zip(list1,list2),key=lambda x: x[0])]
sorted_list2 = sorted(list1)

print(sorted_list1)
print(sorted_list2)

output

['one', 'one2', 'two', 'three', 'four']
[1, 1, 2, 3, 4]

How to use Apple's new .p8 certificate for APNs in firebase console

Firebase console is now accepting .p8 file, in fact, it's recommending to upload .p8 file.

You can see in below-attached screenshot

Turn off deprecated errors in PHP 5.3

I just faced a similar problem where a SEO plugin issued a big number of warnings making my blog disk use exceed the plan limit.

I found out that you must include the error_reporting command after the wp-settings.php require in the wp-config.php file:

   require_once( ABSPATH .'wp-settings.php' );
   error_reporting( E_ALL ^ ( E_NOTICE | E_WARNING | E_DEPRECATED ) );

by doing this no more warnings, notices nor deprecated lines are appended to your error log file!

Tested on WordPress 3.8 but I guess it works for every installation.

How do you fix the "element not interactable" exception?

I know you may have found the answer , but if there were people looking for it in the future, they may find the solution.OK, straight to the point ,I had a similar problem like this one. When you are usually staring to use this library (selenium webdriver ) one thing that can make you angry is not to know how to use the library " import time " that is very import for breaking this type of " barrier ".

Follow the code snippet below:

Well, my solution was simple and objective. Remembering that you must wait for the element to be clickable (interactable), which is, first use the technique of searching for element by xpath.

buttonNoInteractable = browser.find_element_by_xpath('/html/body/div[2]/div/div/div[2]/div/div/div[2]/div/table[2]/thead/tr/th[2]/input')

buttonNoIteractable.click() time.sleep(10)

Or it can be by class name. Use the amount of seconds you need, if you have a slow connection, put it in 30 seconds, or if it is fast, a few seconds less is enough, for example "time.sleep (10)".

As I said, for me this solution worked very well using python.

send = browser.find_element_by_name('stacks') send.click()

Memory address of an object in C#

Getting the address of an arbitrary object in .NET is not possible, but can be done if you change the source code and use mono. See instructions here: Get Memory Address of .NET Object (C#)

Null vs. False vs. 0 in PHP

Below is an example:

            Comparisons of $x with PHP functions

Expression          gettype()   empty()     is_null()   isset() boolean : if($x)
$x = "";            string      TRUE        FALSE       TRUE    FALSE
$x = null;          NULL        TRUE        TRUE        FALSE   FALSE
var $x;             NULL        TRUE        TRUE        FALSE   FALSE
$x is undefined     NULL        TRUE        TRUE        FALSE   FALSE
$x = array();       array       TRUE        FALSE       TRUE    FALSE
$x = false;         boolean     TRUE        FALSE       TRUE    FALSE
$x = true;          boolean     FALSE       FALSE       TRUE    TRUE
$x = 1;             integer     FALSE       FALSE       TRUE    TRUE
$x = 42;            integer     FALSE       FALSE       TRUE    TRUE
$x = 0;             integer     TRUE        FALSE       TRUE    FALSE
$x = -1;            integer     FALSE       FALSE       TRUE    TRUE
$x = "1";           string      FALSE       FALSE       TRUE    TRUE
$x = "0";           string      TRUE        FALSE       TRUE    FALSE
$x = "-1";          string      FALSE       FALSE       TRUE    TRUE
$x = "php";         string      FALSE       FALSE       TRUE    TRUE
$x = "true";        string      FALSE       FALSE       TRUE    TRUE
$x = "false";       string      FALSE       FALSE       TRUE    TRUE

Please see this for more reference of type comparisons in PHP. It should give you a clear understanding.

How to preserve request url with nginx proxy_pass

I think the proxy_set_header directive could help:

location / {
    proxy_pass http://my_app_upstream;
    proxy_set_header Host $host;
    # ...
}

jQuery - hashchange event

What about using a different way instead of the hash event and listen to popstate like.

window.addEventListener('popstate', function(event)
{
    if(window.location.hash) {
            var hash = window.location.hash;
            console.log(hash);
    }
});

This method works fine in most browsers i have tried so far.

Zero an array in C code

Note: You can use memset with any character.

Example:

int arr[20];
memset(arr, 'A', sizeof(arr));

Also could be partially filled

int arr[20];
memset(&arr[5], 0, 10);

But be carefull. It is not limited for the array size, you could easily cause severe damage to your program doing something like this:

int arr[20];
memset(arr, 0, 200);

It is going to work (under windows) and zero memory after your array. It might cause damage to other variables values.

Using setDate in PreparedStatement

tl;dr

With JDBC 4.2 or later and java 8 or later:

myPreparedStatement.setObject( … , myLocalDate  )

…and…

myResultSet.getObject( … , LocalDate.class )

Details

The Answer by Vargas is good about mentioning java.time types but refers only to converting to java.sql.Date. No need to convert if your driver is updated.

java.time

The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat. The Joda-Time team also advises migration to java.time.

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

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.

LocalDate

In java.time, the java.time.LocalDate class represents a date-only value without time-of-day and without time zone.

If using a JDBC driver compliant with JDBC 4.2 or later spec, no need to use the old java.sql.Date class. You can pass/fetch LocalDate objects directly to/from your database via PreparedStatement::setObject and ResultSet::getObject.

LocalDate localDate = LocalDate.now( ZoneId.of( "America/Montreal" ) );
myPreparedStatement.setObject( 1 , localDate  );

…and…

LocalDate localDate = myResultSet.getObject( 1 , LocalDate.class );

Before JDBC 4.2, convert

If your driver cannot handle the java.time types directly, fall back to converting to java.sql types. But minimize their use, with your business logic using only java.time types.

New methods have been added to the old classes for conversion to/from java.time types. For java.sql.Date see the valueOf and toLocalDate methods.

java.sql.Date sqlDate = java.sql.Date.valueOf( localDate );

…and…

LocalDate localDate = sqlDate.toLocalDate();

Placeholder value

Be wary of using 0000-00-00 as a placeholder value as shown in your Question’s code. Not all databases and other software can handle going back that far in time. I suggest using something like the commonly-used Unix/Posix epoch reference date of 1970, 1970-01-01.

LocalDate EPOCH_DATE = LocalDate.ofEpochDay( 0 ); // 1970-01-01 is day 0 in Epoch counting.

About java.time

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

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

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

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

Where to obtain the java.time classes?

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

Want to move a particular div to right

This will do the job:

_x000D_
_x000D_
<div style="position:absolute; right:0;">Hello world</div>
_x000D_
_x000D_
_x000D_

What's is the difference between include and extend in use case diagram?

whenever there are prerequisites to a usecase then,go for include.

for usecases having authentication,worst case scenario,or are optional then go for extend..

example:for a use case of seeking admission,appointment,ticket reservation YOU MUST FILL A form (registration or feedback form)....this is where include comes..

example:for a use case verifying login or sign in your account,your authentication is a must.also think of worst case scenarios.like returning book with fine..NOT getting a reservation..paying the bill AFTER DUE DATE..this is where extend comes to play...

do not overuse include and extend in the diagrams.

KEEP IT SIMPLE SILLY!!!

YouTube iframe API: how do I control an iframe player that's already in the HTML?

You can do this with far less code:

function callPlayer(func, args) {
    var i = 0,
        iframes = document.getElementsByTagName('iframe'),
        src = '';
    for (i = 0; i < iframes.length; i += 1) {
        src = iframes[i].getAttribute('src');
        if (src && src.indexOf('youtube.com/embed') !== -1) {
            iframes[i].contentWindow.postMessage(JSON.stringify({
                'event': 'command',
                'func': func,
                'args': args || []
            }), '*');
        }
    }
}

Working example: http://jsfiddle.net/kmturley/g6P5H/296/

Best way to check for nullable bool in a condition expression (if ...)

Use extensions.

public static class NullableMixin {
    public static bool IsTrue(this System.Nullable<bool> val) {
        return val == true;
    }
    public static bool IsFalse(this System.Nullable<bool> val) {
        return val == false;
    }
    public static bool IsNull(this System.Nullable<bool> val) {
        return val == null;
    }
    public static bool IsNotNull(this System.Nullable<bool> val) {
        return val.HasValue;
    }
}


Nullable<bool> value = null;
if(value.IsTrue()) {
// do something with it
}

How can I generate a list of files with their absolute path in Linux?

If you give find an absolute path to start with, it will print absolute paths. For instance, to find all .htaccess files in the current directory:

find "$(pwd)" -name .htaccess

or if your shell expands $PWD to the current directory:

find "$PWD" -name .htaccess

find simply prepends the path it was given to a relative path to the file from that path.

Greg Hewgill also suggested using pwd -P if you want to resolve symlinks in your current directory.

What is Ad Hoc Query?

An Ad-Hoc query is:

  1. Pre-planned question.
  2. Pre-scheduled question.
  3. spur of the moment question.
  4. Question that will not return any results.

How to iterate over columns of pandas dataframe to run regression

Using list comprehension, you can get all the columns names (header):

[column for column in df]

Can you break from a Groovy "each" closure?

Replace each loop with any closure.

def list = [1, 2, 3, 4, 5]
list.any { element ->
    if (element == 2)
        return // continue

    println element

    if (element == 3)
        return true // break
}

Output

1
3

how to make label visible/invisible?

you could try

if (isValid) {
    document.getElementById("endTimeLabel").style.display = "none";
}else {
    document.getElementById("endTimeLabel").style.display = "block";
}

alone those lines

How do I format a String in an email so Outlook will print the line breaks?

I have a good solution that I tried it, it is just add the Char(13) at end of line like the following example:

Dim S As String
 S = "Some Text" & Chr(13)
 S = S + "Some Text" & Chr(13)

Getter and Setter of Model object in Angular 4

The way you declare the date property as an input looks incorrect but its hard to say if it's the only problem without seeing all your code. Rather than using @Input('date') declare the date property like so: private _date: string;. Also, make sure you are instantiating the model with the new keyword. Lastly, access the property using regular dot notation.

Check your work against this example from https://www.typescriptlang.org/docs/handbook/classes.html :

let passcode = "secret passcode";

class Employee {
    private _fullName: string;

    get fullName(): string {
        return this._fullName;
    }

    set fullName(newName: string) {
        if (passcode && passcode == "secret passcode") {
            this._fullName = newName;
        }
        else {
            console.log("Error: Unauthorized update of employee!");
        }
    }
}

let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
    console.log(employee.fullName);
}

And here is a plunker demonstrating what it sounds like you're trying to do: https://plnkr.co/edit/OUoD5J1lfO6bIeME9N0F?p=preview

How to insert a picture into Excel at a specified cell position with VBA

Try this:

With xlApp.ActiveSheet.Pictures.Insert(PicPath)
    With .ShapeRange
        .LockAspectRatio = msoTrue
        .Width = 75
        .Height = 100
    End With
    .Left = xlApp.ActiveSheet.Cells(i, 20).Left
    .Top = xlApp.ActiveSheet.Cells(i, 20).Top
    .Placement = 1
    .PrintObject = True
End With

It's better not to .select anything in Excel, it is usually never necessary and slows down your code.

Getting "type or namespace name could not be found" but everything seems ok?

I've no idea why this worked, but I removed the project reference that VS2015 was telling me it couldn't find, and added it again. Solved the problem. I'd tried both cleaning, building and restarting VS to no avail.

Best method to download image from url in Android

I use this library, it's really great when you have to deal with lots of images. It downloads them asynchronously, caches them etc.

As for the OOM exceptions, using this and this class drastically reduced them for me.

How to display a readable array - Laravel

actually a much easier way to get a readable array of what you (probably) want to see, is instead of using

dd($users); 

or

dd(User::all());

use this

dd($users->toArray());

or

 dd(User::all()->toArray());

which is a lot nicer to debug with.

EDIT - additional, this also works nicely in your views / templates so if you pass the get all users to your template, you can then dump it into your blade template

{{ dd($users->toArray()) }}

select into in mysql

Use the CREATE TABLE SELECT syntax.

http://dev.mysql.com/doc/refman/5.0/en/create-table-select.html

CREATE TABLE new_tbl SELECT * FROM orig_tbl;

Inheritance and init method in Python

A simple change in Num2 class like this:

super().__init__(num) 

It works in python3.

class Num:
        def __init__(self,num):
                self.n1 = num

class Num2(Num):
        def __init__(self,num):
                super().__init__(num)
                self.n2 = num*2
        def show(self):
                print (self.n1,self.n2)

mynumber = Num2(8)
mynumber.show()

Regular expression for validating names and surnames?

I sympathize with the need to constrain input in this situation, but I don't believe it is possible - Unicode is vast, expanding, and so is the subset used in names throughout the world.

Unlike email, there's no universally agreed-upon standard for the names people may use, or even which representations they may register as official with their respective governments. I suspect that any regex will eventually fail to pass a name considered valid by someone, somewhere in the world.

Of course, you do need to sanitize or escape input, to avoid the Little Bobby Tables problem. And there may be other constraints on which input you allow as well, such as the underlying systems used to store, render or manipulate names. As such, I recommend that you determine first the restrictions necessitated by the system your validation belongs to, and create a validation expression based on those alone. This may still cause inconvenience in some scenarios, but they should be rare.

WCF vs ASP.NET Web API

The new ASP.NET Web API is a continuation of the previous WCF Web API project (although some of the concepts have changed).

WCF was originally created to enable SOAP-based services. For simpler RESTful or RPCish services (think clients like jQuery) ASP.NET Web API should be good choice.


For us, WCF is used for SOAP and Web API for REST. I wish Web API supported SOAP too. We are not using advanced features of WCF. Here is comparison from MSDN:

enter image description here


ASP.net Web API is all about HTTP and REST based GET,POST,PUT,DELETE with well know ASP.net MVC style of programming and JSON returnable; web API is for all the light weight process and pure HTTP based components. For one to go ahead with WCF even for simple or simplest single web service it will bring all the extra baggage. For light weight simple service for ajax or dynamic calls always WebApi just solves the need. This neatly complements or helps in parallel to the ASP.net MVC.

Check out the podcast : Hanselminutes Podcast 264 - This is not your father's WCF - All about the WebAPI with Glenn Block by Scott Hanselman for more information.


In the scenarios listed below you should go for WCF:

  1. If you need to send data on protocols like TCP, MSMQ or MIME
  2. If the consuming client just knows how to consume SOAP messages

WEB API is a framework for developing RESTful/HTTP services.

There are so many clients that do not understand SOAP like Browsers, HTML5, in those cases WEB APIs are a good choice.

HTTP services header specifies how to secure service, how to cache the information, type of the message body and HTTP body can specify any type of content like HTML not just XML as SOAP services.

What is the use of the JavaScript 'bind' method?

From the MDN docs on Function.prototype.bind() :

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

So, what does that mean?!

Well, let's take a function that looks like this :

var logProp = function(prop) {
    console.log(this[prop]);
};

Now, let's take an object that looks like this :

var Obj = {
    x : 5,
    y : 10
};

We can bind our function to our object like this :

Obj.log = logProp.bind(Obj);

Now, we can run Obj.log anywhere in our code :

Obj.log('x'); // Output : 5
Obj.log('y'); // Output : 10

This works, because we bound the value of this to our object Obj.


Where it really gets interesting, is when you not only bind a value for this, but also for its argument prop :

Obj.logX = logProp.bind(Obj, 'x');
Obj.logY = logProp.bind(Obj, 'y');

We can now do this :

Obj.logX(); // Output : 5
Obj.logY(); // Output : 10

Unlike with Obj.log, we do not have to pass x or y, because we passed those values when we did our binding.

How to construct a WebSocket URI relative to the page URI?

Assuming your WebSocket server is listening on the same port as from which the page is being requested, I would suggest:

function createWebSocket(path) {
    var protocolPrefix = (window.location.protocol === 'https:') ? 'wss:' : 'ws:';
    return new WebSocket(protocolPrefix + '//' + location.host + path);
}

Then, for your case, call it as follows:

var socket = createWebSocket(location.pathname + '/to/ws');

System.web.mvc missing

in VS 2017 I cleaned the solution and rebuilt it and that fixed it

How to replace url parameter with javascript/jquery?

I have get best solution to replace the URL parameter.

Following function will replace room value to 3 in the following URL.

http://example.com/property/?min=50000&max=60000&room=1&property_type=House

var newurl = replaceUrlParam('room','3');
history.pushState(null, null, newurl);

function replaceUrlParam(paramName, paramValue){
    var url = window.location.href;

    if (paramValue == null) {
        paramValue = '';
    }

    var pattern = new RegExp('\\b('+paramName+'=).*?(&|#|$)');
    if (url.search(pattern)>=0) {
        return url.replace(pattern,'$1' + paramValue + '$2');
    }

    url = url.replace(/[?#]$/,'');
    return url + (url.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue;
}

Output

http://example.com/property/?min=50000&max=60000&room=3&property_type=House

jQuery datepicker set selected date, on the fly

$('.date-pick').datePicker().val(new Date()).trigger('change')

finally, that what i look for the last few hours! I need initiate changes, not just setup date in text field!

How do I keep two side-by-side divs the same height?

Using jQuery

Using jQuery, you can do it in a super simple one-line-script.

// HTML
<div id="columnOne">
</div>

<div id="columnTwo">
</div>

// Javascript
$("#columnTwo").height($("#columnOne").height());

Using CSS

This is a bit more interesting. The technique is called Faux Columns. More or less you don't actually set the actual height to be the same, but you rig up some graphical elements so they look the same height.

How to customize a Spinner in Android

You can create fully custom spinner design like as

Step1: In drawable folder make background.xml for a border of the spinner.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@android:color/transparent" />
<corners android:radius="5dp" />
<stroke
android:width="1dp"
   android:color="@android:color/darker_gray" />
</shape>

Step2: for layout design of spinner use this drop-down icon or any image drop.png enter image description here

 <RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginRight="3dp"
    android:layout_weight=".28"
    android:background="@drawable/spinner_border"
    android:orientation="horizontal">

    <Spinner
        android:id="@+id/spinner2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_gravity="center"
        android:background="@android:color/transparent"
        android:gravity="center"
        android:layout_marginLeft="5dp"
        android:spinnerMode="dropdown" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:layout_gravity="center"
        android:src="@mipmap/drop" />

</RelativeLayout>

Finally looks like below image and it is everywhere clickable in round area and no need to write click Lister for imageView.

enter image description here

Step3: For drop-down design, remove the line from Dropdown ListView and change the background color, Create custom adapter like as

Spinner spinner = (Spinner) findViewById(R.id.spinner1);
String[] years = {"1996","1997","1998","1998"};
ArrayAdapter<CharSequence> langAdapter = new ArrayAdapter<CharSequence>(getActivity(), R.layout.spinner_text, years );
langAdapter.setDropDownViewResource(R.layout.simple_spinner_dropdown);
mSpinner5.setAdapter(langAdapter);

In layout folder create R.layout.spinner_text.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layoutDirection="ltr"
android:id="@android:id/text1"
style="@style/spinnerItemStyle"
android:singleLine="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:paddingLeft="2dp"
/>

In layout folder create simple_spinner_dropdown.xml

<?xml version="1.0" encoding="utf-8"?>
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
style="@style/spinnerDropDownItemStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:paddingBottom="5dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="5dp"
android:singleLine="true" />

In styles, you can add custom dimensions and height as per your requirement.

<style name="spinnerItemStyle" parent="android:Widget.TextView.SpinnerItem">
</style>

<style name="spinnerDropDownItemStyle" parent="android:TextAppearance.Widget.TextView.SpinnerItem">
</style>

Finally looks like as

enter image description here

According to the requirement, you can change background color and text of drop-down color by changing the background color or text color of simple_spinner_dropdown.xml

Is there a Boolean data type in Microsoft SQL Server like there is in MySQL?

You may want to use the BIT data type, probably setting is as NOT NULL:

Quoting the MSDN article:

bit (Transact-SQL)

An integer data type that can take a value of 1, 0, or NULL.

The SQL Server Database Engine optimizes storage of bit columns. If there are 8 or less bit columns in a table, the columns are stored as 1 byte. If there are from 9 up to 16 bit columns, the columns are stored as 2 bytes, and so on.

The string values TRUE and FALSE can be converted to bit values: TRUE is converted to 1 and FALSE is converted to 0.

How do you discover model attributes in Rails?

some_instance.attributes

Source: blog

MySQL: Fastest way to count number of rows

I handled tables for the German Government with sometimes 60 million records.

And we needed to know many times the total rows.

So we database programmers decided that in every table is record one always the record in which the total record numbers is stored. We updated this number, depending on INSERT or DELETE rows.

We tried all other ways. This is by far the fastest way.

Oracle "SQL Error: Missing IN or OUT parameter at index:: 1"

I got the same error and found the cause to be a wrong or missing foreign key. (Using JDBC)

Debugging with command-line parameters in Visual Studio

Even if you do start the executable outside Visual Studio, you can still use the "Attach" command to connect Visual Studio to your already-running executable. This can be useful e.g. when your application is run as a plug-in within another application.

How do you use "git --bare init" repository?

You can execute the following commands to initialize your local repository

mkdir newProject
cd newProject
touch .gitignore
git init
git add .
git commit -m "Initial Commit"
git remote add origin user@host:~/path_on_server/newProject.git
git push origin master

You should work on your project from your local repository and use the server as the central repository.

You can also follow this article which explains each and every aspect of creating and maintaining a Git repository. Git for Beginners

How do I get Maven to use the correct repositories?

I think what you have missed here is this:

https://maven.apache.org/settings.html#Servers

The repositories for download and deployment are defined by the repositories and distributionManagement elements of the POM. However, certain settings such as username and password should not be distributed along with the pom.xml. This type of information should exist on the build server in the settings.xml.

This is the prefered way of using custom repos. So probably what is happening is that the url of this repo is in settings.xml of the build server.

Once you get hold of the url and credentials, you can put them in your machine here: ~/.m2/settings.xml like this:

<settings ...> 

        .
        .
        .
        <servers>
            <server>
              <id>internal-repository-group</id>
              <username>YOUR-USERNAME-HERE</username>
              <password>YOUR-PASSWORD-HERE</password>
            </server>
        </servers>
</settings>

EDIT:

You then need to refer this repository into project POM. The id internal-repository-group can be used in every project. You can setup multiple repos and credentials setting using different IDs in settings xml.

The advantage of this approach is that project can be shared without worrying about the credentials and don't have to mention the credentials in every project.

Following is a sample pom of a project using "internal-repository-group"

<repositories>
    <repository>
        <id>internal-repository-group</id>
        <name>repo-name</name>
        <url>http://project.com/yourrepourl/</url>
        <layout>default</layout>
        <releases>
            <enabled>true</enabled>
            <updatePolicy>never</updatePolicy>
        </releases>
        <snapshots>
            <enabled>true</enabled>
            <updatePolicy>never</updatePolicy>
        </snapshots>
    </repository>
</repositories>

can you add HTTPS functionality to a python flask web server?

  • To run https functionality or SSL authentication in flask application you first install "pyOpenSSL" python package using:

     pip install pyopenssl
    
  • Next step is to create 'cert.pem' and 'key.pem' using following command on terminal :

     openssl req -x509 -newkey rsa:4096 -nodes -out cert.pem -keyout key.pem -days 365
    
  • Copy generated 'cert.pem' and 'kem.pem' in you flask application project

  • Add ssl_context=('cert.pem', 'key.pem') in app.run()

For example:

    from flask import Flask, jsonify

    app = Flask(__name__)

    @app.route('/')

    def index():

        return 'Flask is running!'


    @app.route('/data')

    def names():

        data = {"names": ["John", "Jacob", "Julie", "Jennifer"]}

        return jsonify(data)

  if __name__ == '__main__':

        app.run(ssl_context=('cert.pem', 'key.pem'))

Catching KeyboardInterrupt in Python during program shutdown

You could ignore SIGINTs after shutdown starts by calling signal.signal(signal.SIGINT, signal.SIG_IGN) before you start your cleanup code.

Is it possible to make abstract classes in Python?

Use the abc module to create abstract classes. Use the abstractmethod decorator to declare a method abstract, and declare a class abstract using one of three ways, depending upon your Python version.

In Python 3.4 and above, you can inherit from ABC. In earlier versions of Python, you need to specify your class's metaclass as ABCMeta. Specifying the metaclass has different syntax in Python 3 and Python 2. The three possibilities are shown below:

# Python 3.4+
from abc import ABC, abstractmethod
class Abstract(ABC):
    @abstractmethod
    def foo(self):
        pass
# Python 3.0+
from abc import ABCMeta, abstractmethod
class Abstract(metaclass=ABCMeta):
    @abstractmethod
    def foo(self):
        pass
# Python 2
from abc import ABCMeta, abstractmethod
class Abstract:
    __metaclass__ = ABCMeta

    @abstractmethod
    def foo(self):
        pass

Whichever way you use, you won't be able to instantiate an abstract class that has abstract methods, but will be able to instantiate a subclass that provides concrete definitions of those methods:

>>> Abstract()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class Abstract with abstract methods foo
>>> class StillAbstract(Abstract):
...     pass
... 
>>> StillAbstract()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class StillAbstract with abstract methods foo
>>> class Concrete(Abstract):
...     def foo(self):
...         print('Hello, World')
... 
>>> Concrete()
<__main__.Concrete object at 0x7fc935d28898>

What are the differences between type() and isinstance()?

For the real differences, we can find it in code, but I can't find the implement of the default behavior of the isinstance().

However we can get the similar one abc.__instancecheck__ according to __instancecheck__.

From above abc.__instancecheck__, after using test below:

# file tree
# /test/__init__.py
# /test/aaa/__init__.py
# /test/aaa/aa.py
class b():
pass

# /test/aaa/a.py
import sys
sys.path.append('/test')

from aaa.aa import b
from aa import b as c

d = b()

print(b, c, d.__class__)
for i in [b, c, object]:
    print(i, '__subclasses__',  i.__subclasses__())
    print(i, '__mro__', i.__mro__)
    print(i, '__subclasshook__', i.__subclasshook__(d.__class__))
    print(i, '__subclasshook__', i.__subclasshook__(type(d)))
print(isinstance(d, b))
print(isinstance(d, c))

<class 'aaa.aa.b'> <class 'aa.b'> <class 'aaa.aa.b'>
<class 'aaa.aa.b'> __subclasses__ []
<class 'aaa.aa.b'> __mro__ (<class 'aaa.aa.b'>, <class 'object'>)
<class 'aaa.aa.b'> __subclasshook__ NotImplemented
<class 'aaa.aa.b'> __subclasshook__ NotImplemented
<class 'aa.b'> __subclasses__ []
<class 'aa.b'> __mro__ (<class 'aa.b'>, <class 'object'>)
<class 'aa.b'> __subclasshook__ NotImplemented
<class 'aa.b'> __subclasshook__ NotImplemented
<class 'object'> __subclasses__ [..., <class 'aaa.aa.b'>, <class 'aa.b'>]
<class 'object'> __mro__ (<class 'object'>,)
<class 'object'> __subclasshook__ NotImplemented
<class 'object'> __subclasshook__ NotImplemented
True
False

I get this conclusion, For type:

# according to `abc.__instancecheck__`, they are maybe different! I have not found negative one 
type(INSTANCE) ~= INSTANCE.__class__
type(CLASS) ~= CLASS.__class__

For isinstance:

# guess from `abc.__instancecheck__`
return any(c in cls.__mro__ or c in cls.__subclasses__ or cls.__subclasshook__(c) for c in {INSTANCE.__class__, type(INSTANCE)})

BTW: better not to mix use relative and absolutely import, use absolutely import from project_dir( added by sys.path)

Delete last commit in bitbucket

You can write the command also for Bitbucket as mentioned by Dustin:

git push -f origin HEAD^:master

Note: instead of master you can use any branch. And it deletes just push on Bitbucket.

To remove last commit locally in git use:

git reset --hard HEAD~1

How can I get the last day of the month in C#?

try this. It will solve your problem.

 var lastDayOfMonth = DateTime.DaysInMonth(int.Parse(ddlyear.SelectedValue), int.Parse(ddlmonth.SelectedValue));
DateTime tLastDayMonth = Convert.ToDateTime(lastDayOfMonth.ToString() + "/" + ddlmonth.SelectedValue + "/" + ddlyear.SelectedValue);

how to define variable in jquery

var name = 'john';
document.write(name);

it will write the variable you have declared upper

Can an XSLT insert the current date?

format-date(current-date(), '[M01]/[D01]/[Y0001]') = 09/19/2013
format-time(current-time(), '[H01]:[m01] [z]') = 09:26 GMT+10
format-dateTime(current-dateTime(), '[h1]:[m01] [P] on [MNn] [D].') = 9:26 a.m. on September 19.

reference: Formatting Dates and Times using XSLT 2.0 and XPath

SQL query to check if a name begins and ends with a vowel

For MS access or MYSQL server

SELECT city FROM station
WHERE City LIKE '[aeiou]%'and City LIKE '%[aeiou]';

Entity Framework: There is already an open DataReader associated with this Command

I had originally decided to use a static field in my API class to reference an instance of MyDataContext object (Where MyDataContext is an EF5 Context object), but that is what seemed to create the problem. I added code something like the following to every one of my API methods and that fixed the problem.

using(MyDBContext db = new MyDBContext())
{
    //Do some linq queries
}

As other people have stated, the EF Data Context objects are NOT thread safe. So placing them in the static object will eventually cause the "data reader" error under the right conditions.

My original assumption was that creating only one instance of the object would be more efficient, and afford better memory management. From what I have gathered researching this issue, that is not the case. In fact, it seems to be more efficient to treat each call to your API as an isolated, thread safe event. Ensuring that all resources are properly released, as the object goes out of scope.

This makes sense especially if you take your API to the next natural progression which would be to expose it as a WebService or REST API.

Disclosure

  • OS: Windows Server 2012
  • .NET: Installed 4.5, Project using 4.0
  • Data Source: MySQL
  • Application Framework: MVC3
  • Authentication: Forms

What is the difference between H.264 video and MPEG-4 video?

They are names for the same standard from two different industries with different naming methods, the guys who make & sell movies and the guys who transfer the movies over the internet. Since 2003: "MPEG 4 Part 10" = "H.264" = "AVC". Before that the relationship was a little looser in that they are not equal but an "MPEG 4 Part 2" decoder can render a stream that's "H.263". The Next standard is "MPEG H Part 2" = "H.265" = "HEVC"

install apt-get on linux Red Hat server

wget http://dag.wieers.com/packages/apt/apt-0.5.15lorg3.1-4.el4.rf.i386.rpm

rpm -ivh apt-0.5.15lorg3.1-4.el4.rf.i386.rpm

wget http://dag.wieers.com/packages/rpmforge-release/rpmforge-release-0.3.4-1.el4.rf.i386.rpm

rpm -Uvh rpmforge-release-0.3.4-1.el4.rf.i386.rpm

maybe some URL is broken,please research it. Enjoy~~

Best Practices: working with long, multiline strings in PHP?

but what's the deal with new lines and carriage returns? What's the difference? Is \n\n the equivalent of \r\r or \n\r? Which should I use when I'm creating a line gap between lines?

No one here seemed to actualy answer this question, so here I am.

\r represents 'carriage-return'

\n represents 'line-feed'

The actual reason for them goes back to typewriters. As you typed the 'carriage' would slowly slide, character by character, to the right of the typewriter. When you got to the end of the line you would return the carriage and then go to a new line. To go to the new line, you would flip a lever which fed the lines to the type writer. Thus these actions, combined, were called carriage return line feed. So quite literally:

A line feed,\n, means moving to the next line.

A carriage return, \r, means moving the cursor to the beginning of the line.

Ultimately Hello\n\nWorld should result in the following output on the screen:

Hello

     World

Where as Hello\r\rWorld should result in the following output.

It's only when combining the 2 characters \r\n that you have the common understanding of knew line. I.E. Hello\r\nWorld should result in:

Hello
World

And of course \n\r would result in the same visual output as \r\n.

Originally computers took \r and \n quite literally. However these days the support for carriage return is sparse. Usually on every system you can get away with using \n on its own. It never depends on the OS, but it does depend on what you're viewing the output in.

Still I'd always advise using \r\n wherever you can!

Java inner class and static nested class

From the Java Tutorial:

Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are simply called static nested classes. Non-static nested classes are called inner classes.

Static nested classes are accessed using the enclosing class name:

OuterClass.StaticNestedClass

For example, to create an object for the static nested class, use this syntax:

OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();

Objects that are instances of an inner class exist within an instance of the outer class. Consider the following classes:

class OuterClass {
    ...
    class InnerClass {
        ...
    }
}

An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance.

To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:

OuterClass outerObject = new OuterClass()
OuterClass.InnerClass innerObject = outerObject.new InnerClass();

see: Java Tutorial - Nested Classes

For completeness note that there is also such a thing as an inner class without an enclosing instance:

class A {
  int t() { return 1; }
  static A a =  new A() { int t() { return 2; } };
}

Here, new A() { ... } is an inner class defined in a static context and does not have an enclosing instance.

how to remove only one style property with jquery

You can also replace "-moz-user-select:none" with "-moz-user-select:inherit". This will inherit the style value from any parent style or from the default style if no parent style was defined.

Fixed digits after decimal with f-strings

Include the type specifier in your format expression:

>>> a = 10.1234
>>> f'{a:.2f}'
'10.12'

Simple dynamic breadcrumb

Also made a little script using RDFa (you can also use microdata or other formats) Check it out on google This script also keeps in mind your site structure.

function breadcrumbs($text = 'You are here: ', $sep = ' &raquo; ', $home = 'Home') {
//Use RDFa breadcrumb, can also be used for microformats etc.
$bc     =   '<div xmlns:v="http://rdf.data-vocabulary.org/#" id="crums">'.$text;
//Get the website:
$site   =   'http://'.$_SERVER['HTTP_HOST'];
//Get all vars en skip the empty ones
$crumbs =   array_filter( explode("/",$_SERVER["REQUEST_URI"]) );
//Create the home breadcrumb
$bc    .=   '<span typeof="v:Breadcrumb"><a href="'.$site.'" rel="v:url" property="v:title">'.$home.'</a>'.$sep.'</span>'; 
//Count all not empty breadcrumbs
$nm     =   count($crumbs);
$i      =   1;
//Loop the crumbs
foreach($crumbs as $crumb){
    //Make the link look nice
    $link    =  ucfirst( str_replace( array(".php","-","_"), array(""," "," ") ,$crumb) );
    //Loose the last seperator
    $sep     =  $i==$nm?'':$sep;
    //Add crumbs to the root
    $site   .=  '/'.$crumb;
    //Make the next crumb
    $bc     .=  '<span typeof="v:Breadcrumb"><a href="'.$site.'" rel="v:url" property="v:title">'.$link.'</a>'.$sep.'</span>';
    $i++;
}
$bc .=  '</div>';
//Return the result
return $bc;}

jQuery see if any or no checkboxes are selected

JQuery .is will test all specified elements and return true if at least one of them matches selector:

if ($(":checkbox[name='choices']", form).is(":checked"))
{
    // one or more checked
}
else
{
    // nothing checked
}

Get UTC time and local time from NSDate object

Xcode 9 • Swift 4 (also works Swift 3.x)

extension Formatter {
    // create static date formatters for your date representations
    static let preciseLocalTime: DateFormatter = {
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.dateFormat = "HH:mm:ss.SSS"
        return formatter
    }()
    static let preciseGMTTime: DateFormatter = {
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.timeZone = TimeZone(secondsFromGMT: 0)
        formatter.dateFormat = "HH:mm:ss.SSS"
        return formatter
    }()
}

extension Date {
    // you can create a read-only computed property to return just the nanoseconds from your date time
    var nanosecond: Int { return Calendar.current.component(.nanosecond,  from: self)   }
    // the same for your local time
    var preciseLocalTime: String {
        return Formatter.preciseLocalTime.string(for: self) ?? ""
    }
    // or GMT time
    var preciseGMTTime: String {
        return Formatter.preciseGMTTime.string(for: self) ?? ""
    }
}

Playground testing

Date().preciseLocalTime // "09:13:17.385"  GMT-3
Date().preciseGMTTime   // "12:13:17.386"  GMT
Date().nanosecond       // 386268973

This might help you also formatting your dates:

enter image description here

Add st, nd, rd and th (ordinal) suffix to a number

By splitting the number into an array and reversing we can easily check the last 2 digits of the number using array[0] and array[1].

If a number is in the teens array[1] = 1 it requires "th".

function getDaySuffix(num)
{
    var array = ("" + num).split("").reverse(); // E.g. 123 = array("3","2","1")

    if (array[1] != "1") { // Number is in the teens
        switch (array[0]) {
            case "1": return "st";
            case "2": return "nd";
            case "3": return "rd";
        }
    }

    return "th";
}

Which Architecture patterns are used on Android?

The Following Android Classes uses Design Patterns

1) View Holder uses Singleton Design Pattern

2) Intent uses Factory Design Pattern

3) Adapter uses Adapter Design Pattern

4) Broadcast Receiver uses Observer Design Pattern

5) View uses Composite Design Pattern

6) Media FrameWork uses Façade Design Pattern

AND/OR in Python?

As Matt Ball's answer explains, or is "and/or". But or doesn't work with in the way you use it above. You have to say if "a" in someList or "á" in someList or.... Or better yet,

if any(c in someList for c in ("a", "á", "à", "ã", "â")):
    ...

That's the answer to your question as asked.

Other Notes

However, there are a few more things to say about the example code you've posted. First, the chain of someList.remove... or someList remove... statements here is unnecessary, and may result in unexpected behavior. It's also hard to read! Better to break it into individual lines:

someList.remove("a")
someList.remove("á")
...

Even that's not enough, however. As you observed, if the item isn't in the list, then an error is thrown. On top of that, using remove is very slow, because every time you call it, Python has to look at every item in the list. So if you want to remove 10 different characters, and you have a list that has 100 characters, you have to perform 1000 tests.

Instead, I would suggest a very different approach. Filter the list using a set, like so:

chars_to_remove = set(("a", "á", "à", "ã", "â"))
someList = [c for c in someList if c not in chars_to_remove]

Or, change the list in-place without creating a copy:

someList[:] = (c for c in someList if c not in chars_to_remove)

These both use list comprehension syntax to create a new list. They look at every character in someList, check to see of the character is in chars_to_remove, and if it is not, they include the character in the new list.

This is the most efficient version of this code. It has two speed advantages:

  1. It only passes through someList once. Instead of performing 1000 tests, in the above scenario, it performs only 100.
  2. It can test all characters with a single operation, because chars_to_remove is a set. If it chars_to_remove were a list or tuple, then each test would really be 10 tests in the above scenario -- because each character in the list would need to be checked individually.

Find elements inside forms and iframe using Java and Selenium WebDriver

Before you try searching for the elements within the iframe you will have to switch Selenium focus to the iframe.

Try this before searching for the elements within the iframe:

driver.switchTo().frame(driver.findElement(By.name("iFrameTitle")));

iTunes Connect Screenshots Sizes for all iOS (iPhone/iPad/Apple Watch) devices

To get screenshots of the proper size without having to create them manually -- run your app in the latest version of Xcode and choose the iPhone you need screenshots for, then hit cmd-s while viewing the simulator. This will save a screenshot to your desktop in the full resolution that you need for submission.

As noted below by @HoffZ, be sure that the scale is set to 100%.

In Xcode select simulator you want:

Xcode simulators

In the Simulator menu set the scale to 100%:

Set Scale to 100%

Press cmd-s to save:

Save Screenshot

How to get local server host and port in Spring Boot?

You can get port info via

@Value("${local.server.port}")
private String serverPort;

Rails raw SQL example

You can do this:

sql = "Select * from ... your sql query here"
records_array = ActiveRecord::Base.connection.execute(sql)

records_array would then be the result of your sql query in an array which you can iterate through.

Overriding a JavaScript function while referencing the original

Thanks guys the proxy pattern really helped.....Actually I wanted to call a global function foo.. In certain pages i need do to some checks. So I did the following.

//Saving the original func
var org_foo = window.foo;

//Assigning proxy fucnc
window.foo = function(args){
    //Performing checks
    if(checkCondition(args)){
        //Calling original funcs
        org_foo(args);
    }
};

Thnx this really helped me out

Does Google Chrome work with Selenium IDE (as Firefox does)?

While you cannot record tests using the Selenium IDE in Chrome (or any other browser other than FF), you can run them (from the IDE) in Chrome, IE and other browsers using the Webdriver playback feature of Selenium 2 IDE. Tests will need to be recorded and launched from FF - Chrome will launch before the first step of the test is executed. Instructions for setup and test execution are here and here. You will need to install Selenium 2 IDE (if you haven't already done so) and the Chrome Webdriver Server executable - both are available for download on the Selenium HQ website.

NOTE: If the above meets your needs, you may also want to consider just converting all your tests to Selenium Webdriver (which means they would be all code and no longer run from the Selenium IDE). This would be a better solution from the perspective of test maintenance and simplicity of execution. The Selenium documentation (on the Selenium website) has more information on the process to convert Selenium IDE tests to Webdriver.

How to add a new row to an empty numpy array

I want to do a for loop, yet with askewchan's method it does not work well, so I have modified it.

x = np.empty((0,3))
y = np.array([1,2,3])
for i in ...
    x = np.vstack((x,y))

What exactly is Python's file.flush() doing?

There's typically two levels of buffering involved:

  1. Internal buffers
  2. Operating system buffers

The internal buffers are buffers created by the runtime/library/language that you're programming against and is meant to speed things up by avoiding system calls for every write. Instead, when you write to a file object, you write into its buffer, and whenever the buffer fills up, the data is written to the actual file using system calls.

However, due to the operating system buffers, this might not mean that the data is written to disk. It may just mean that the data is copied from the buffers maintained by your runtime into the buffers maintained by the operating system.

If you write something, and it ends up in the buffer (only), and the power is cut to your machine, that data is not on disk when the machine turns off.

So, in order to help with that you have the flush and fsync methods, on their respective objects.

The first, flush, will simply write out any data that lingers in a program buffer to the actual file. Typically this means that the data will be copied from the program buffer to the operating system buffer.

Specifically what this means is that if another process has that same file open for reading, it will be able to access the data you just flushed to the file. However, it does not necessarily mean it has been "permanently" stored on disk.

To do that, you need to call the os.fsync method which ensures all operating system buffers are synchronized with the storage devices they're for, in other words, that method will copy data from the operating system buffers to the disk.

Typically you don't need to bother with either method, but if you're in a scenario where paranoia about what actually ends up on disk is a good thing, you should make both calls as instructed.


Addendum in 2018.

Note that disks with cache mechanisms is now much more common than back in 2013, so now there are even more levels of caching and buffers involved. I assume these buffers will be handled by the sync/flush calls as well, but I don't really know.

NPM vs. Bower vs. Browserify vs. Gulp vs. Grunt vs. Webpack

Yarn is a recent package manager that probably deserves to be mentioned.
So, here it is: https://yarnpkg.com/

As far as I know it can fetch both npm and bower dependencies and has other appreciated features.

ASP.NET MVC controller actions that return JSON or partial html

Another nice way to deal with JSON data is using the JQuery getJSON function. You can call the

public ActionResult SomeActionMethod(int id) 
{ 
    return Json(new {foo="bar", baz="Blech"});
}

Method from the jquery getJSON method by simply...

$.getJSON("../SomeActionMethod", { id: someId },
    function(data) {
        alert(data.foo);
        alert(data.baz);
    }
);

How to import functions from different js file in a Vue+webpack+vue-loader project

Say I want to import data into a component from src/mylib.js:

var test = {
  foo () { console.log('foo') },
  bar () { console.log('bar') },
  baz () { console.log('baz') }
}

export default test

In my .Vue file I simply imported test from src/mylib.js:

<script> 
  import test from '@/mylib'

  console.log(test.foo())
  ...
</script>

how to display employee names starting with a and then b in sql

select name_last, name_first
from employees
where name_last like 'A%' or name_last like 'B%'
order by name_last, name_first asc

Android load from URL to Bitmap

I Prefer these one:

Creates Bitmap from InputStream and returns it:

    public static  Bitmap downloadImage(String url) {
        Bitmap bitmap = null;
        InputStream stream = null;
        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        bmOptions.inSampleSize = 1;

        try {
            stream = getHttpConnection(url);
            bitmap = BitmapFactory.decodeStream(stream, null, bmOptions);
            stream.close();
        }
        catch (IOException e1) {
            e1.printStackTrace();
            System.out.println("downloadImage"+ e1.toString());
        }
        return bitmap;
    }

  // Makes HttpURLConnection and returns InputStream

 public static  InputStream getHttpConnection(String urlString)  throws IOException {

        InputStream stream = null;
        URL url = new URL(urlString);
        URLConnection connection = url.openConnection();

        try {
            HttpURLConnection httpConnection = (HttpURLConnection) connection;
            httpConnection.setRequestMethod("GET");
            httpConnection.connect();

            if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                stream = httpConnection.getInputStream();
            }
        }
        catch (Exception ex) {
            ex.printStackTrace();
            System.out.println("downloadImage" + ex.toString());
        }
        return stream;
    }

REMEMBER :

Android includes two HTTP clients: HttpURLConnection and Apache HTTP Client. For Gingerbread and later, HttpURLConnection is the best choice.

From Android 3.x Honeycomb or later, you cannot perform Network IO on the UI thread and doing this throws android.os.NetworkOnMainThreadException. You must use Asynctask instead as shown below

/**     AsyncTAsk for Image Bitmap  */
    private class AsyncGettingBitmapFromUrl extends AsyncTask<String, Void, Bitmap> {


        @Override
        protected Bitmap doInBackground(String... params) {

            System.out.println("doInBackground");

            Bitmap bitmap = null;

            bitmap = AppMethods.downloadImage(params[0]);

            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {

            System.out.println("bitmap" + bitmap);

        }
    }

Can IntelliJ IDEA encapsulate all of the functionality of WebStorm and PHPStorm through plugins?

Definitely a great question. I've noted this also as a sub question of the choice for versions within IDEa that this link may help to address...

http://www.jetbrains.com/idea/features/editions_comparison_matrix.html

it as well potentially possesses a ground work for looking at your other IDE choices and the options they provide.

I'm thinking WebStorm is best for JavaScript and Git repo management, meaning the HTML5 CSS Cordova kinds of stacks, which is really where (I believe along with others) the future lies and energies should be focused now... but ya it depends on your needs, etc.

Anyway this tells that story too... http://www.jetbrains.com/products.html

NodeJS / Express: what is "app.use"?

app.use() handles all the middleware functions.
What is middleware?
Middlewares are the functions which work like a door between two all the routes.

For instance:

app.use((req, res, next) => {
    console.log("middleware ran");
    next();
});

app.get("/", (req, res) => {
    console.log("Home route");
});

When you visit / route in your console the two message will be printed. The first message will be from middleware function. If there is no next() function passed then only middleware function runs and other routes are blocked.

Rounding Bigdecimal values with 2 Decimal Places

You can call setScale(newScale, roundingMode) method three times with changing the newScale value from 4 to 3 to 2 like

First case

    BigDecimal a = new BigDecimal("10.12345");

    a = a.setScale(4, BigDecimal.ROUND_HALF_UP); 
    System.out.println("" + a); //10.1235
    a = a.setScale(3, BigDecimal.ROUND_HALF_UP); 
    System.out.println("" + a); //10.124
    a = a.setScale(2, BigDecimal.ROUND_HALF_UP);
    System.out.println("" + a); //10.12

Second case

    BigDecimal a = new BigDecimal("10.12556");

    a = a.setScale(4, BigDecimal.ROUND_HALF_UP); 
    System.out.println("" + a); //10.1256
    a = a.setScale(3, BigDecimal.ROUND_HALF_UP); 
    System.out.println("" + a); //10.126
    a = a.setScale(2, BigDecimal.ROUND_HALF_UP);
    System.out.println("" + a); //10.13

How to store an array into mysql?

You can save your array as a json.
there is documentation for json data type: https://dev.mysql.com/doc/refman/5.7/en/json.html

How to prevent form from submitting multiple times from client side?

Use unobtrusive javascript to disable the submit event on the form after it has already been submitted. Here is an example using jQuery.

EDIT: Fixed issue with submitting a form without clicking the submit button. Thanks, ichiban.

$("body").on("submit", "form", function() {
    $(this).submit(function() {
        return false;
    });
    return true;
});

Why use static_cast<int>(x) instead of (int)x?

C Style casts are easy to miss in a block of code. C++ style casts are not only better practice; they offer a much greater degree of flexibility.

reinterpret_cast allows integral to pointer type conversions, however can be unsafe if misused.

static_cast offers good conversion for numeric types e.g. from as enums to ints or ints to floats or any data types you are confident of type. It does not perform any run time checks.

dynamic_cast on the other hand will perform these checks flagging any ambiguous assignments or conversions. It only works on pointers and references and incurs an overhead.

There are a couple of others but these are the main ones you will come across.

google-services.json for different productFlavors

So if you want to programmatically copy google-services.json file from all your variants into your root folder. When you switch to a specific variant here's a solution for you

android {
  applicationVariants.all { variant ->
    copy {
        println "Switches to $variant google-services.json"
        from "src/$variant"
        include "google-services.json"
        into "."
    }
  }
}

There's a caveat to this approach that is you need to have google-service.json file in each of your variants folder here's an example. variant image

How do I keep track of pip-installed packages in an Anaconda (Conda) environment?

There is a branch of conda (new-pypi-install) that adds better integration with pip and PyPI. In particular conda list will also show pip installed packages and conda install will first try to find a conda package and failing that will use pip to install the package.

This branch is scheduled to be merged later this week so that version 2.1 of conda will have better pip-integration with conda.

How to develop a soft keyboard for Android?

Some tips:

About your questions:

An inputMethod is basically an Android Service, so yes, you can do HTTP and all the stuff you can do in a Service.

You can open Activities and dialogs from the InputMethod. Once again, it's just a Service.

I've been developing an IME, so ask again if you run into an issue.

Preferred Java way to ping an HTTP URL for availability

The following code performs a HEAD request to check whether the website is available or not.

public static boolean isReachable(String targetUrl) throws IOException
{
    HttpURLConnection httpUrlConnection = (HttpURLConnection) new URL(
            targetUrl).openConnection();
    httpUrlConnection.setRequestMethod("HEAD");

    try
    {
        int responseCode = httpUrlConnection.getResponseCode();

        return responseCode == HttpURLConnection.HTTP_OK;
    } catch (UnknownHostException noInternetConnection)
    {
        return false;
    }
}

How/when to use ng-click to call a route?

Using a custom attribute (implemented with a directive) is perhaps the cleanest way. Here's my version, based on @Josh and @sean's suggestions.

angular.module('mymodule', [])

// Click to navigate
// similar to <a href="#/partial"> but hash is not required, 
// e.g. <div click-link="/partial">
.directive('clickLink', ['$location', function($location) {
    return {
        link: function(scope, element, attrs) {
            element.on('click', function() {
                scope.$apply(function() {
                    $location.path(attrs.clickLink);
                });
            });
        }
    }
}]);

It has some useful features, but I'm new to Angular so there's probably room for improvement.

Shell Script: Execute a python program from within a shell script

I use this and it works fine

#/bin/bash
/usr/bin/python python python_script.py

How to make a JTable non-editable

You can override the method isCellEditable and implement as you want for example:

//instance table model
DefaultTableModel tableModel = new DefaultTableModel() {

    @Override
    public boolean isCellEditable(int row, int column) {
       //all cells false
       return false;
    }
};

table.setModel(tableModel);

or

//instance table model
DefaultTableModel tableModel = new DefaultTableModel() {

   @Override
   public boolean isCellEditable(int row, int column) {
       //Only the third column
       return column == 3;
   }
};

table.setModel(tableModel);

Note for if your JTable disappears

If your JTable is disappearing when you use this it is most likely because you need to use the DefaultTableModel(Object[][] data, Object[] columnNames) constructor instead.

//instance table model
DefaultTableModel tableModel = new DefaultTableModel(data, columnNames) {

    @Override
    public boolean isCellEditable(int row, int column) {
       //all cells false
       return false;
    }
};

table.setModel(tableModel);

How to add items to array in nodejs

Check out Javascript's Array API for details on the exact syntax for Array methods. Modifying your code to use the correct syntax would be:

var array = [];
calendars.forEach(function(item) {
    array.push(item.id);
});

console.log(array);

You can also use the map() method to generate an Array filled with the results of calling the specified function on each element. Something like:

var array = calendars.map(function(item) {
    return item.id;
});

console.log(array);

And, since ECMAScript 2015 has been released, you may start seeing examples using let or const instead of var and the => syntax for creating functions. The following is equivalent to the previous example (except it may not be supported in older node versions):

let array = calendars.map(item => item.id);
console.log(array);

Options for embedding Chromium instead of IE WebBrowser control with WPF/C#

Here is another one:

http://www.essentialobjects.com/Products/WebBrowser/Default.aspx

This one is also based on the latest Chrome engine but it's much easier to use than CEF. It's a single .NET dll that you can simply reference and use.

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

Being a geezer programmer, many of my school programming projects used text menu driven interactions. Virtually all used something like the following logic for the main procedure:

do
    display options
    get choice
    perform action appropriate to choice
while choice is something other than exit

Since school days, I have found that I use the while loop more frequently.

How can I parse a local JSON file from assets folder into a ListView?

With Kotlin have this extension function to read the file return as string.

fun AssetManager.readAssetsFile(fileName : String): String = open(fileName).bufferedReader().use{it.readText()}

Parse the output string using any JSON parser.

How can I get the height of an element using css only

You could use the CSS calc parameter to calculate the height dynamically like so:

_x000D_
_x000D_
.dynamic-height {_x000D_
   color: #000;_x000D_
   font-size: 12px;_x000D_
   margin-top: calc(100% - 10px);_x000D_
   text-align: left;_x000D_
}
_x000D_
<div class='dynamic-height'>_x000D_
    <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem.</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Add a row number to result set of a SQL query

The typical pattern would be as follows, but you need to actually define how the ordering should be applied (since a table is, by definition, an unordered bag of rows):

SELECT t.A, t.B, t.C, number = ROW_NUMBER() OVER (ORDER BY t.A)
  FROM dbo.tableZ AS t
  ORDER BY t.A;

Not sure what the variables in your question are supposed to represent (they don't match).

What is an ORM, how does it work, and how should I use one?

An ORM (Object Relational Mapper) is a piece/layer of software that helps map your code Objects to your database.

Some handle more aspects than others...but the purpose is to take some of the weight of the Data Layer off of the developer's shoulders.

Here's a brief clip from Martin Fowler (Data Mapper):

Patterns of Enterprise Application Architecture Data Mappers

Python JSON serialize a Decimal object

My $.02!

I extend a bunch of the JSON encoder since I am serializing tons of data for my web server. Here's some nice code. Note that it's easily extendable to pretty much any data format you feel like and will reproduce 3.9 as "thing": 3.9

JSONEncoder_olddefault = json.JSONEncoder.default
def JSONEncoder_newdefault(self, o):
    if isinstance(o, UUID): return str(o)
    if isinstance(o, datetime): return str(o)
    if isinstance(o, time.struct_time): return datetime.fromtimestamp(time.mktime(o))
    if isinstance(o, decimal.Decimal): return str(o)
    return JSONEncoder_olddefault(self, o)
json.JSONEncoder.default = JSONEncoder_newdefault

Makes my life so much easier...

How to get the real and total length of char * (char array)?

when new allocates an array, depending on the compiler (i use gnu c++), the word in front of the array contains information about the number of bytes allocated.

The test code:

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

int
main ()
{
    int arraySz;
    char *a;
    unsigned int *q;

    for (arraySz = 5; arraySz <= 64; arraySz++) {

        printf ("%02d - ", arraySz);

        a = new char[arraySz];
        unsigned char *p = (unsigned char *) a;

        q = (unsigned int *) (a - 4);
        printf ("%02d\n", (*q));

        delete[] (a);

    }
}

on my machine dumps out:

05 - 19
06 - 19
07 - 19
08 - 19
09 - 19
10 - 19
11 - 19
12 - 19
13 - 27
14 - 27
15 - 27
16 - 27
17 - 27
18 - 27
19 - 27
20 - 27
21 - 35
22 - 35
23 - 35
24 - 35
25 - 35
26 - 35
27 - 35
28 - 35
29 - 43
30 - 43
31 - 43
32 - 43
33 - 43
34 - 43
35 - 43
36 - 43
37 - 51
38 - 51
39 - 51
40 - 51
41 - 51
42 - 51
43 - 51
44 - 51
45 - 59
46 - 59
47 - 59
48 - 59
49 - 59
50 - 59
51 - 59
52 - 59
53 - 67
54 - 67
55 - 67
56 - 67
57 - 67
58 - 67
59 - 67
60 - 67
61 - 75
62 - 75
63 - 75
64 - 75

I would not recommend this solution (vector is better), but if you are really desperate, you could find a relationship and be able to conclude the number of bytes allocated from the heap.

Check if date is a valid one

Try this one. It is not nice but it will work as long as the input is constant format from your date picker.

It is badDate coming from your picker in this example

https://jsfiddle.net/xs8tvox9/

var dateFormat = 'DD-MM-YYYY'
var badDate = "2016-10-19";

var splittedDate = badDate.split('-');

if (splittedDate.length == 3) {
  var d = moment(splittedDate[2]+"-"+splittedDate[1]+"-"+splittedDate[0], dateFormat);
  alert(d.isValid())
} else {
  //incorrectFormat
}

Is there a way to set background-image as a base64 encoded image?

In my case, it was just because I didn't set the height and width.

But there is another issue.

The background image could be removed using

element.style.backgroundImage=""

but couldn't be set using

element.style.backgroundImage="some base64 data"

Jquery works fine.

How do I get total physical memory size using PowerShell without WMI?

Maybe not the best solution, but it worked for me.

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.VisualBasic")
$VBObject=[Microsoft.VisualBasic.Devices.ComputerInfo]::new()
$SystemMemory=$VBObject.TotalPhysicalMemory

Loading PictureBox Image from resource file with path (Part 3)

It depends on your file path. For me, the current directory was [project]\bin\Debug, so I had to move to the parent folder twice.

Image image = Image.FromFile(@"..\..\Pictures\"+text+".png");
this.pictureBox1.Image = image;

To find your current directory, you can make a dummy label called label2 and write this:

this.label2.Text = System.IO.Directory.GetCurrentDirectory();

Searching if value exists in a list of objects using Linq

customerList.Any(x=>x.Firstname == "John")

PYTHONPATH on Linux

  1. PYTHONPATH is an environment variable
  2. Yes (see https://unix.stackexchange.com/questions/24802/on-which-unix-distributions-is-python-installed-as-part-of-the-default-install)
  3. /usr/lib/python2.7 on Ubuntu
  4. you shouldn't install packages manually. Instead, use pip. When a package isn't in pip, it usually has a setuptools setup script which will install the package into the proper location (see point 3).
  5. if you use pip or setuptools, then you don't need to set PYTHONPATH explicitly

If you look at the instructions for pyopengl, you'll see that they are consistent with points 4 and 5.

How do you run CMD.exe under the Local System Account?

(Comment)

I can't comment yet, so posting here... I just tried the above OSK.EXE debug trick but regedit instantly closes when I save the filled "C:\windows\system32\cmd.exe" into the already created Debugger key so Microsoft is actively working to block native ways to do this. It is really weird because other things do not trigger this.

Using task scheduler does create a SYSTEM CMD but it is in the system environment and not displayed within a human user profile so this is also now defunct (though it is logical).

Currently on Microsoft Windows [Version 10.0.20201.1000]

So, at this point it has to be third party software that mediates this and further tricks are being more actively sealed by Microsoft these days.

.htaccess File Options -Indexes on Subdirectories

htaccess files affect the directory they are placed in and all sub-directories, that is an htaccess file located in your root directory (yoursite.com) would affect yoursite.com/content, yoursite.com/content/contents, etc.

http://www.javascriptkit.com/howto/htaccess.shtml

No resource found - Theme.AppCompat.Light.DarkActionBar

I had this same problem. None of the solutions listed here helped my situation. As it turns out, I was importing the parent folder for a project into Android Studio 1.5, rather than the project folder itself. This threw Gradel into a tizzy. Solution was to import the project folder instead.

What's "tools:context" in Android layout files?

This is best solution : https://developer.android.com/studio/write/tool-attributes

This is design attributes we can set activty context in xml like

tools:context=".activity.ActivityName"

Adapter:

tools:context="com.PackegaName.AdapterName"

enter image description here

You can navigate to java class when clicking on the marked icon and tools have more features like

tools:text=""
tools:visibility:""
tools:listItems=""//for recycler view 

etx

Difference between Math.Floor() and Math.Truncate()

They are functionally equivalent with positive numbers. The difference is in how they handle negative numbers.

For example:

Math.Floor(2.5) = 2
Math.Truncate(2.5) = 2

Math.Floor(-2.5) = -3
Math.Truncate(-2.5) = -2

MSDN links: - Math.Floor Method - Math.Truncate Method

P.S. Beware of Math.Round it may not be what you expect.

To get the "standard" rounding result use:

float myFloat = 4.5;
Console.WriteLine( Math.Round(myFloat) ); // writes 4
Console.WriteLine( Math.Round(myFloat, 0, MidpointRounding.AwayFromZero) ) //writes 5
Console.WriteLine( myFloat.ToString("F0") ); // writes 5

How can I get my webapp's base URL in ASP.NET MVC?

@{
    var baseurl = Request.Url.Scheme + "://" + Request.Url.Host + ":" + Request.Url.Port + Url.Content("~");
}
@baseurl

--output http://localhost:49626/TEST/

How to convert DateTime? to DateTime

MS already made a method for this, so you dont have to use the null coalescing operator. No difference in functionality, but it is easier for non-experts to get what is happening at a glance.

DateTime updatedTime = _objHotelPackageOrder.UpdatedDate.GetValueOrDefault(DateTime.Now);

How do I install opencv using pip?

  1. Open terminal
  2. Run the following command pip install --trusted-host=pypi.org --trusted-host=files.pythonhosted.org opencv-python.
  3. Hope it will work.

Objective-C for Windows

A recent attempt to port Objective C 2.0 to Windows is the Subjective project.

From the Readme:

Subjective is an attempt to bring Objective C 2.0 with ARC support to Windows.

This project is a fork of objc4-532.2, the Objective C runtime that ships with OS X 10.8.5. The port can be cross-compiled on OS X using llvm-clang combined with the MinGW linker.

There are certain limitations many of which are a matter of extra work, while others, such as exceptions and blocks, depend on more serious work in 3rd party projects. The limitations are:

• 32-bit only - 64-bit is underway

• Static linking only - dynamic linking is underway

• No closures/blocks - until libdispatch supports them on Windows

• No exceptions - until clang supports them on Windows

• No old style GC - until someone cares...

• Internals: no vtables, no gdb support, just plain malloc, no preoptimizations - some of these things will be available under the 64-bit build.

• Currently a patched clang compiler is required; the patch adds -fobjc-runtime=subj flag

The project is available on Github, and there is also a thread on the Cocotron Group outlining some of the progress and issues encountered.

conflicting types error when compiling c program using gcc

To answer a more generic case, this error is noticed when you pick a function name which is already used in some built in library. For e.g., select.

A simple method to know about it is while compiling the file, the compiler will indicate the previous declaration.

Web Application Problems (web.config errors) HTTP 500.19 with IIS7.5 and ASP.NET v2

In my case, there was something wrong with the .NET Core Windows Hosting Bundle installation.

I had that installed and had restarted IIS using ("net stop was /y" and "net start w3svc") after installation, but I would get that 500.19 error with Error Code 0x8007000d and Config Source -1: 0:.

I managed to resolve the issue by repairing the .NET Core Windows Hosting Bundle installation and restarting IIS using the commands I mentioned above.

Hope this helps someone!

SQL - Create view from multiple tables

Are you using MySQL or PostgreSQL?

You want to use JOIN syntax, not UNION. For example, using INNER JOIN:

CREATE VIEW V AS
SELECT POP.country, POP.year, POP.pop, FOOD.food, INCOME.income
FROM POP
INNER JOIN FOOD ON (POP.country=FOOD.country) AND (POP.year=FOOD.year)
INNER JOIN INCOME ON (POP.country=INCOME.country) AND (POP.year=INCOME.year)

However, this will only show results when each country and year are present in all three tables. If this is not what you want, look into left outer joins (using the same link above).

CSS - display: none; not working

This is because the inline style display:block is overwriting your CSS. You'll need to either remove this inline style or use:

#tfl {
  display: none !important;
}

This overrides inline styles. Note that using !important is generally not recommended unless it's a last resort.

sql - insert into multiple tables in one query

MySQL doesn't support multi-table insertion in a single INSERT statement. Oracle is the only one I'm aware of that does, oddly...

INSERT INTO NAMES VALUES(...)
INSERT INTO PHONES VALUES(...)

How to get the first and last date of the current year?

simply write:-

select convert (date,DATEADD(YEAR,DATEDIFF(YEAR,0,GETDATE()),0))

start date of the year.

select convert (date,DATEADD(YEAR, DATEDIFF(YEAR,0,GETDATE()) + 1, -1))  

cannot load such file -- bundler/setup (LoadError)

I had this because something bad was in my vendor/bundle. Nothing to do with Apache, just in local dev env.

To fix, I deleted vendor\bundle, and also deleted the reference to it in my .bundle/config so it wouldn't get re-used.

Then, I re-bundled (which then installed to GEM_HOME instead of vendor/bundle and the problem went away.

Character Limit in HTML

In addition to the above, I would like to point out that client-side validation (HTML code, javascript, etc.) is never enough. Also check the length server-side, or just don't check at all (if it's not so important that people can be allowed to get around it, then it's not important enough to really warrant any steps to prevent that, either).

Also, fellows, he (or she) said HTML, not XHTML. ;)