Programs & Examples On #Low memory

Adding new files to a subversion repository

Probably svn import would be the best option around. Check out Getting Data into Your Repository (in Version Control with Subversion, For Subversion).

The svn import command is a quick way to copy an unversioned tree of files into a repository, creating intermediate directories as necessary. svn import doesn't require a working copy, and your files are immediately committed to the repository. You typically use this when you have an existing tree of files that you want to begin tracking in your Subversion repository. For example:

$ svn import /path/to/mytree \
             http://svn.example.com/svn/repo/some/project \
             -m "Initial import"
Adding         mytree/foo.c
Adding         mytree/bar.c
Adding         mytree/subdir
Adding         mytree/subdir/quux.h

Committed revision 1.
$

The previous example copied the contents of the local directory mytree into the directory some/project in the repository. Note that you didn't have to create that new directory first—svn import does that for you. Immediately after the commit, you can see your data in the repository:

$ svn list http://svn.example.com/svn/repo/some/project
bar.c
foo.c
subdir/
$

Note that after the import is finished, the original local directory is not converted into a working copy. To begin working on that data in a versioned fashion, you still need to create a fresh working copy of that tree.

Note: if you are on the same machine as the Subversion repository you can use the file:// specifier with a path rather than the https:// with a URL specifier.

The number of method references in a .dex file cannot exceed 64k API 17

**

For Unity Game Developers

**

If anyone comes here because this error showed up in their Unity project, Go to File->Build Settings -> Player Settings -> Player. go to Publishing Settings and under the Build tab, enable "Custom Launcher Gradle Template". a path will be shown under that text. go to the path and add multiDexEnabled true like this:

defaultConfig {
    minSdkVersion **MINSDKVERSION**
    targetSdkVersion **TARGETSDKVERSION**
    applicationId '**APPLICATIONID**'
    ndk {
        abiFilters **ABIFILTERS**
    }
    versionCode **VERSIONCODE**
    versionName '**VERSIONNAME**'
    multiDexEnabled true
}

How to Solve the XAMPP 1.7.7 - PHPMyAdmin - MySQL Error #2002 in Ubuntu

It turns out that the solution is to stop all the related services and solve the “Another daemon is already running” issue.

The commands i used to solve the issue are as follows:

sudo /opt/lampp/lampp stop              
sudo /etc/init.d/apache2 stop    
sudo /etc/init.d/mysql stop

Or, you can also type instead:

sudo service apache2 stop
sudo service mysql stop

After that, we again start the lampp services:

sudo /opt/lampp/lampp start

Now, there must be no problems while opening:

http://localhost                  
http://localhost/phpmyadmin

Can I configure a subdomain to point to a specific port on my server

With only 1 IP you can forget DNS but you can use a MineProxy because the handshake packet of the client contains the host that then he connected to and a MineProxy will ready this host and proxy the connection to a server that is registered for that host

Add content to a new open window

When You want to open new tab/window (depends on Your browser configuration defaults):

output = 'Hello, World!';
window.open().document.write(output);

When output is an Object and You want get JSON, for example (also can generate any type of document, even image encoded in Base64)

output = ({a:1,b:'2'});
window.open('data:application/json;' + (window.btoa?'base64,'+btoa(JSON.stringify(output)):JSON.stringify(output)));

Update

Google Chrome (60.0.3112.90) block this code:

Not allowed to navigate top frame to data URL: data:application/json;base64,eyJhIjoxLCJiIjoiMiJ9

When You want to append some data to existing page

output = '<h1>Hello, World!</h1>';
window.open('output.html').document.body.innerHTML += output;

output = 'Hello, World!';
window.open('about:blank').document.body.innerText += output;

Allow only numbers to be typed in a textbox

You also can use some HTML5 attributes, some browsers might already take advantage of them (type="number" min="0").

Whatever you do, remember to re-check your inputs on the server side: you can never assume the client-side validation has been performed.

How do I get the name of the active user via the command line in OS X?

as 'whoami' has been obsoleted, it's probably more forward compatible to use:

id -un

What does the @Valid annotation indicate in Spring?

I wanted to add more details about how the @Valid works, especially in spring.

Everything you'd want to know about validation in spring is explained clearly and in detail in https://reflectoring.io/bean-validation-with-spring-boot/, but I'll copy the answer to how @Valid works incase the link goes down.

The @Valid annotation can be added to variables in a rest controller method to validate them. There are 3 types of variables that can be validated:

  • the request body,
  • variables within the path (e.g. id in /foos/{id}) and,
  • query parameters.

So now... how does spring "validate"? You can define constraints to the fields of a class by annotating them with certain annotations. Then, you pass an object of that class into a Validator which checks if the constraints are satisfied.

For example, suppose I had controller method like this:

@RestController
class ValidateRequestBodyController {

  @PostMapping("/validateBody")
  ResponseEntity<String> validateBody(@Valid @RequestBody Input input) {
    return ResponseEntity.ok("valid");
  }

}

So this is a POST request which takes in a response body, and we're mapping that response body to a class Input.

Here's the class Input:

class Input {

  @Min(1)
  @Max(10)
  private int numberBetweenOneAndTen;

  @Pattern(regexp = "^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$")
  private String ipAddress;
  
  // ...
}

The @Valid annotation will tell spring to go and validate the data passed into the controller by checking to see that the integer numberBetweenOneAndTen is between 1 and 10 inclusive because of those min and max annotations. It'll also check to make sure the ip address passed in matches the regular expression in the annotation.

side note: the regular expression isn't perfect.. you could pass in 3 digit numbers that are greater than 255 and it would still match the regular expression.


Here's an example of validating a query variable and path variable:

@RestController
@Validated
class ValidateParametersController {

  @GetMapping("/validatePathVariable/{id}")
  ResponseEntity<String> validatePathVariable(
      @PathVariable("id") @Min(5) int id) {
    return ResponseEntity.ok("valid");
  }
  
  @GetMapping("/validateRequestParameter")
  ResponseEntity<String> validateRequestParameter(
      @RequestParam("param") @Min(5) int param) { 
    return ResponseEntity.ok("valid");
  }
}

In this case, since the query variable and path variable are just integers instead of just complex classes, we put the constraint annotation @Min(5) right on the parameter instead of using @Valid.

What is the @Html.DisplayFor syntax for?

DisplayFor is also useful for templating. You could write a template for your Model, and do something like this:

@Html.DisplayFor(m => m)

Similar to @Html.EditorFor(m => m). It's useful for the DRY principal so that you don't have to write the same display logic over and over for the same Model.

Take a look at this blog on MVC2 templates. It's still very applicable to MVC3:

http://www.dalsoft.co.uk/blog/index.php/2010/04/26/mvc-2-templates/


It's also useful if your Model has a Data annotation. For instance, if the property on the model is decorated with the EmailAddress data annotation, DisplayFor will render it as a mailto: link.

Print an ArrayList with a for-each loop

Your code works. If you don't have any output, you may have "forgotten" to add some values to the list:

// add values
list.add("one");
list.add("two");

// your code
for (String object: list) {
    System.out.println(object);
}

Is it possible to use the SELECT INTO clause with UNION [ALL]?

SELECT * INTO tmpFerdeen FROM 
(SELECT top(100)*  
FROM Customers 
UNION All 
SELECT top(100)*  
FROM CustomerEurope 
UNION All 
SELECT top(100)*  
FROM CustomerAsia 
UNION All 
SELECT top(100)*  
FROM CustomerAmericas) AS Blablabal

This "Blablabal" is necessary

Getting the 'external' IP address in Java

http://jstun.javawi.de/ will do it - provided your gateway device does STUN )most do)

How do I work with a git repository within another repository?

If I understand your problem well you want the following things:

  1. Have your media files stored in one single git repository, which is used by many projects
  2. If you modify a media file in any of the projects in your local machine, it should immediately appear in every other project (so you don't want to commit+push+pull all the time)

Unfortunately there is no ultimate solution for what you want, but there are some things by which you can make your life easier.

First you should decide one important thing: do you want to store for every version in your project repository a reference to the version of the media files? So for example if you have a project called example.com, do you need know which style.css it used 2 weeks ago, or the latest is always (or mostly) the best?

If you don't need to know that, the solution is easy:

  1. create a repository for the media files and one for each project
  2. create a symbolic link in your projects which point to the locally cloned media repository. You can either create a relative symbolic link (e.g. ../media) and assume that everybody will checkout the project so that the media directory is in the same place, or write the name of the symbolic link into .gitignore, and everybody can decide where he/she puts the media files.

In most of the cases, however, you want to know this versioning information. In this case you have two choices:

  1. Store every project in one big repository. The advantage of this solution is that you will have only 1 copy of the media repository. The big disadvantage is that it is much harder to switch between project versions (if you checkout to a different version you will always modify ALL projects)

  2. Use submodules (as explained in answer 1). This way you will store the media files in one repository, and the projects will contain only a reference to a specific media repo version. But this way you will normally have many local copies of the media repository, and you cannot easily modify a media file in all projects.

If I were you I would probably choose the first or third solution (symbolic links or submodules). If you choose to use submodules you can still do a lot of things to make your life easier:

  1. Before committing you can rename the submodule directory and put a symlink to a common media directory. When you're ready to commit, you can remove the symlink and remove the submodule back, and then commit.

  2. You can add one of your copy of the media repository as a remote repository to all of your projects.

You can add local directories as a remote this way:

cd /my/project2/media
git remote add project1 /my/project1/media

If you modify a file in /my/project1/media, you can commit it and pull it from /my/project2/media without pushing it to a remote server:

cd /my/project1/media
git commit -a -m "message"
cd /my/project2/media
git pull project1 master

You are free to remove these commits later (with git reset) because you haven't shared them with other users.

Lua - Current time in milliseconds

If your environment is Windows and you have access to system commands, you can get time of centiseconds precision with io.popen(command):

local handle = io.popen("echo %time%")
local result = handle:read("*a")
handle:close()

The result will hold string of hh:mm:ss.cc format: (with trailing line break)

"19:56:53.90\n"

Note, it's in local timesone, so you probably want to extract only the .cc part and combine it with epoch seconds from os.time().

java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer in java 1.6

Use:

((Long) userService.getAttendanceList(currentUser)).intValue();

instead.

The .intValue() method is defined in class Number, which Long extends.

Why should I prefer to use member initialization lists?

For POD class members, it makes no difference, it's just a matter of style. For class members which are classes, then it avoids an unnecessary call to a default constructor. Consider:

class A
{
public:
    A() { x = 0; }
    A(int x_) { x = x_; }
    int x;
};

class B
{
public:
    B()
    {
        a.x = 3;
    }
private:
    A a;
};

In this case, the constructor for B will call the default constructor for A, and then initialize a.x to 3. A better way would be for B's constructor to directly call A's constructor in the initializer list:

B()
  : a(3)
{
}

This would only call A's A(int) constructor and not its default constructor. In this example, the difference is negligible, but imagine if you will that A's default constructor did more, such as allocating memory or opening files. You wouldn't want to do that unnecessarily.

Furthermore, if a class doesn't have a default constructor, or you have a const member variable, you must use an initializer list:

class A
{
public:
    A(int x_) { x = x_; }
    int x;
};

class B
{
public:
    B() : a(3), y(2)  // 'a' and 'y' MUST be initialized in an initializer list;
    {                 // it is an error not to do so
    }
private:
    A a;
    const int y;
};

Xcode warning: "Multiple build commands for output file"

In the Project Navigator, select your Xcode Project file. This will show you the project settings as well as the targets in the project. Look in the "Copy Bundle Resources" Build Phase. You should find the offending files in that list twice. Delete the duplicate reference.

Xcode is complaining that you are trying to bundle the same file with your application two times.

Convert Pandas DataFrame to JSON format

Here is small utility class that converts JSON to DataFrame and back: Hope you find this helpful.

# -*- coding: utf-8 -*-
from pandas.io.json import json_normalize

class DFConverter:

    #Converts the input JSON to a DataFrame
    def convertToDF(self,dfJSON):
        return(json_normalize(dfJSON))

    #Converts the input DataFrame to JSON 
    def convertToJSON(self, df):
        resultJSON = df.to_json(orient='records')
        return(resultJSON)

Update div with jQuery ajax response html

It's also possible to use jQuery's .load()

$('#submitform').click(function() {
  $('#showresults').load('getinfo.asp #showresults', {
    txtsearch: $('#appendedInputButton').val()
  }, function() {
    // alert('Load was performed.')
    // $('#showresults').slideDown('slow')
  });
});

unlike $.get(), allows us to specify a portion of the remote document to be inserted. This is achieved with a special syntax for the url parameter. If one or more space characters are included in the string, the portion of the string following the first space is assumed to be a jQuery selector that determines the content to be loaded.

We could modify the example above to use only part of the document that is fetched:

$( "#result" ).load( "ajax/test.html #container" );

When this method executes, it retrieves the content of ajax/test.html, but then jQuery parses the returned document to find the element with an ID of container. This element, along with its contents, is inserted into the element with an ID of result, and the rest of the retrieved document is discarded.

No provider for Router?

Please use this module

RouterModule.forRoot(
  [
    { path: "", component: LoginComponent}
  ]
)

now just replace your <login></login> with <router-outlet></router-outlet> thats it

Javascript Array Alert

If you want to see the array as an array, you can say

alert(JSON.stringify(aCustomers));

instead of all those document.writes.

http://jsfiddle.net/5b2eb/

However, if you want to display them cleanly, one per line, in your popup, do this:

alert(aCustomers.join("\n"));

http://jsfiddle.net/5b2eb/1/

How to recursively download a folder via FTP on Linux

You could rely on wget which usually handles ftp get properly (at least in my own experience). For example:

wget -r ftp://user:[email protected]/

You can also use -m which is suitable for mirroring. It is currently equivalent to -r -N -l inf.

If you've some special characters in the credential details, you can specify the --user and --password arguments to get it to work. Example with custom login with specific characters:

wget -r --user="user@login" --password="Pa$$wo|^D" ftp://server.com/

As pointed out by @asmaier, watch out that even if -r is for recursion, it has a default max level of 5:

-r
--recursive
    Turn on recursive retrieving.

-l depth
--level=depth
    Specify recursion maximum depth level depth.  The default maximum depth is 5.

If you don't want to miss out subdirs, better use the mirroring option, -m:

-m
--mirror
    Turn on options suitable for mirroring.  This option turns on recursion and time-stamping, sets infinite
    recursion depth and keeps FTP directory listings.  It is currently equivalent to -r -N -l inf
    --no-remove-listing.

Best practices for SQL varchar column length

Whenever I set up a new SQL table I feel the same way about 2^n being more "even"... but to sum up the answers here, there is no significant impact on storage space simply by defining varchar(2^n) or even varchar(MAX).

That said, you should still anticipate the potential implications on storage and performance when setting a high varchar() limit. For example, let's say you create a varchar(MAX) column to hold product descriptions with full-text indexing. If 99% of descriptions are only 500 characters long, and then suddenly you get somebody who replaces said descriptions with wikipedia articles, you may notice unanticipated significant storage and performance hits.

Another thing to consider from Bill Karwin:

There's one possible performance impact: in MySQL, temporary tables and MEMORY tables store a VARCHAR column as a fixed-length column, padded out to its maximum length. If you design VARCHAR columns much larger than the greatest size you need, you will consume more memory than you have to. This affects cache efficiency, sorting speed, etc.

Basically, just come up with reasonable business constraints and error on a slightly larger size. As @onedaywhen pointed out, family names in UK are usually between 1-35 characters. If you decide to make it varchar(64), you're not really going to hurt anything... unless you're storing this guy's family name that's said to be up to 666 characters long. In that case, maybe varchar(1028) makes more sense.

And in case it's helpful, here's what varchar 2^5 through 2^10 might look like if filled:

varchar(32)     Lorem ipsum dolor sit amet amet.

varchar(64)     Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donecie

varchar(128)    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donecie
                vestibulum massa. Nullam dignissim elementum molestie. Vehiculas

varchar(256)    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donecie
                vestibulum massa. Nullam dignissim elementum molestie. Vehiculas
                velit metus, sit amet tristique purus condimentum eleifend. Quis
                que mollis magna vel massa malesuada bibendum. Proinde tincidunt

varchar(512)    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donecie
                vestibulum massa. Nullam dignissim elementum molestie. Vehiculas
                velit metus, sit amet tristique purus condimentum eleifend. Quis
                que mollis magna vel massa malesuada bibendum. Proinde tincidunt
                dolor tellus, sit amet porta neque varius vitae. Seduse molestie
                lacus id lacinia tempus. Vestibulum accumsan facilisis lorem, et
                mollis diam pretium gravida. In facilisis vitae tortor id vulput
                ate. Proin ornare arcu in sollicitudin pharetra. Crasti molestie

varchar(1024)   Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donecie
                vestibulum massa. Nullam dignissim elementum molestie. Vehiculas
                velit metus, sit amet tristique purus condimentum eleifend. Quis
                que mollis magna vel massa malesuada bibendum. Proinde tincidunt
                dolor tellus, sit amet porta neque varius vitae. Seduse molestie
                lacus id lacinia tempus. Vestibulum accumsan facilisis lorem, et
                mollis diam pretium gravida. In facilisis vitae tortor id vulput
                ate. Proin ornare arcu in sollicitudin pharetra. Crasti molestie
                dapibus leo lobortis eleifend. Vivamus vitae diam turpis. Vivamu
                nec tristique magna, vel tincidunt diam. Maecenas elementum semi
                quam. In ut est porttitor, sagittis nulla id, fermentum turpist.
                Curabitur pretium nibh a imperdiet cursus. Sed at vulputate este
                proin fermentum pretium justo, ac malesuada eros et Pellentesque
                vulputate hendrerit molestie. Aenean imperdiet a enim at finibus
                fusce ut ullamcorper risus, a cursus massa. Nunc non dapibus vel
                Lorem ipsum dolor sit amet, consectetur Praesent ut ultrices sit

When to use CouchDB over MongoDB and vice versa

Very old question but it's on top of Google and I don't quite like the answers I see so here's my own.

There's much more to Couchdb than the ability to develop CouchApps. Most people use CouchDb in a classical 3-tiers web architecture.

In practice the deciding factor for most people will be the fact that MongoDb allows ad-hoc querying with a SQL like syntax while CouchDb doesn't (you've got to create map/reduce views which turns some people off even though creating these views is Rapid Application Development friendly - they have nothing to do with stored procedures).

To address points raised in the accepted answer : CouchDb has a great versionning system, but it doesn't mean that it is only suited (or more suited) for places where versionning is important. Also, couchdb is heavy-write friendly thanks to its append-only nature (writes operations return in no time while guaranteeing that no data will ever be lost).

One very important thing that is not mentioned by anyone is the fact that CouchDb relies on b-tree indexes. This means that whether you have 1 "row" or 20 billions, the querying time will always remain below 10ms. This is a game changer which makes CouchDb a low-latency and read-friendly database, and this really shouldn't be overlooked.

To be fair and exhaustive the advantage MongoDb has over CouchDb is tooling and marketing. They have first-class citizen tools for all major languages and platforms making the on-boarding easy and this added to their adhoc querying makes the transition from SQL even easier.

CouchDb doesn't have this level of tooling - even though there are many libraries available today - but CouchDb is exposed as an HTTP API and it is therefore quite easy to create a wrapper in your favorite language to talk with it. I personally like this approach as it avoids bloat and allows you to only take what you want (interface segregation principle).

So I'd say using one or the other is largely a matter of comfort and preference with their paradigms. CouchDb approach "just fits", for certain people, but if after learning about the database features (in the exhaustive official guide) you don't have your "hell yeah" moment, you should probably move on.

I'd discourage using CouchDb if you just want to use "the right tool for the right job". because you'll find out that you can't just use it that way and you'll end up being pissed and writing blog posts such as "Where are joins in CouchDb ?" and "Where is transaction management ?". Indeed Couchdb is - paradoxically - very transparent but at the same time requires a paradigm shift and a change in the way you approach problems to really shine (and really work).

But once you've done that it really pays off. I'd personally need very strong reasons or a major deal breaker on a project to choose another database, but so far I haven't met any.

Getting an attribute value in xml element

How about:

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class Demo {

    public static void main(String[] args) throws Exception {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document document = db.parse(new File("input.xml"));
        NodeList nodeList = document.getElementsByTagName("Item");
        for(int x=0,size= nodeList.getLength(); x<size; x++) {
            System.out.println(nodeList.item(x).getAttributes().getNamedItem("name").getNodeValue());
        }
    }
}

Unable to compile simple Java 10 / Java 11 project with Maven

It might not exactly be the same error, but I had a similar one.

Check Maven Java Version

Since Maven is also runnig with Java, check first with which version your Maven is running on:

mvn --version | grep -i java 

It returns:

Java version 1.8.0_151, vendor: Oracle Corporation, runtime: C:\tools\jdk\openjdk1.8

Incompatible version

Here above my maven is running with Java Version 1.8.0_151. So even if I specify maven to compile with Java 11:

<properties>
    <java.version>11</java.version>
    <maven.compiler.source>${java.version}</maven.compiler.source>
    <maven.compiler.target>${java.version}</maven.compiler.target>
</properties>

It will logically print out this error:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.0:compile (default-compile) on project efa-example-commons-task: Fatal error compiling: invalid target release: 11 -> [Help 1]

How to set specific java version to Maven

The logical thing to do is to set a higher Java Version to Maven (e.g. Java version 11 instead 1.8).

Maven make use of the environment variable JAVA_HOME to find the Java Version to run. So change this variable to the JDK you want to compile against (e.g. OpenJDK 11).

Sanity check

Then run again mvn --version to make sure the configuration has been taken care of:

mvn --version | grep -i java

yields

Java version: 11.0.2, vendor: Oracle Corporation, runtime: C:\tools\jdk\openjdk11

Which is much better and correct to compile code written with the Java 11 specifications.

How do I get the SharedPreferences from a PreferenceActivity in Android?

If you don't have access to getDefaultSharedPreferenes(), you can use getSharedPreferences(name, mode) instead, you just have to pass in the right name.

Android creates this name (possibly based on the package name of your project?). You can get it by putting the following code in a SettingsActivity onCreate(), and seeing what preferencesName is.

String preferencesName = this.getPreferenceManager().getSharedPreferencesName();

The string should be something like com.example.projectname_preferences. Hard code that somewhere in your project, and pass it in to getSharedPreferences() and you should be good to go.

How to calculate UILabel width based on text length?

Here's something I came up with after applying a few principles other SO posts, including Aaron's link:

AnnotationPin *myAnnotation = (AnnotationPin *)annotation;

self = [super initWithAnnotation:myAnnotation reuseIdentifier:reuseIdentifier];
self.backgroundColor = [UIColor greenColor];
self.frame = CGRectMake(0,0,30,30);
imageView = [[UIImageView alloc] initWithImage:myAnnotation.THEIMAGE];
imageView.frame = CGRectMake(3,3,20,20);
imageView.layer.masksToBounds = NO;
[self addSubview:imageView];
[imageView release];

CGSize titleSize = [myAnnotation.THETEXT sizeWithFont:[UIFont systemFontOfSize:12]];
CGRect newFrame = self.frame;
newFrame.size.height = titleSize.height + 12;
newFrame.size.width = titleSize.width + 32;
self.frame = newFrame;
self.layer.borderColor = [UIColor colorWithRed:0 green:.3 blue:0 alpha:1.0f].CGColor;
self.layer.borderWidth = 3.0;
        
UILabel *infoLabel = [[UILabel alloc] initWithFrame:CGRectMake(26,5,newFrame.size.width-32,newFrame.size.height-12)];
infoLabel.text = myAnnotation.title;
infoLabel.backgroundColor = [UIColor clearColor];
infoLabel.textColor = [UIColor blackColor];
infoLabel.textAlignment = UITextAlignmentCenter;
infoLabel.font = [UIFont systemFontOfSize:12];

[self addSubview:infoLabel];
[infoLabel release];

In this example, I'm adding a custom pin to a MKAnnotation class that resizes a UILabel according to the text size. It also adds an image on the left side of the view, so you see some of the code managing the proper spacing to handle the image and padding.

The key is to use CGSize titleSize = [myAnnotation.THETEXT sizeWithFont:[UIFont systemFontOfSize:12]]; and then redefine the view's dimensions. You can apply this logic to any view.

Although Aaron's answer works for some, it didn't work for me. This is a far more detailed explanation that you should try immediately before going anywhere else if you want a more dynamic view with an image and resizable UILabel. I already did all the work for you!!

Name does not exist in the current context

I also faced a similar issue. The reason was that I had the changes done in the .aspx page but not the designer page and hence I got the mentioned error. When the reference was created in the designer page I was able to build the solution.

Filename timestamp in Windows CMD batch script getting truncated

In the past, I've used a .cmd script I found on the Internet. I hate the way localization normally messes with dates. Anytime you have dates in filenames (or anywhere else, if I may be so bold) I figure you want them in ISO 8601 format:

2015-02-19T14:54:51Z

or something else that has Y M D H M in that order, such as

2015-02-19 14:54

because it fixes the MDY / DMY ambiguity and because it's sortable as text.

I don't know where I got that .cmd script, but it may have been http://ss64.com/nt/syntax-getdate.html, which works beautifully on my YYYY-MM-DD Windows 8.1 and on a M/D/YYYY vanilla install of Windows 7. Both give the same format:

2015-02-09 04:43

How do I set 'semi-bold' font via CSS? Font-weight of 600 doesn't make it look like the semi-bold I see in my Photoshop file

Select fonts by specifying the weights you need on load

Font-families consist of several distinct fonts

For example, extra-bold will make the font look quite different in say, Photoshop, because you're selecting a different font. The same applies to italic font, which can look very different indeed. Setting font-weight:800 or font-style:italic may result in just a best effort of the web browser to fatten or slant the normal font in the family.

Even though you're loading a font-family, you must specify the weights and styles you need for some web browsers to let you select a different font in the family with font-weight and font-style.

Example

This example specifies the light, normal, normal italic, bold, and extra-bold fonts in the font family Open Sans:

_x000D_
_x000D_
<html>_x000D_
  <head>_x000D_
    <link rel="stylesheet"_x000D_
          href="https://fonts.googleapis.com/css?family=Open+Sans:100,400,400i,600,800">_x000D_
    <style>_x000D_
      body {_x000D_
        font-family: 'Open Sans', serif;_x000D_
        font-size: 48px;_x000D_
      }_x000D_
    </style>_x000D_
  </head>_x000D_
  <body>    _x000D_
    <div style="font-weight:400">Didn't work with all the fonts</div>_x000D_
   <div style="font-weight:600">Didn't work with all the fonts</div>_x000D_
   <div style="font-weight:800">Didn't work with all the fonts</div>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Reference

(Quora warning, please remove if not allowed.)

https://www.quora.com/How-do-I-make-Open-Sans-extra-bold-once-imported-from-Google-Fonts

Testing

Tested working in Firefox 66.0.3 on Mac and Firefox 36.0.1 in Windows.

Non-Google fonts

Other fonts must be uploaded to the server, style and weight specified by their individual names.

System fonts

Assume nothing, font-wise, about what device is visiting your website or what fonts are installed on its OS.

(You may use the fall-backs of serif and sans-serif, but you will get the font mapped to these by the individual web browser version used, within the fonts available in the OS version it's running under, and not what you designed.)

Testing should be done with the font temporarily uninstalled from your system, to be sure that your design is in effect.

How to catch a click event on a button?

Just declare a method,e.g:if ur button id is button1 then,

button1.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Toast.makeText(Context, "Hello", Toast.LENGTH_SHORT).show();
        }
    });

If you want to make the imageview1 visible then in that method write:

imageview1.setVisibility(ImageView.VISIBLE);

ToString() function in Go

Another example with a struct :

package types

import "fmt"

type MyType struct {
    Id   int    
    Name string
}

func (t MyType) String() string {
    return fmt.Sprintf(
    "[%d : %s]",
    t.Id, 
    t.Name)
}

Be careful when using it,
concatenation with '+' doesn't compile :

t := types.MyType{ 12, "Blabla" }

fmt.Println(t) // OK
fmt.Printf("t : %s \n", t) // OK
//fmt.Println("t : " + t) // Compiler error !!!
fmt.Println("t : " + t.String()) // OK if calling the function explicitly

Floating point vs integer calculations on modern hardware

Alas, I can only give you an "it depends" answer...

From my experience, there are many, many variables to performance...especially between integer & floating point math. It varies strongly from processor to processor (even within the same family such as x86) because different processors have different "pipeline" lengths. Also, some operations are generally very simple (such as addition) and have an accelerated route through the processor, and others (such as division) take much, much longer.

The other big variable is where the data reside. If you only have a few values to add, then all of the data can reside in cache, where they can be quickly sent to the CPU. A very, very slow floating point operation that already has the data in cache will be many times faster than an integer operation where an integer needs to be copied from system memory.

I assume that you are asking this question because you are working on a performance critical application. If you are developing for the x86 architecture, and you need extra performance, you might want to look into using the SSE extensions. This can greatly speed up single-precision floating point arithmetic, as the same operation can be performed on multiple data at once, plus there is a separate* bank of registers for the SSE operations. (I noticed in your second example you used "float" instead of "double", making me think you are using single-precision math).

*Note: Using the old MMX instructions would actually slow down programs, because those old instructions actually used the same registers as the FPU does, making it impossible to use both the FPU and MMX at the same time.

IIS7: A process serving application pool 'YYYYY' suffered a fatal communication error with the Windows Process Activation Service

Debug Diagnostics Tool (DebugDiag) can be a lifesaver. It creates and analyze IIS crash dumps. I figured out my crash in minutes once I saw the call stack. https://support.microsoft.com/en-us/kb/919789

ActiveModel::ForbiddenAttributesError when creating new user

I guess you are using Rails 4. If so, the needed parameters must be marked as required.

You might want to do it like this:

class UsersController < ApplicationController

  def create
    @user = User.new(user_params)
    # ...
  end

  private

  def user_params
    params.require(:user).permit(:username, :email, :password, :salt, :encrypted_password)
  end
end

Update elements in a JSONObject

Generic way to update the any JSONObjet with new values.

private static void updateJsonValues(JsonObject jsonObj) {
    for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {
        JsonElement element = entry.getValue();
        if (element.isJsonArray()) {
            parseJsonArray(element.getAsJsonArray());
        } else if (element.isJsonObject()) {
            updateJsonValues(element.getAsJsonObject());
        } else if (element.isJsonPrimitive()) {
            jsonObj.addProperty(entry.getKey(), "<provide new value>");
        }

    }
}

private static void parseJsonArray(JsonArray asJsonArray) {
    for (int index = 0; index < asJsonArray.size(); index++) {
        JsonElement element = asJsonArray.get(index);
        if (element.isJsonArray()) {
            parseJsonArray(element.getAsJsonArray());
        } else if (element.isJsonObject()) {
            updateJsonValues(element.getAsJsonObject());
        }

    }
}

What is the "N+1 selects problem" in ORM (Object-Relational Mapping)?

The supplied link has a very simply example of the n + 1 problem. If you apply it to Hibernate it's basically talking about the same thing. When you query for an object, the entity is loaded but any associations (unless configured otherwise) will be lazy loaded. Hence one query for the root objects and another query to load the associations for each of these. 100 objects returned means one initial query and then 100 additional queries to get the association for each, n + 1.

http://pramatr.com/2009/02/05/sql-n-1-selects-explained/

Spark DataFrame TimestampType - how to get Year, Month, Day values from field?

Actually, we really do not need to import any python library. We can separate the year, month, date using simple SQL. See the below example,

+----------+
|       _c0|
+----------+
|1872-11-30|
|1873-03-08|
|1874-03-07|
|1875-03-06|
|1876-03-04|
|1876-03-25|
|1877-03-03|
|1877-03-05|
|1878-03-02|
|1878-03-23|
|1879-01-18|

I have a date column in my data frame which contains the date, month and year and assume I want to extract only the year from the column.

df.createOrReplaceTempView("res")
sqlDF = spark.sql("SELECT EXTRACT(year from `_c0`) FROM res ")

Here I'm creating a temporary view and store the year values using this single line and the output will be,

+-----------------------+
|year(CAST(_c0 AS DATE))|
+-----------------------+
|                   1872|
|                   1873|
|                   1874|
|                   1875|
|                   1876|
|                   1876|
|                   1877|
|                   1877|
|                   1878|
|                   1878|
|                   1879|
|                   1879|
|                   1879|

How do I use a PriorityQueue?

Use the constructor overload which takes a Comparator<? super E> comparator and pass in a comparator which compares in the appropriate way for your sort order. If you give an example of how you want to sort, we can provide some sample code to implement the comparator if you're not sure. (It's pretty straightforward though.)

As has been said elsewhere: offer and add are just different interface method implementations. In the JDK source I've got, add calls offer. Although add and offer have potentially different behaviour in general due to the ability for offer to indicate that the value can't be added due to size limitations, this difference is irrelevant in PriorityQueue which is unbounded.

Here's an example of a priority queue sorting by string length:

// Test.java
import java.util.Comparator;
import java.util.PriorityQueue;

public class Test {
    public static void main(String[] args) {
        Comparator<String> comparator = new StringLengthComparator();
        PriorityQueue<String> queue = new PriorityQueue<String>(10, comparator);
        queue.add("short");
        queue.add("very long indeed");
        queue.add("medium");
        while (queue.size() != 0) {
            System.out.println(queue.remove());
        }
    }
}

// StringLengthComparator.java
import java.util.Comparator;

public class StringLengthComparator implements Comparator<String> {
    @Override
    public int compare(String x, String y) {
        // Assume neither string is null. Real code should
        // probably be more robust
        // You could also just return x.length() - y.length(),
        // which would be more efficient.
        if (x.length() < y.length()) {
            return -1;
        }
        if (x.length() > y.length()) {
            return 1;
        }
        return 0;
    }
}

Here is the output:

short

medium

very long indeed

How to implement one-to-one, one-to-many and many-to-many relationships while designing tables?

One-to-many

The one-to-many table relationship looks as follows:

One-to-many

In a relational database system, a one-to-many table relationship links two tables based on a Foreign Key column in the child which references the Primary Key of the parent table row.

In the table diagram above, the post_id column in the post_comment table has a Foreign Key relationship with the post table id Primary Key column:

ALTER TABLE
    post_comment
ADD CONSTRAINT
    fk_post_comment_post_id
FOREIGN KEY (post_id) REFERENCES post

One-to-one

The one-to-one table relationship looks as follows:

One-to-one

In a relational database system, a one-to-one table relationship links two tables based on a Primary Key column in the child which is also a Foreign Key referencing the Primary Key of the parent table row.

Therefore, we can say that the child table shares the Primary Key with the parent table.

In the table diagram above, the id column in the post_details table has also a Foreign Key relationship with the post table id Primary Key column:

ALTER TABLE
    post_details
ADD CONSTRAINT
    fk_post_details_id
FOREIGN KEY (id) REFERENCES post

Many-to-many

The many-to-many table relationship looks as follows:

Many-to-many

In a relational database system, a many-to-many table relationship links two parent tables via a child table which contains two Foreign Key columns referencing the Primary Key columns of the two parent tables.

In the table diagram above, the post_id column in the post_tag table has also a Foreign Key relationship with the post table id Primary Key column:

ALTER TABLE
    post_tag
ADD CONSTRAINT
    fk_post_tag_post_id
FOREIGN KEY (post_id) REFERENCES post

And, the tag_id column in the post_tag table has a Foreign Key relationship with the tag table id Primary Key column:

ALTER TABLE
    post_tag
ADD CONSTRAINT
    fk_post_tag_tag_id
FOREIGN KEY (tag_id) REFERENCES tag

Sort array of objects by string property value

There are many good answers here, but I would like to point out that they can be extended very simply to achieve a lot more complex sorting. The only thing you have to do is to use the OR operator to chain comparision functions like this:

objs.sort((a,b)=> fn1(a,b) || fn2(a,b) || fn3(a,b) )

Where fn1, fn2, ... are the sort functions which return [-1,0,1]. This results in "sorting by fn1", "sorting by fn2" which is pretty much equal to ORDER BY in SQL.

This solution is based on the behaviour of || operator which evaluates to the first evaluated expression which can be converted to true.

The simplest form has only one inlined function like this:

// ORDER BY last_nom
objs.sort((a,b)=> a.last_nom.localeCompare(b.last_nom) )

Having two steps with last_nom,first_nom sort order would look like this:

// ORDER_BY last_nom, first_nom
objs.sort((a,b)=> a.last_nom.localeCompare(b.last_nom) || 
                  a.first_nom.localeCompare(b.first_nom)  )

A generic comparision function could be something like this:

// ORDER BY <n>
let cmp = (a,b,n)=>a[n].localeCompare(b[n])

This function could be extended to support numeric fields, case sensitity, arbitary datatypes etc.

You can them use it with chaining them by sort priority:

// ORDER_BY last_nom, first_nom
objs.sort((a,b)=> cmp(a,b, "last_nom") || cmp(a,b, "first_nom") )
// ORDER_BY last_nom, first_nom DESC
objs.sort((a,b)=> cmp(a,b, "last_nom") || -cmp(a,b, "first_nom") )
// ORDER_BY last_nom DESC, first_nom DESC
objs.sort((a,b)=> -cmp(a,b, "last_nom") || -cmp(a,b, "first_nom") )

The point here is that pure JavaScript with functional approach can take you a long way without external libraries or complex code. It is also very effective, since no string parsing have to be done

React Native android build failed. SDK location not found

If you are on windows escape (add backlashes to) the backslashes and the colon in the android/local.properties file. If its not there then create it

sdk.dir = C\:\\Android\\sdk

C++ "Access violation reading location" Error

You haven't posted the findvertex method, but Access Reading Violation with an offset like 0x00000048 means that the Vertex* f; in your getCost function is receiving null, and when trying to access the member adj in the null Vertex pointer (that is, in f), it is offsetting to adj (in this case, 72 bytes ( 0x48 bytes in decimal )), it's reading near the 0 or null memory address.

Doing a read like this violates Operating-System protected memory, and more importantly means whatever you're pointing at isn't a valid pointer. Make sure findvertex isn't returning null, or do a comparisong for null on f before using it to keep yourself sane (or use an assert):

assert( f != null ); // A good sanity check

EDIT:

If you have a map for doing something like a find, you can just use the map's find method to make sure the vertex exists:

Vertex* Graph::findvertex(string s)
{
    vmap::iterator itr = map1.find( s );
    if ( itr == map1.end() )
    {
        return NULL;
    }
    return itr->second;
}

Just make sure you're still careful to handle the error case where it does return NULL. Otherwise, you'll keep getting this access violation.

`getchar()` gives the same output as the input string

getchar() reads a single character of input and returns that character as the value of the function. If there is an error reading the character, or if the end of input is reached, getchar() returns a special value, represented by EOF.

How do I remove an object from an array with JavaScript?

If you have access to ES2015 functions, and you're looking for a more functional approach I'd go with something like:

const people = [
  { id: 1, name: 'serdar' },
  { id: 5, name: 'alex' },
  { id: 300, name: 'brittany' }
];

const idToRemove = 5;

const filteredPeople = people.filter((item) => item.id !== idToRemove);

// [
//   { id: 1, name: 'serdar' },
//   { id: 300, name: 'brittany' }
// [

Watch out though, filter() is non-mutating, so you'll get a new array back.

See the Mozilla Developer Network notes on Filter.

Replace text inside td using jQuery having td containing other elements

Using text nodes in jquery is a particularly delicate endeavour and most operations are made to skip them altogether.

Instead of going through the trouble of carefully avoiding the wrong nodes, why not just wrap whatever you need to replace inside a <span> for instance:

<td><span class="replaceme">8: Tap on APN and Enter <B>www</B>.</span></td>

Then:

$('.replaceme').html('Whatever <b>HTML</b> you want here.');

How to deal with page breaks when printing a large HTML table

Note: when using the page-break-after:always for the tag it will create a page break after the last bit of the table, creating an entirely blank page at the end every time! To fix this just change it to page-break-after:auto. It will break correctly and not create an extra blank page.

<html>
<head>
<style>
@media print
{
  table { page-break-after:auto }
  tr    { page-break-inside:avoid; page-break-after:auto }
  td    { page-break-inside:avoid; page-break-after:auto }
  thead { display:table-header-group }
  tfoot { display:table-footer-group }
}
</style>
</head>

<body>
....
</body>
</html>

Media Queries - In between two widths

@Jonathan Sampson i think your solution is wrong if you use multiple @media.

You should use (min-width first):

@media screen and (min-width:400px) and (max-width:900px){
   ...
}

Linq to SQL how to do "where [column] in (list of values)"

Here is how I do it by using HashSet

        HashSet<String> hs = new HashSet<string>(new String[] { "Pluto", "Earth", "Neptune" });
        String[] arr =
        {
            "Pluto",
            "Earth",
            "Neptune",
            "Jupiter",
            "Saturn",
            "Mercury",
            "Pluto",
            "Earth",
            "Neptune",
            "Jupiter",
            "Saturn",
            "Mercury",
            // etc.
        };
        ICollection<String> coll = arr;

        String[] arrStrFiltered = coll.Where(str => hs.Contains(str)).ToArray();

HashSet is basically almost to O(1) so your complexity remains O(n).

Search File And Find Exact Match And Print Line?

you should use regular expressions to find all you need:

import re
p = re.compile(r'(\d+)')  # a pattern for a number

for line in file :
    if num in p.findall(line) :
        print line

regular expression will return you all numbers in a line as a list, for example:

>>> re.compile(r'(\d+)').findall('123kh234hi56h9234hj29kjh290')
['123', '234', '56', '9234', '29', '290']

so you don't match '200' or '220' for '20'.

How to echo shell commands as they are executed

Combining all the answers I found this to be the best

exe(){
    set -x
    "$@"
    { set +x; } 2>/dev/null
}
# example
exe go generate ./...

{ set +x; } 2>/dev/null from https://stackoverflow.com/a/19226038/8608146

Get unicode value of a character

are you picky with using Unicode because with java its more simple if you write your program to use "dec" value or (HTML-Code) then you can simply cast data types between char and int

char a = 98;
char b = 'b';
char c = (char) (b+0002);

System.out.println(a);
System.out.println((int)b);
System.out.println((int)c);
System.out.println(c);

Gives this output

b
98
100
d

Check if an array is empty or exists

You should do this

    if (!image_array) {
      // image_array defined but not assigned automatically coerces to false
    } else if (!(0 in image_array)) {
      // empty array
      // doSomething
    }

Python to print out status bar and percentage

Here you can use following code as a function:

def drawProgressBar(percent, barLen = 20):
    sys.stdout.write("\r")
    progress = ""
    for i in range(barLen):
        if i < int(barLen * percent):
            progress += "="
        else:
            progress += " "
    sys.stdout.write("[ %s ] %.2f%%" % (progress, percent * 100))
    sys.stdout.flush()

With use of .format:

def drawProgressBar(percent, barLen = 20):
    # percent float from 0 to 1. 
    sys.stdout.write("\r")
    sys.stdout.write("[{:<{}}] {:.0f}%".format("=" * int(barLen * percent), barLen, percent * 100))
    sys.stdout.flush()

Converting a datetime string to timestamp in Javascript

Date.parse() isn't a constructor, its a static method.

So, just use

var timeInMillis = Date.parse(s);

instead of

var timeInMillis = new Date.parse(s);

How to send data to COM PORT using JAVA?

An alternative to javax.comm is the rxtx library which supports more platforms than javax.comm.

YouTube URL in Video Tag

This will give you the answer you need. The easiest way to do it is with the youTube-provided methods. How to Embed Youtube Videos into HTML5 <video> Tag?

How to rollback a specific migration?

To rollback the last migration you can do:

rake db:rollback

If you want to rollback a specific migration with a version you should do:

rake db:migrate:down VERSION=YOUR_MIGRATION_VERSION

For e.g. if the version is 20141201122027, you will do:

rake db:migrate:down VERSION=20141201122027

to rollback that specific migration.

Setting Authorization Header of HttpClient

To set basic authentication with C# HttpClient. The following code is working for me.

   using (var client = new HttpClient())
        {
            var webUrl ="http://localhost/saleapi/api/";
            var uri = "api/sales";
            client.BaseAddress = new Uri(webUrl);
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.ConnectionClose = true;

            //Set Basic Auth
            var user = "username";
            var password = "password";
            var base64String =Convert.ToBase64String( Encoding.ASCII.GetBytes($"{user}:{password}"));
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",base64String);

            var result = await client.PostAsJsonAsync(uri, model);
            return result;
        }

Enable/disable buttons with Angular

export class ClassComponent implements OnInit {
  classes = [
{
  name: 'string',
  level: 'string',
  code: 'number',
  currentLesson: '1'
}]


checkCurrentLession(current){

 this.classes.forEach((obj)=>{
    if(obj.currentLession == current){
      return true;
    }

  });
  return false;
}


<ul class="table lessonOverview">
        <li>
          <p>Lesson 1</p>
          <button [routerLink]="['/lesson1']" 
             [disabled]="checkCurrentLession(1)" class="primair">
               Start lesson</button>
        </li>
        <li>
          <p>Lesson 2</p>
          <button [routerLink]="['/lesson2']" 
             [disabled]="!checkCurrentLession(2)" class="primair">
               Start lesson</button>
        </li>
     </ul>

How to sort List of objects by some property

In java you need to use the static Collections.sort method. Here is an example for a list of CompanyRole objects, sorted first by begin and then by end. You can easily adapt for your own object.

private static void order(List<TextComponent> roles) {

    Collections.sort(roles, new Comparator() {
        @Override
        public int compare(Object o1, Object o2) {
            int x1 = ((CompanyRole) o1).getBegin();
            int x2 = ((CompanyRole) o2).getBegin();

            if (x1 != x2) {
                return x1 - x2;
            } else {
                int y1 = ((CompanyRole) o1).getEnd();
                int y2 = ((CompanyRole) o2).getEnd();
                return y2 - y1;
            }
        }
    });
}

How to use regex in String.contains() method in Java

If you want to check if a string contains substring or not using regex, the closest you can do is by using find() -

    private static final validPattern =   "\\bstores\\b.*\\bstore\\b.*\\bproduct\\b"
    Pattern pattern = Pattern.compile(validPattern);
    Matcher matcher = pattern.matcher(inputString);
    System.out.print(matcher.find()); // should print true or false.

Note the difference between matches() and find(), matches() return true if the whole string matches the given pattern. find() tries to find a substring that matches the pattern in a given input string. Also by using find() you don't have to add extra matching like - (?s).* at the beginning and .* at the end of your regex pattern.

Append column to pandas dataframe

Just as a matter of fact:

data_joined = dat1.join(dat2)
print(data_joined)

Adding padding to a tkinter widget only on one side

The padding options padx and pady of the grid and pack methods can take a 2-tuple that represent the left/right and top/bottom padding.

Here's an example:

import tkinter as tk

class MyApp():
    def __init__(self):
        self.root = tk.Tk()
        l1 = tk.Label(self.root, text="Hello")
        l2 = tk.Label(self.root, text="World")
        l1.grid(row=0, column=0, padx=(100, 10))
        l2.grid(row=1, column=0, padx=(10, 100)) 

app = MyApp()
app.root.mainloop()

how to list all sub directories in a directory

show all directry and sub directories

def dir():

from glob import glob

dir = []

dir = glob("path")

def all_sub_dir(dir):
{

     for item in dir:

            {
                b = "{}\*".format(item)
                dir += glob(b)
            }
         print(dir)
}

Check if string has space in between (or anywhere)

Trim() will only remove leading or trailing spaces.

Try .Contains() to check if a string contains white space

"sossjjs sskkk".Contains(" ") // returns true

Fixed point vs Floating point number

From my understanding, fixed-point arithmetic is done using integers. where the decimal part is stored in a fixed amount of bits, or the number is multiplied by how many digits of decimal precision is needed.

For example, If the number 12.34 needs to be stored and we only need two digits of precision after the decimal point, the number is multiplied by 100 to get 1234. When performing math on this number, we'd use this rule set. Adding 5620 or 56.20 to this number would yield 6854 in data or 68.54.

If we want to calculate the decimal part of a fixed-point number, we use the modulo (%) operand.

12.34 (pseudocode):

v1 = 1234 / 100 // get the whole number
v2 = 1234 % 100 // get the decimal number (100ths of a whole).
print v1 + "." + v2 // "12.34"

Floating point numbers are a completely different story in programming. The current standard for floating point numbers use something like 23 bits for the data of the number, 8 bits for the exponent, and 1 but for sign. See this Wikipedia link for more information on this.

Property getters and setters

Update for Swift 5.1

As of Swift 5.1 you can now get your variable without using get keyword. For example:

var helloWorld: String {
"Hello World"
}

How to increase request timeout in IIS?

In IIS Manager, right click on the site and go to Manage Web Site -> Advanced Settings. Under Connection Limits option, you should see Connection Time-out.

How to terminate a Python script

You can also use simply exit().

Keep in mind that sys.exit(), exit(), quit(), and os._exit(0) kill the Python interpreter. Therefore, if it appears in a script called from another script by execfile(), it stops execution of both scripts.

See "Stop execution of a script called with execfile" to avoid this.

How to get all checked checkboxes

Get all the checked checkbox value in an array - one liner

_x000D_
_x000D_
const data = [...document.querySelectorAll('.inp:checked')].map(e => e.value);_x000D_
console.log(data);
_x000D_
<div class="row">_x000D_
    <input class="custom-control-input inp"type="checkbox" id="inlineCheckbox1" Checked value="option1"> _x000D_
    <label class="custom-control-label" for="inlineCheckbox1">Option1</label>_x000D_
    <input class="custom-control-input inp"  type="checkbox" id="inlineCheckbox1" value="option2"> _x000D_
    <label class="custom-control-label" for="inlineCheckbox1">Option2</label>_x000D_
    <input class="custom-control-input inp" Checked  type="checkbox" id="inlineCheckbox1" value="option3"> _x000D_
    <label class="custom-control-label" for="inlineCheckbox1">Option3</label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

MySQL default datetime through phpmyadmin

You're getting that error because the default value current_time is not valid for the type DATETIME. That's what it says, and that's whats going on.

The only field you can use current_time on is a timestamp.

ScrollIntoView() causing the whole page to move

I've added a way to display the imporper behavior of the ScrollIntoView - http://jsfiddle.net/LEqjm/258/ [it should be a comment but I don't have enough reputation]

$("ul").click(function() {
    var target = document.getElementById("target");
if ($('#scrollTop').attr('checked')) {
    target.parentNode.scrollTop = target.offsetTop;    
} else {
        target.scrollIntoView(!0);
}
});

How to correctly get image from 'Resources' folder in NetBeans

For me it worked like I had images in icons folder under src and I wrote below code.

new ImageIcon(getClass().getResource("/icons/rsz_measurment_01.png"));

AES vs Blowfish for file encryption

The algorithm choice probably doesn't matter that much. I'd use AES since it's been better researched. What's much more important is choosing the right operation mode and key derivation function.

You might want to take a look at the TrueCrypt format specification for inspiration if you want fast random access. If you don't need random access than XTS isn't the optimal mode, since it has weaknesses other modes don't. And you might want to add some kind of integrity check(or message authentication code) too.

A circular reference was detected while serializing an object of type 'SubSonic.Schema .DatabaseColumn'.

//first: Create a class as your view model

public class EventViewModel 
{
 public int Id{get;set}
 public string Property1{get;set;}
 public string Property2{get;set;}
}
//then from your method
[HttpGet]
public async Task<ActionResult> GetEvent()
{
 var events = await db.Event.Find(x => x.ID != 0);
 List<EventViewModel> model = events.Select(event => new EventViewModel(){
 Id = event.Id,
 Property1 = event.Property1,
 Property1 = event.Property2
}).ToList();
 return Json(new{ data = model }, JsonRequestBehavior.AllowGet);
}

How to replace multiple white spaces with one white space

Here is the Solution i work with. Without RegEx and String.Split.

public static string TrimWhiteSpace(this string Value)
{
    StringBuilder sbOut = new StringBuilder();
    if (!string.IsNullOrEmpty(Value))
    {
        bool IsWhiteSpace = false;
        for (int i = 0; i < Value.Length; i++)
        {
            if (char.IsWhiteSpace(Value[i])) //Comparion with WhiteSpace
            {
                if (!IsWhiteSpace) //Comparison with previous Char
                {
                    sbOut.Append(Value[i]);
                    IsWhiteSpace = true;
                }
            }
            else
            {
                IsWhiteSpace = false;
                sbOut.Append(Value[i]);
            }
        }
    }
    return sbOut.ToString();
}

so you can:

string cleanedString = dirtyString.TrimWhiteSpace();

How do I find an element that contains specific text in Selenium WebDriver (Python)?

Try the following:

driver.find_elements_by_xpath("//*[contains(text(), 'My Button')]")

What are the pros and cons of parquet format compared to other formats?

Avro is a row-based storage format for Hadoop.

Parquet is a column-based storage format for Hadoop.

If your use case typically scans or retrieves all of the fields in a row in each query, Avro is usually the best choice.

If your dataset has many columns, and your use case typically involves working with a subset of those columns rather than entire records, Parquet is optimized for that kind of work.

Source

How can I make the contents of a fixed element scrollable only when it exceeds the height of the viewport?

For your purpose, you can just use

position: absolute;
top: 0%;

and it still be resizable, scrollable and responsive.

How might I convert a double to the nearest integer value?

I know this question is old, but I came across it in my search for the answer to my similar question. I thought I would share the very useful tip that I have been given.

When converting to int, simply add .5 to your value before downcasting. As downcasting to int always drops to the lower number (e.g. (int)1.7 == 1), if your number is .5 or higher, adding .5 will bring it up into the next number and your downcast to int should return the correct value. (e.g. (int)(1.8 + .5) == 2)

How to use matplotlib tight layout with Figure?

Just call fig.tight_layout() as you normally would. (pyplot is just a convenience wrapper. In most cases, you only use it to quickly generate figure and axes objects and then call their methods directly.)

There shouldn't be a difference between the QtAgg backend and the default backend (or if there is, it's a bug).

E.g.

import matplotlib.pyplot as plt

#-- In your case, you'd do something more like:
# from matplotlib.figure import Figure
# fig = Figure()
#-- ...but we want to use it interactive for a quick example, so 
#--    we'll do it this way
fig, axes = plt.subplots(nrows=4, ncols=4)

for i, ax in enumerate(axes.flat, start=1):
    ax.set_title('Test Axes {}'.format(i))
    ax.set_xlabel('X axis')
    ax.set_ylabel('Y axis')

plt.show()

Before Tight Layout

enter image description here

After Tight Layout

import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=4, ncols=4)

for i, ax in enumerate(axes.flat, start=1):
    ax.set_title('Test Axes {}'.format(i))
    ax.set_xlabel('X axis')
    ax.set_ylabel('Y axis')

fig.tight_layout()

plt.show()

enter image description here

How do we use runOnUiThread in Android?

  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        gifImageView = (GifImageView) findViewById(R.id.GifImageView);
        gifImageView.setGifImageResource(R.drawable.success1);

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //dummy delay for 2 second
                    Thread.sleep(8000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                //update ui on UI thread
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        gifImageView.setGifImageResource(R.drawable.success);
                    }
                });

            }
        }).start();

    }

CSS Positioning Elements Next to each other

If you want them to be displayed side by side, why is sideContent the child of mainContent? make them siblings then use:

float:left; display:inline; width: 49%;

on both of them.

#mainContent, #sideContent {float:left; display:inline; width: 49%;}

Iframe positioning

It's because you're missing position:relative; on #contentframe

<div id="contentframe" style="position:relative; top: 160px; left: 0px;">

position:absolute; positions itself against the closest ancestor that has a position that is not static. Since the default is static that is what was causing your issue.

How to save S3 object to a file using boto3

boto3 now has a nicer interface than the client:

resource = boto3.resource('s3')
my_bucket = resource.Bucket('MyBucket')
my_bucket.download_file(key, local_filename)

This by itself isn't tremendously better than the client in the accepted answer (although the docs say that it does a better job retrying uploads and downloads on failure) but considering that resources are generally more ergonomic (for example, the s3 bucket and object resources are nicer than the client methods) this does allow you to stay at the resource layer without having to drop down.

Resources generally can be created in the same way as clients, and they take all or most of the same arguments and just forward them to their internal clients.

How can I mark a foreign key constraint using Hibernate annotations?

@Column is not the appropriate annotation. You don't want to store a whole User or Question in a column. You want to create an association between the entities. Start by renaming Questions to Question, since an instance represents a single question, and not several ones. Then create the association:

@Entity
@Table(name = "UserAnswer")
public class UserAnswer {

    // this entity needs an ID:
    @Id
    @Column(name="useranswer_id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @ManyToOne
    @JoinColumn(name = "user_id")
    private User user;

    @ManyToOne
    @JoinColumn(name = "question_id")
    private Question question;

    @Column(name = "response")
    private String response;

    //getter and setter 
}

The Hibernate documentation explains that. Read it. And also read the javadoc of the annotations.

Bootstrap datepicker disabling past dates without current date

You can find your solution in this link below: https://codepen.io/ahmetcadirci25/pen/NpMNzJ

Thats work for me.

My code:

        var date = new Date();
        date.setDate(date.getDate());

        $('#datetimepicker1').datetimepicker({
            isRTL: false,
            format: 'dd.mm.yyyy hh:ii',
            autoclose: true,
            language: 'tr',
            startDate: date
        });

How to check if IEnumerable is null or empty?

This may help

public static bool IsAny<T>(this IEnumerable<T> enumerable)
{
    return enumerable?.Any() == true;
}

public static bool IsNullOrEmpty<T>(this IEnumerable<T> enumerable)
{
    return enumerable?.Any() != true;
}

Replace all spaces in a string with '+'

Here's an alternative that doesn't require regex:

var str = 'a b c';
var replaced = str.split(' ').join('+');

Calling a Fragment method from a parent Activity

First you create method in your fragment like

public void name()
{


}

in your activity you add this

add onCreate() method

myfragment fragment=new myfragment()

finally call the method where you want to call add this

fragment.method_name();

try this code

The EXECUTE permission was denied on the object 'xxxxxxx', database 'zzzzzzz', schema 'dbo'

The general answer is to grant execute permission as explained above. But that doesn't work if the schema owner of SP is different to underlying objects.

Check schema owners by:

select name, USER_NAME(s.principal_id) AS Schema_Owner from sys.schemas s

To change the owner of an schema you can:

ALTER AUTHORIZATION ON SCHEMA::YOUR_SCHEMA TO YOUR_USER;

Examples:

ALTER AUTHORIZATION ON SCHEMA::Claim TO dbo
ALTER AUTHORIZATION ON SCHEMA::datix TO user1;

Finally if within your SP you are truncating a table or changing structure you may want to add WITH EXECUTE AS OWNER in your SP:

ALTER procedure [myProcedure] 
WITH EXECUTE AS OWNER

as

truncate table etl.temp

Double.TryParse or Convert.ToDouble - which is faster and safer?

Personally, I find the TryParse method easier to read, which one you'll actually want to use depends on your use-case: if errors can be handled locally you are expecting errors and a bool from TryParse is good, else you might want to just let the exceptions fly.

I would expect the TryParse to be faster too, since it avoids the overhead of exception handling. But use a benchmark tool, like Jon Skeet's MiniBench to compare the various possibilities.

Where can I download IntelliJ IDEA Color Schemes?

I like ZenBurn theme, I think it is very mild and appealing for the eye. I had here my own theme's settings JAR file, but I stopped updating it. I still think that theme is very good so I updated this post to a suitable theme with similar colors which is already available on @Yarg's web site screenshot

Link towards the theme

How can one create an overlay in css?

If you don't mind messing with z-index, but you want to avoid adding extra div for overlay, you can use the following approach

/* make sure ::before is positioned relative to .foo */
.foo { position: relative; }

/* overlay */
.foo::before {
    content: '';
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.5);
    z-index: 0;
}
/* make sure all elements inside .foo placed above overlay element */
.foo > * { z-index: 1; }

How to get the day name from a selected date?

System.Threading.Thread.CurrentThread.CurrentUICulture.DateTimeFormat.GetDayName(System.DateTime.Now.DayOfWeek)

or

System.Threading.Thread.CurrentThread.CurrentUICulture.DateTimeFormat.GetDayName(DateTime.Parse("23/10/2009").DayOfWeek)

preg_match in JavaScript?

var text = 'price[5][68]';
var regex = /price\[(\d+)\]\[(\d+)\]/gi;
match = regex.exec(text);

match[1] and match[2] will contain the numbers you're looking for.

How do you rebase the current branch's changes on top of changes being merged in?

You've got what rebase does backwards. git rebase master does what you're asking for — takes the changes on the current branch (since its divergence from master) and replays them on top of master, then sets the head of the current branch to be the head of that new history. It doesn't replay the changes from master on top of the current branch.

Get current NSDate in timestamp format

Here's what I use:

NSString * timestamp = [NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSince1970] * 1000];

(times 1000 for milliseconds, otherwise, take that out)

If You're using it all the time, it might be nice to declare a macro

#define TimeStamp [NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSince1970] * 1000]

Then Call it like this:

NSString * timestamp = TimeStamp;

Or as a method:

- (NSString *) timeStamp {
    return [NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSince1970] * 1000];
}

As TimeInterval

- (NSTimeInterval) timeStamp {
    return [[NSDate date] timeIntervalSince1970] * 1000;
}

NOTE:

The 1000 is to convert the timestamp to milliseconds. You can remove this if you prefer your timeInterval in seconds.

Swift

If you'd like a global variable in Swift, you could use this:

var Timestamp: String {
    return "\(NSDate().timeIntervalSince1970 * 1000)"
}

Then, you can call it

println("Timestamp: \(Timestamp)")

Again, the *1000 is for miliseconds, if you'd prefer, you can remove that. If you want to keep it as an NSTimeInterval

var Timestamp: NSTimeInterval {
    return NSDate().timeIntervalSince1970 * 1000
}

Declare these outside of the context of any class and they'll be accessible anywhere.

Android, How can I Convert String to Date?

It could be a good idea to be careful with the Locale upon which c.getTime().toString(); depends.

One idea is to store the time in seconds (e.g. UNIX time). As an int you can easily compare it, and then you just convert it to string when displaying it to the user.

Finding local IP addresses using Python's stdlib

A machine can have multiple network interfaces (including the local loopback 127.0.0.1) you mentioned. As far as the OS is concerned, it's also a "real IP address".

If you want to track all of interfaces, have a look at the following Puthon package : http://alastairs-place.net/netifaces/

I think you can avoid having gethostbyname return 127.0.0.1 if you ommit the loopback entry from your hosts file. (to be verified).

C subscripted value is neither array nor pointer nor vector when assigning an array element value

C lets you use the subscript operator [] on arrays and on pointers. When you use this operator on a pointer, the resultant type is the type to which the pointer points to. For example, if you apply [] to int*, the result would be an int.

That is precisely what's going on: you are passing int*, which corresponds to a vector of integers. Using subscript on it once makes it int, so you cannot apply the second subscript to it.

It appears from your code that arr should be a 2-D array. If it is implemented as a "jagged" array (i.e. an array of pointers) then the parameter type should be int **.

Moreover, it appears that you are trying to return a local array. In order to do that legally, you need to allocate the array dynamically, and return a pointer. However, a better approach would be declaring a special struct for your 4x4 matrix, and using it to wrap your fixed-size array, like this:

// This type wraps your 4x4 matrix
typedef struct {
    int arr[4][4];
} FourByFour;
// Now rotate(m) can use FourByFour as a type
FourByFour rotate(FourByFour m) {
    FourByFour D;
    for(int i = 0; i < 4; i ++ ){
        for(int n = 0; n < 4; n++){
            D.arr[i][n] = m.arr[n][3 - i];
        }
    }
    return D;
}
// Here is a demo of your rotate(m) in action:
int main(void) {
    FourByFour S = {.arr = {
        { 1, 4, 10, 3 },
        { 0, 6, 3, 8 },
        { 7, 10 ,8, 5 },
        { 9, 5, 11, 2}
    } };
    FourByFour r = rotate(S);
    for(int i=0; i < 4; i ++ ){
        for(int n=0; n < 4; n++){
            printf("%d ", r.arr[i][n]);
        }
        printf("\n");
    }
    return 0;
}

This prints the following:

3 8 5 2 
10 3 8 11 
4 6 10 5 
1 0 7 9 

Count number of rows within each group

If you want to include 0 counts for month-years that are missing in the data, you can use a little table magic.

data.frame(with(df1, table(Year, Month)))

For example, the toy data.frame in the question, df1, contains no observations of January 2014.

df1
    x Year Month
1   1 2012   Feb
2   2 2014   Feb
3   3 2013   Mar
4   4 2012   Jan
5   5 2014   Feb
6   6 2014   Feb
7   7 2012   Jan
8   8 2014   Feb
9   9 2013   Mar
10 10 2013   Jan
11 11 2013   Jan
12 12 2012   Jan
13 13 2014   Mar
14 14 2012   Mar
15 15 2013   Feb
16 16 2014   Feb
17 17 2014   Mar
18 18 2012   Jan
19 19 2013   Mar
20 20 2012   Jan

The base R aggregate function does not return an observation for January 2014.

aggregate(x ~ Year + Month, data = df1, FUN = length)
  Year Month x
1 2012   Feb 1
2 2013   Feb 1
3 2014   Feb 5
4 2012   Jan 5
5 2013   Jan 2
6 2012   Mar 1
7 2013   Mar 3
8 2014   Mar 2

If you would like an observation of this month-year with 0 as the count, then the above code will return a data.frame with counts for all month-year combinations:

data.frame(with(df1, table(Year, Month)))
  Year Month Freq
1 2012   Feb    1
2 2013   Feb    1
3 2014   Feb    5
4 2012   Jan    5
5 2013   Jan    2
6 2014   Jan    0
7 2012   Mar    1
8 2013   Mar    3
9 2014   Mar    2

Visual Studio: Relative Assembly References Paths

I might be off here, but it seems that the answer is quite obvious: Look at reference paths in the project properties. In our setup I added our common repository folder, to the ref path GUI window, like so

Reference Paths in VS20xx

That way I can copy my dlls (ready for publish) to this folder and every developer now gets the updated DLL every time it builds from this folder.

If the dll is found in the Solution, the builder should prioritize the local version over the published team version.

Get top 1 row of each group

I've done some timings over the various recommendations here, and the results really depend on the size of the table involved, but the most consistent solution is using the CROSS APPLY These tests were run against SQL Server 2008-R2, using a table with 6,500 records, and another (identical schema) with 137 million records. The columns being queried are part of the primary key on the table, and the table width is very small (about 30 bytes). The times are reported by SQL Server from the actual execution plan.

Query                                  Time for 6500 (ms)    Time for 137M(ms)

CROSS APPLY                                    17.9                17.9
SELECT WHERE col = (SELECT MAX(COL)…)           6.6               854.4
DENSE_RANK() OVER PARTITION                     6.6               907.1

I think the really amazing thing was how consistent the time was for the CROSS APPLY regardless of the number of rows involved.

What does <![CDATA[]]> in XML mean?

CDATA stands for Character Data. You can use this to escape some characters which otherwise will be treated as regular XML. The data inside this will not be parsed. For example, if you want to pass a URL that contains & in it, you can use CDATA to do it. Otherwise, you will get an error as it will be parsed as regular XML.

Python: create dictionary using dict() with integer keys?

a = dict(one=1, two=2, three=3)

Providing keyword arguments as in this example only works for keys that are valid Python identifiers. Otherwise, any valid keys can be used.

Media Queries: How to target desktop, tablet, and mobile?

One extra feature is you can also use-media queries in the media attribute of the <link> tag.

<link href="style.css" rel="stylesheet">
<link href="justForFrint.css" rel="stylesheet" media="print">
<link href="deviceSizeDepending.css" rel="stylesheet" media="(min-width: 40em)">

With this, the browser will download all CSS resources, regardless of the media attribute. The difference is that if the media-query of the media attribute is evaluated to false then that .css file and his content will not be render-blocking.

Therefore, it is recommended to use the media attribute in the <link> tag since it guarantees a better user experience.

Here you can read a Google article about this issue https://developers.google.com/web/fundamentals/performance/critical-rendering-path/render-blocking-css

Some tools that will help you to automate the separation of your css code in different files according to your media-querys

Webpack https://www.npmjs.com/package/media-query-plugin https://www.npmjs.com/package/media-query-splitting-plugin

PostCSS https://www.npmjs.com/package/postcss-extract-media-query

Getting the Username from the HKEY_USERS values

It is possible to query this information from WMI. The following command will output a table with a row for every user along with the SID for each user.

wmic useraccount get name,sid

You can also export this information to CSV:

wmic useraccount get name,sid /format:csv > output.csv

I have used this on Vista and 7. For more information see WMIC - Take Command-line Control over WMI.

How do we update URL or query strings using javascript/jQuery without reloading the page?

Prefix URL changes with a hashtag to avoid a redirect.

This redirects

location.href += '&test='true';

This doesn't redirect

location.href += '#&test='true';

python re.split() to split by spaces, commas, and periods, but not in cases like 1,000 or 1.50

Use a negative lookahead and a negative lookbehind:

> s = "one two 3.4 5,6 seven.eight nine,ten"
> parts = re.split('\s|(?<!\d)[,.](?!\d)', s)
['one', 'two', '3.4', '5,6', 'seven', 'eight', 'nine', 'ten']

In other words, you always split by \s (whitespace), and only split by commas and periods if they are not followed (?!\d) or preceded (?<!\d) by a digit.

DEMO.

EDIT: As per @verdesmarald comment, you may want to use the following instead:

> s = "one two 3.4 5,6 seven.eight nine,ten,1.2,a,5"
> print re.split('\s|(?<!\d)[,.]|[,.](?!\d)', s)
['one', 'two', '3.4', '5,6', 'seven', 'eight', 'nine', 'ten', '1.2', 'a', '5']

This will split "1.2,a,5" into ["1.2", "a", "5"].

DEMO.

In oracle, how do I change my session to display UTF8?

Therefore, before starting '$ sqlplus' on OS, run the followings:

  • On Windows

    set NLS_LANG=AMERICAN_AMERICA.UTF8

  • On Unix (Solaris and Linux, centos etc)

    export NLS_LANG=AMERICAN_AMERICA.UTF8

It would also be advisable to set env variable in your '.bash_profile' [on start up script]

This is the place where other ORACLE env variables (ORACLE_SID, ORACLE_HOME) are usually set.

just fyi - SQL Developer is good at displaying/handling non-English UTF8 characters.

RelativeLayout center vertical

This is working for me.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rell_main_bg"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#096d74" > 

<ImageView 
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    android:src="@drawable/img_logo_large"
    android:contentDescription="@null" />

</RelativeLayout>

Back to previous page with header( "Location: " ); in PHP

Just a little addition: I believe it's a common and known thing to add exit; after the header function in case we don't want the rest of the code to load or execute...

header('Location: ' . $_SERVER['HTTP_REFERER']);
exit;

How to get Last record from Sqlite?

Here's a simple example that simply returns the last line without need to sort anything from any column:

"SELECT * FROM TableName ORDER BY rowid DESC LIMIT 1;"       

how to check if string contains '+' character

[+]is simpler

    String s = "ddjdjdj+kfkfkf";

    if(s.contains ("+"))
    {
        String parts[] = s.split("[+]");
        s =  parts[0]; // i want to strip part after  +
    }
    System.out.println(s);

localhost refused to connect Error in visual studio

Project properties> Web > Create Virtual Directory worked for me

Find the smallest positive integer that does not occur in a given sequence

// you can also use imports, for example:
// import java.util.*;

// you can write to stdout for debugging purposes, e.g.
// System.out.println("this is a debug message");

class Solution {
    public int solution(int[] A) {
    int size=A.length;
    int min=A[0];
    for(int i=1;i<=size;i++){
        boolean found=false;
        for(int j=0;j<size;j++){
            if(A[j]<min){min=A[j];}
            if(i==A[j]){
                found=true;
            }
        }
            if(found==false){
                return i;

            }
        }

    if(min<0){return 1;}
        return size+1;



    }
}

Create a root password for PHPMyAdmin

I believe the command you are looking for is passwd

How to open maximized window with Javascript?

Checkout this jquery window plugin: http://fstoke.me/jquery/window/

// create a window
sampleWnd = $.window({
   .....
});

// resize the window by passed w,h parameter
sampleWnd.resize(screen.width, screen.height);

Usages of doThrow() doAnswer() doNothing() and doReturn() in mockito

To add a bit to accepted answer ...

If you get an UnfinishedStubbingException, be sure to set the method to be stubbed after the when closure, which is different than when you write Mockito.when

Mockito.doNothing().when(mock).method()    //method is declared after 'when' closes

Mockito.when(mock.method()).thenReturn(something)   //method is declared inside 'when'

How do I detect IE 8 with jQuery?

You can easily detect which type and version of the browser, using this jquery

$(document).ready(function()
{
 if ( $.browser.msie ){
    if($.browser.version == '6.0')
    {   $('html').addClass('ie6');
    }
    else if($.browser.version == '7.0')
    {   $('html').addClass('ie7');
    }
    else if($.browser.version == '8.0')
    {   $('html').addClass('ie8');
    }
    else if($.browser.version == '9.0')
    {   $('html').addClass('ie9');
    }
 }
 else if ( $.browser.webkit )
 { $('html').addClass('webkit');
 }
 else if ( $.browser.mozilla )
 { $('html').addClass('mozilla');
 }
 else if ( $.browser.opera )
 { $('html').addClass('opera');
 }
});

Twitter Bootstrap Modal Form Submit

Simple

<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<button class="btn btn-primary" onclick="event.preventDefault();document.getElementById('your-form').submit();">Save changes</button>

CSS Calc Viewport Units Workaround?

<div>It's working fine.....</div>

div
{
     height: calc(100vh - 8vw);
    background: #000;
    overflow:visible;
    color: red;
}

Check here this css code right now support All browser without Opera

just check this

Live

see Live preview by jsfiddle

See Live preview by codepen.io

How to find serial number of Android device?

Build.SERIAL is the simplest way to go, although not entirely reliable as it can be empty or sometimes return a different value (proof 1, proof 2) than what you can see in your device's settings.

There are several ways to get that number depending on the device's manufacturer and Android version, so I decided to compile every possible solution I could found in a single gist. Here's a simplified version of it :

public static String getSerialNumber() {
    String serialNumber;

    try {
        Class<?> c = Class.forName("android.os.SystemProperties");
        Method get = c.getMethod("get", String.class);

        serialNumber = (String) get.invoke(c, "gsm.sn1");
        if (serialNumber.equals(""))
            serialNumber = (String) get.invoke(c, "ril.serialnumber");
        if (serialNumber.equals(""))
            serialNumber = (String) get.invoke(c, "ro.serialno");
        if (serialNumber.equals(""))
            serialNumber = (String) get.invoke(c, "sys.serialnumber");
        if (serialNumber.equals(""))
            serialNumber = Build.SERIAL;

        // If none of the methods above worked
        if (serialNumber.equals(""))
            serialNumber = null;
    } catch (Exception e) {
        e.printStackTrace();
        serialNumber = null;
    }

    return serialNumber;
}

How to trim whitespace from a Bash variable?

In order to remove all the spaces from the beginning and the end of a string (including end of line characters):

echo $variable | xargs echo -n

This will remove duplicate spaces also:

echo "  this string has a lot       of spaces " | xargs echo -n

Produces: 'this string has a lot of spaces'

Can pm2 run an 'npm start' script

I wrote shell script below (named start.sh). Because my package.json has prestart option. So I want to run npm start.

#!/bin/bash
cd /path/to/project
npm start

Then, start start.sh by pm2.

pm2 start start.sh --name appNameYouLike

What is the correct way to create a single-instance WPF application?

Not using Mutex though, simple answer:

System.Diagnostics;    
...
string thisprocessname = Process.GetCurrentProcess().ProcessName;

if (Process.GetProcesses().Count(p => p.ProcessName == thisprocessname) > 1)
                return;

Put it inside the Program.Main().
Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;

namespace Sample
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            //simple add Diagnostics namespace, and these 3 lines below 
            string thisprocessname = Process.GetCurrentProcess().ProcessName;
            if (Process.GetProcesses().Count(p => p.ProcessName == thisprocessname) > 1)
                return;

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Sample());
        }
    }
}

You can add MessageBox.Show to the if-statement and put "Application already running".
This might be helpful to someone.

SQL query for a carriage return in a string and ultimately removing carriage return

In SQL Server I would use:

WHERE CHARINDEX(CHAR(13), name) <> 0 OR CHARINDEX(CHAR(10), name) <> 0

This will search for both carriage returns and line feeds.

If you want to search for tabs too just add:

OR CHARINDEX(CHAR(9), name) <> 0

Laravel 5: Retrieve JSON array from $request

Just a mention with jQuery v3.2.1 and Laravel 5.6.

Case 1: The JS object posted directly, like:

$.post("url", {name:'John'}, function( data ) {
});

Corresponding Laravel PHP code should be:

parse_str($request->getContent(),$data); //JSON will be parsed to object $data

Case 2: The JSON string posted, like:

$.post("url", JSON.stringify({name:'John'}), function( data ) {
});

Corresponding Laravel PHP code should be:

$data = json_decode($request->getContent(), true);

android layout with visibility GONE

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/activity_register_header"
    android:minHeight="50dp"
    android:orientation="vertical"
    android:visibility="gone" />

Try this piece of code..For me this code worked..

INSERT INTO vs SELECT INTO

The simple difference between select Into and Insert Into is: --> Select Into don't need existing table. If you want to copy table A data, you just type Select * INTO [tablename] from A. Here, tablename can be existing table or new table will be created which has same structure like table A.

--> Insert Into do need existing table.INSERT INTO [tablename] SELECT * FROM A;. Here tablename is an existing table.

Select Into is usually more popular to copy data especially backup data.

You can use as per your requirement, it is totally developer choice which should be used in his scenario.

Performance wise Insert INTO is fast.

References :

https://www.w3schools.com/sql/sql_insert_into_select.asp https://www.w3schools.com/sql/sql_select_into.asp

Changing column names of a data frame

Similar to the others:

cols <- c("premium","change","newprice")
colnames(dataframe) <- cols

Quite simple and easy to modify.

Grouping into interval of 5 minutes within a time range

This works with every interval.

PostgreSQL

SELECT
    TIMESTAMP WITH TIME ZONE 'epoch' +
    INTERVAL '1 second' * round(extract('epoch' from timestamp) / 300) * 300 as timestamp,
    name,
    count(b.name)
FROM time a, id 
WHERE …
GROUP BY 
round(extract('epoch' from timestamp) / 300), name


MySQL

SELECT
    timestamp,  -- not sure about that
    name,
    count(b.name)
FROM time a, id 
WHERE …
GROUP BY 
UNIX_TIMESTAMP(timestamp) DIV 300, name

Scroll to bottom of div?

On my Angular 6 application I just did this:

postMessage() {
  // post functions here
  let history = document.getElementById('history')
  let interval    
  interval = setInterval(function() {
    history.scrollTop = history.scrollHeight
    clearInterval(interval)
  }, 1)
}

The clearInterval(interval) function will stop the timer to allow manual scroll top / bottom.

Elevating process privilege programmatically?

[PrincipalPermission(SecurityAction.Demand, Role = @"BUILTIN\Administrators")]

This will do it without UAC - no need to start a new process. If the running user is member of Admin group as for my case.

How to remove close button on the jQuery UI dialog?

Easy way to achieve: (Do this in your Javascript)

$("selector").dialog({
    autoOpen: false,
    open: function(event, ui) {   // It'll hide Close button
        $(".ui-dialog-titlebar-close", ui.dialog | ui).hide();
    },
    closeOnEscape: false,        // Do not close dialog on press Esc button
    show: {
        effect: "clip",
        duration: 500
    },
    hide: {
        effect: "blind",
        duration: 200
    },
    ....
});

Launch Image does not show up in my iOS App

Do what Spectravideo328 answered and:

Try to UNCHECK the iOS 7 and later box and CHECK the iOS 6 and prior box in the asset catalog. There seems to be a bug with the iOS 7 Launch Image. (These both have the same Launch Images except for the 320x480 one)

Hope this helps, it did help for me!

console.writeline and System.out.println

They're essentially the same, if your program is run from an interactive prompt and you haven't redirected stdin or stdout:

public class ConsoleTest {
    public static void main(String[] args) {
        System.out.println("Console is: " + System.console());
    }
}

results in:

$ java ConsoleTest
Console is: java.io.Console@2747ee05
$ java ConsoleTest </dev/null
Console is: null
$ java ConsoleTest | cat
Console is: null

The reason Console exists is to provide features that are useful in the specific case that you're being run from an interactive command line:

  • secure password entry (hard to do cross-platform)
  • synchronisation (multiple threads can prompt for input and Console will queue them up nicely, whereas if you used System.in/out then all of the prompts would appear simultaneously).

Notice above that redirecting even one of the streams results in System.console() returning null; another irritation is that there's often no Console object available when spawned from another program such as Eclipse or Maven.

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

The evaluation of condition resulted in an NA. The if conditional must have either a TRUE or FALSE result.

if (NA) {}
## Error in if (NA) { : missing value where TRUE/FALSE needed

This can happen accidentally as the results of calculations:

if(TRUE && sqrt(-1)) {}
## Error in if (TRUE && sqrt(-1)) { : missing value where TRUE/FALSE needed

To test whether an object is missing use is.na(x) rather than x == NA.


See also the related errors:

Error in if/while (condition) { : argument is of length zero

Error in if/while (condition) : argument is not interpretable as logical

if (NULL) {}
## Error in if (NULL) { : argument is of length zero

if ("not logical") {}
## Error: argument is not interpretable as logical

if (c(TRUE, FALSE)) {}
## Warning message:
## the condition has length > 1 and only the first element will be used

Angular 2 Routing run in new tab

In my use case, I wanted to asynchronously retrieve a url, and then follow that url to an external resource in a new window. A directive seemed overkill because I don't need reusability, so I simply did:

<button (click)="navigateToResource()">Navigate</button>

And in my component.ts

navigateToResource(): void {
  this.service.getUrl((result: any) => window.open(result.url));
}


Note:

Routing to a link indirectly like this will likely trigger the browser's popup blocker.

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

import Foo 
dir(Foo)

import collections
dir(collections)

PSEXEC, access denied errors

I tried a lot of way but I could not use psexec. It gives "Access denied". After I change the target user account type from Standard to Admin, I connected the machine via psexec.

I researched the reason why admin type account is required then I found this answer.

You can change target machine user account this way: Control Panel -> User Accounts -> Change Account Type. You must enter an admin account and password to change that account if you logged in standard account.

After that I logged in with this command: psexec \\remotepcname -u remoteusername -p remotepassword cmd

Where can I find the Tomcat 7 installation folder on Linux AMI in Elastic Beanstalk?

Following environment variables worked for me on Debian Wheezy 7 and Tomcat 7:

CATALINA_HOME=/usr/share/tomcat7
CATALINA_BASE=/var/lib/tomcat7
CATALINA_TMPDIR=/tmp/tomcat7

(I did create /tmp/tomcat7 manually)

Android get image from gallery into ImageView

This is the easiest way to get image from gallery and crop ass well

step 1: StartActivity for result

imageUser.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent intent = new Intent(Intent.ACTION_PICK,
                    MediaStore.Images.Media.INTERNAL_CONTENT_URI);
            intent.setType("image/*");
            intent.putExtra("crop", "true");
            intent.putExtra("scale", true);
            intent.putExtra("outputX", 256);
            intent.putExtra("outputY", 256);
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            intent.putExtra("return-data", true);
            startActivityForResult(intent, 1);

            }
    });

step 2:Handle the result

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode != RESULT_OK) {
        return;
    }
    if (requestCode == 1) {
        final Bundle extras = data.getExtras();
        if (extras != null) {
            //Get image
            Bitmap ProfilePic = extras.getParcelable("data");
            imageUser.setImageBitmap(ProfilePic);
            TextView t=(TextView)findViewById(R.id.textoverimage);
            t.setText("image Selected");
        }
    }


}

What is the role of the bias in neural networks?

The bias helps to get a better equation

Imagine the input and output like a function y = ax + b and you need to put the right line between the input(x) and output(y) to minimise the global error between each point and the line , if you keep the equation like this y = ax , you will have one parameter for adaptation only , even if you find the best a minimising the global error it will be kind of far from the wanted value

You can say the bias makes the equation more flexible to adapt to the best values

Node.js: How to read a stream into a buffer?

I suggest to have array of buffers and concat to resulting buffer only once at the end. Its easy to do manually, or one could use node-buffers

Cannot simply use PostgreSQL table name ("relation does not exist")

Easiest workaround is Just change the table name and all column names to lowercase and your issue will be resolved.

For example:

  • Change Table_Name to table_name and
  • Change ColumnName to columnname

PHP: how can I get file creation date?

This is the example code taken from the PHP documentation here: https://www.php.net/manual/en/function.filemtime.php

// outputs e.g.  somefile.txt was last changed: December 29 2002 22:16:23.

$filename = 'somefile.txt';

if (file_exists($filename)) {

    echo "$filename was last modified: " . date ("F d Y H:i:s.", filemtime($filename));
}

The code specifies the filename, then checks if it exists and then displays the modification time using filemtime().

filemtime() takes 1 parameter which is the path to the file, this can be relative or absolute.

How do I disable log messages from the Requests library?

Kbrose's guidance on finding which logger was generating log messages was immensely useful. For my Django project, I had to sort through 120 different loggers until I found that it was the elasticsearch Python library that was causing issues for me. As per the guidance in most of the questions, I disabled it by adding this to my loggers:

      ...
      'elasticsearch': {
          'handlers': ['console'],
          'level': logging.WARNING,
      },     
      ...

Posting here in case someone else is seeing the unhelpful log messages come through whenever they run an Elasticsearch query.

Any tools to generate an XSD schema from an XML instance document?

Altova XmlSpy does this well - you can find an overview here

How to make image hover in css?

You've got an a tag containing an img tag. That's your normal state. You then add a background-image as your hover state, and it's appearing in the background of your a tag - behind the img tag.

You should probably create a CSS sprite and use background positions, but this should get you started:

<div>
    <a href="home.html"></a>
</div>

div a {
    width:  59px;
    height: 59px;
    display: block;
    background-image: url('images/btnhome.png');
}

div a:hover {
    background-image: url('images/btnhomeh.png);
}

This A List Apart Article from 2004 is still relevant, and will give you some background about sprites, and why it's a good idea to use them instead of two different images. It's a lot better written than anything I could explain to you.

How to iterate through SparseArray?

If you use Kotlin, you can use extension functions as such, for example:

fun <T> LongSparseArray<T>.valuesIterator(): Iterator<T> {
    val nSize = this.size()
    return object : Iterator<T> {
        var i = 0
        override fun hasNext(): Boolean = i < nSize
        override fun next(): T = valueAt(i++)
    }
}

fun <T> LongSparseArray<T>.keysIterator(): Iterator<Long> {
    val nSize = this.size()
    return object : Iterator<Long> {
        var i = 0
        override fun hasNext(): Boolean = i < nSize
        override fun next(): Long = keyAt(i++)
    }
}

fun <T> LongSparseArray<T>.entriesIterator(): Iterator<Pair<Long, T>> {
    val nSize = this.size()
    return object : Iterator<Pair<Long, T>> {
        var i = 0
        override fun hasNext(): Boolean = i < nSize
        override fun next() = Pair(keyAt(i), valueAt(i++))
    }
}

You can also convert to a list, if you wish. Example:

sparseArray.keysIterator().asSequence().toList()

I think it might even be safe to delete items using remove on the LongSparseArray itself (not on the iterator), as it is in ascending order.


EDIT: Seems there is even an easier way, by using collection-ktx (example here) . It's implemented in a very similar way to what I wrote, actally.

Gradle requires this:

implementation 'androidx.core:core-ktx:#'
implementation 'androidx.collection:collection-ktx:#'

Here's the usage for LongSparseArray :

    val sparse= LongSparseArray<String>()
    for (key in sparse.keyIterator()) {
    }
    for (value in sparse.valueIterator()) {
    }
    sparse.forEach { key, value -> 
    }

And for those that use Java, you can use LongSparseArrayKt.keyIterator , LongSparseArrayKt.valueIterator and LongSparseArrayKt.forEach , for example. Same for the other cases.

Check if a string is not NULL or EMPTY

You don't necessarily have to use the [string]:: prefix. This works in the same way:

if ($version)
{
    $request += "/" + $version
}

A variable that is null or empty string evaluates to false.

How to create an object property from a variable value in JavaScript?

Dot notation and the properties are equivalent. So you would accomplish like so:

var myObj = new Object;
var a = 'string1';
myObj[a] = 'whatever';
alert(myObj.string1)

(alerts "whatever")

XPath selecting a node with some attribute value equals to some other node's attribute value

This XPath is specific to the code snippet you've provided. To select <child> with id as #grand you can write //child[@id='#grand'].

To get age //child[@id='#grand']/@age

Hope this helps

The import org.junit cannot be resolved

In case you want to create your own Test Class. In Eclipse go to File -> New -> J Unit Test Case. You can then choose all your paths and testing class setup within the wizard pop-up.

How to get http headers in flask?

If any one's trying to fetch all headers that were passed then just simply use:

dict(request.headers)

it gives you all the headers in a dict from which you can actually do whatever ops you want to. In my use case I had to forward all headers to another API since the python API was a proxy

How to clear radio button in Javascript?

YES<input type="radio" name="group1" id="sal" value="YES" >

NO<input type="radio" name="group1" id="sal1" value="NO" >

<input type="button" onclick="document.getElementById('sal').checked=false;document.getElementById('sal1').checked=false">

Is Visual Studio Community a 30 day trial?

In my case it was most trivial solution - I just needed to run Vistual Studio as Administrator.

It's trivial thing, but i didn't see this mentioned anywhere.

getElementsByClassName not working

If you want to do it by ClassName you could do:

<script type="text/javascript">
function hideTd(className){
    var elements;

    if (document.getElementsByClassName)
    {
        elements = document.getElementsByClassName(className);
    }
    else
    {
        var elArray = [];
        var tmp = document.getElementsByTagName(elements);  
        var regex = new RegExp("(^|\\s)" + className+ "(\\s|$)");
        for ( var i = 0; i < tmp.length; i++ ) {

            if ( regex.test(tmp[i].className) ) {
                elArray.push(tmp[i]);
            }
        }

        elements = elArray;
    }

    for(var i = 0, i < elements.length; i++) {
       if( elements[i].textContent == ''){
          elements[i].style.display = 'none';
       } 
    }

  }
</script>

How does inline Javascript (in HTML) work?

It looks suspicious because there is no apparent function that is being returned from!

It is an anonymous function that has been attached to the click event of the object.

why are you doing this, Steve?

Why on earth are you doi.....Ah nevermind, as you've mentioned, it really is widely adopted bad practice :)

Refresh image with a new one at the same url

No need for new Date().getTime() shenanigans. You can trick the browser by having an invisible dummy image and using jQuery .load(), then creating a new image each time:

<img src="" id="dummy", style="display:none;" />  <!-- dummy img -->
<div id="pic"></div>

<script type="text/javascript">
  var url = whatever;
  // You can repeat the following as often as you like with the same url
  $("#dummy").load(url);
  var image = new Image();
  image.src = url;
  $("#pic").html("").append(image);
</script>

Angular2 handling http response

The service :

import 'rxjs/add/operator/map';

import { Http } from '@angular/http';
import { Observable } from "rxjs/Rx"
import { Injectable } from '@angular/core';

@Injectable()
export class ItemService {
  private api = "your_api_url";

  constructor(private http: Http) {

  }

  toSaveItem(item) {
    return new Promise((resolve, reject) => {
      this.http
        .post(this.api + '/items', { item: item })
        .map(res => res.json())
        // This catch is very powerfull, it can catch all errors
        .catch((err: Response) => {
          // The err.statusText is empty if server down (err.type === 3)
          console.log((err.statusText || "Can't join the server."));
          // Really usefull. The app can't catch this in "(err)" closure
          reject((err.statusText || "Can't join the server."));
          // This return is required to compile but unuseable in your app
          return Observable.throw(err);
        })
        // The (err) => {} param on subscribe can't catch server down error so I keep only the catch
        .subscribe(data => { resolve(data) })
    })
  }
}

In the app :

this.itemService.toSaveItem(item).then(
  (res) => { console.log('success', res) },
  (err) => { console.log('error', err) }
)

Working with dictionaries/lists in R

I'll just comment you can get a lot of mileage out of table when trying to "fake" a dictionary also, e.g.

> x <- c("a","a","b","b","b","c")
> (t <- table(x))
x
a b c 
2 3 1 
> names(t)
[1] "a" "b" "c"
> o <- order(as.numeric(t))
> names(t[o])
[1] "c" "a" "b"

etc.

Hexadecimal value 0x00 is a invalid character

As kind of a late answer:

I've had this problem with SSRS ReportService2005.asmx when uploading a report.

    Public Shared Sub CreateReport(ByVal strFileNameAndPath As String, ByVal strReportName As String, ByVal strReportingPath As String, Optional ByVal bOverwrite As Boolean = True)
        Dim rs As SSRS_2005_Administration_WithFOA = New SSRS_2005_Administration_WithFOA
        rs.Credentials = ReportingServiceInterface.GetMyCredentials(strCredentialsURL)
        rs.Timeout = ReportingServiceInterface.iTimeout
        rs.Url = ReportingServiceInterface.strReportingServiceURL
        rs.UnsafeAuthenticatedConnectionSharing = True

        Dim btBuffer As Byte() = Nothing

        Dim rsWarnings As Warning() = Nothing
        Try
            Dim fstrStream As System.IO.FileStream = System.IO.File.OpenRead(strFileNameAndPath)
            btBuffer = New Byte(fstrStream.Length - 1) {}
            fstrStream.Read(btBuffer, 0, CInt(fstrStream.Length))
            fstrStream.Close()
        Catch ex As System.IO.IOException
            Throw New Exception(ex.Message)
        End Try

        Try
            rsWarnings = rs.CreateReport(strReportName, strReportingPath, bOverwrite, btBuffer, Nothing)

            If Not (rsWarnings Is Nothing) Then
                Dim warning As Warning
                For Each warning In rsWarnings
                    Log(warning.Message)
                Next warning
            Else
                Log("Report: {0} created successfully with no warnings", strReportName)
            End If

        Catch ex As System.Web.Services.Protocols.SoapException
            Log(ex.Detail.InnerXml.ToString())
        Catch ex As Exception
            Log("Error at creating report. Invalid server name/timeout?" + vbCrLf + vbCrLf + "Error Description: " + vbCrLf + ex.Message)
            Console.ReadKey()
            System.Environment.Exit(1)
        End Try
    End Sub ' End Function CreateThisReport

The problem occurs when you allocate a byte array that is at least 1 byte larger than the RDL (XML) file.

Specifically, I used a C# to vb.net converter, that converted

  btBuffer = new byte[fstrStream.Length];

into

  btBuffer = New Byte(fstrStream.Length) {}

But because in C# the number denotes the NUMBER OF ELEMENTS in the array, and in VB.NET, that number denotes the UPPER BOUND of the array, I had an excess byte, causing this error.

So the problem's solution is simply:

  btBuffer = New Byte(fstrStream.Length - 1) {}

How to set the text color of TextView in code?

Similarly, I was using color.xml:

<color name="white">#ffffff</color>
    <color name="black">#000000</color>   

For setting the TextView background like:

textView.setTextColor(R.color.white);

I was getting a different color, but when I used the below code I got the actual color.

textView.setTextColor(Color.parseColor("#ff6363"));

Call JavaScript function on DropDownList SelectedIndexChanged Event:

You can use the ScriptManager.RegisterStartupScript(); to call any of your javascript event/Client Event from the server. For example, to display a message using javascript's alert();, you can do this:

protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
Response.write("<script>alert('This is my message');</script>");
 //----or alternatively and to be more proper
 ScriptManager.RegisterStartupScript(this, this.GetType(), "callJSFunction", "alert('This is my message')", true);
}

To be exact for you, do this...

protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
 ScriptManager.RegisterStartupScript(this, this.GetType(), "callJSFunction", "CalcTotalAmt();", true);
}

How to find the Git commit that introduced a string in any branch?

Not sure why the accepted answer doesn't work in my environment, finally I run below command to get what I need

git log --pretty=format:"%h - %an, %ar : %s"|grep "STRING"

SQL Row_Number() function in Where Clause

SELECT  employee_id
FROM    (
        SELECT  employee_id, ROW_NUMBER() OVER (ORDER BY employee_id) AS rn
        FROM    V_EMPLOYEE
        ) q
WHERE   rn > 0
ORDER BY
        Employee_ID

Note that this filter is redundant: ROW_NUMBER() starts from 1 and is always greater than 0.

Deleting specific rows from DataTable

Before everyone jumps on the 'You can't delete rows in an Enumeration' bandwagon, you need to first realize that DataTables are transactional, and do not technically purge changes until you call AcceptChanges()

If you are seeing this exception while calling Delete, you are already in a pending-changes data state. For instance, if you have just loaded from the database, calling Delete would throw an exception if you were inside a foreach loop.

BUT! BUT!

If you load rows from the database and call the function 'AcceptChanges()' you commit all of those pending changes to the DataTable. Now you can iterate through the list of rows calling Delete() without a care in the world, because it simply ear-marks the row for Deletion, but is not committed until you again call AcceptChanges()

I realize this response is a bit dated, but I had to deal with a similar issue recently and hopefully this saves some pain for a future developer working on 10-year-old code :)


P.s. Here is a simple code example added by Jeff:

C#

YourDataTable.AcceptChanges(); 
foreach (DataRow row in YourDataTable.Rows) {
    // If this row is offensive then
    row.Delete();
} 
YourDataTable.AcceptChanges();

VB.Net

ds.Tables(0).AcceptChanges()
For Each row In ds.Tables(0).Rows
    ds.Tables(0).Rows(counter).Delete()
    counter += 1
Next
ds.Tables(0).AcceptChanges()

OpenCV TypeError: Expected cv::UMat for argument 'src' - What is this?

Is canny your own function? Do you use Canny from OpenCV inside it? If yes check if you feed suitable argument for Canny - first Canny argument should meet following criteria:

  • type: <type 'numpy.ndarray'>
  • dtype: dtype('uint8')
  • being single channel or simplyfing: grayscale, that is 2D array, i.e. its shape should be 2-tuple of ints (tuple containing exactly 2 integers)

You can check it by printing respectively

type(variable_name)
variable_name.dtype
variable_name.shape

Replace variable_name with name of variable you feed as first argument to Canny.

What does the 'Z' mean in Unix timestamp '120314170138Z'?

Yes. 'Z' stands for Zulu time, which is also GMT and UTC.

From http://en.wikipedia.org/wiki/Coordinated_Universal_Time:

The UTC time zone is sometimes denoted by the letter Z—a reference to the equivalent nautical time zone (GMT), which has been denoted by a Z since about 1950. The letter also refers to the "zone description" of zero hours, which has been used since 1920 (see time zone history). Since the NATO phonetic alphabet and amateur radio word for Z is "Zulu", UTC is sometimes known as Zulu time.

Technically, because the definition of nautical time zones is based on longitudinal position, the Z time is not exactly identical to the actual GMT time 'zone'. However, since it is primarily used as a reference time, it doesn't matter what area of Earth it applies to as long as everyone uses the same reference.

From wikipedia again, http://en.wikipedia.org/wiki/Nautical_time:

Around 1950, a letter suffix was added to the zone description, assigning Z to the zero zone, and A–M (except J) to the east and N–Y to the west (J may be assigned to local time in non-nautical applications; zones M and Y have the same clock time but differ by 24 hours: a full day). These were to be vocalized using a phonetic alphabet which pronounces the letter Z as Zulu, leading sometimes to the use of the term "Zulu Time". The Greenwich time zone runs from 7.5°W to 7.5°E longitude, while zone A runs from 7.5°E to 22.5°E longitude, etc.

How do you specifically order ggplot2 x axis instead of alphabetical order?

It is a little difficult to answer your specific question without a full, reproducible example. However something like this should work:

#Turn your 'treatment' column into a character vector
data$Treatment <- as.character(data$Treatment)
#Then turn it back into a factor with the levels in the correct order
data$Treatment <- factor(data$Treatment, levels=unique(data$Treatment))

In this example, the order of the factor will be the same as in the data.csv file.

If you prefer a different order, you can order them by hand:

data$Treatment <- factor(data$Treatment, levels=c("Y", "X", "Z"))

However this is dangerous if you have a lot of levels: if you get any of them wrong, that will cause problems.

Dealing with timestamps in R

You want the (standard) POSIXt type from base R that can be had in 'compact form' as a POSIXct (which is essentially a double representing fractional seconds since the epoch) or as long form in POSIXlt (which contains sub-elements). The cool thing is that arithmetic etc are defined on this -- see help(DateTimeClasses)

Quick example:

R> now <- Sys.time()
R> now
[1] "2009-12-25 18:39:11 CST"
R> as.numeric(now)
[1] 1.262e+09
R> now + 10  # adds 10 seconds
[1] "2009-12-25 18:39:21 CST"
R> as.POSIXlt(now)
[1] "2009-12-25 18:39:11 CST"
R> str(as.POSIXlt(now))
 POSIXlt[1:9], format: "2009-12-25 18:39:11"
R> unclass(as.POSIXlt(now))
$sec
[1] 11.79

$min
[1] 39

$hour
[1] 18

$mday
[1] 25

$mon
[1] 11

$year
[1] 109

$wday
[1] 5

$yday
[1] 358

$isdst
[1] 0

attr(,"tzone")
[1] "America/Chicago" "CST"             "CDT"            
R> 

As for reading them in, see help(strptime)

As for difference, easy too:

R> Jan1 <- strptime("2009-01-01 00:00:00", "%Y-%m-%d %H:%M:%S")
R> difftime(now, Jan1, unit="week")
Time difference of 51.25 weeks
R> 

Lastly, the zoo package is an extremely versatile and well-documented container for matrix with associated date/time indices.

Multiprocessing a for loop?

You can simply use multiprocessing.Pool:

from multiprocessing import Pool

def process_image(name):
    sci=fits.open('{}.fits'.format(name))
    <process>

if __name__ == '__main__':
    pool = Pool()                         # Create a multiprocessing Pool
    pool.map(process_image, data_inputs)  # process data_inputs iterable with pool

How to get the difference between two arrays of objects in JavaScript

_x000D_
_x000D_
let obj1 =[
                 { id: 1, submenu_name: 'login' },
                 { id: 2, submenu_name: 'Profile',}, 
                 { id: 3, submenu_name: 'password',  },  
                 { id: 4, submenu_name: 'reset',}
               ] ;
 let obj2 =[
                 { id: 2}, 
                 { id: 3 },
               ] ;
               
// Need Similar obj 
const result1 = obj1.filter(function(o1){
 return obj2.some(function(o2){
    return o1.id == o2.id;          // id is unnique both array object
  });
});
 console.log(result1);



// Need differnt obj 
 const result2 = obj1.filter(function(o1){
 return !obj2.some(function(o2){    //  for diffrent we use NOT (!) befor obj2 here
    return o1.id == o2.id;          // id is unnique both array object
  });
});
 console.log(result2);
_x000D_
_x000D_
_x000D_

Can I display the value of an enum with printf()?

The correct answer to this has already been given: no, you can't give the name of an enum, only it's value.

Nevertheless, just for fun, this will give you an enum and a lookup-table all in one and give you a means of printing it by name:

main.c:

#include "Enum.h"

CreateEnum(
        EnumerationName,
        ENUMValue1,
        ENUMValue2,
        ENUMValue3);

int main(void)
{
    int i;
    EnumerationName EnumInstance = ENUMValue1;

    /* Prints "ENUMValue1" */
    PrintEnumValue(EnumerationName, EnumInstance);

    /* Prints:
     * ENUMValue1
     * ENUMValue2
     * ENUMValue3
     */
    for (i=0;i<3;i++)
    {
        PrintEnumValue(EnumerationName, i);
    }
    return 0;
}

Enum.h:

#include <stdio.h>
#include <string.h>

#ifdef NDEBUG
#define CreateEnum(name,...) \
    typedef enum \
    { \
        __VA_ARGS__ \
    } name;
#define PrintEnumValue(name,value)
#else
#define CreateEnum(name,...) \
    typedef enum \
    { \
        __VA_ARGS__ \
    } name; \
    const char Lookup##name[] = \
        #__VA_ARGS__;
#define PrintEnumValue(name, value) print_enum_value(Lookup##name, value)
void print_enum_value(const char *lookup, int value);
#endif

Enum.c

#include "Enum.h"

#ifndef NDEBUG
void print_enum_value(const char *lookup, int value)
{
    char *lookup_copy;
    int lookup_length;
    char *pch;

    lookup_length = strlen(lookup);
    lookup_copy = malloc((1+lookup_length)*sizeof(char));
    strcpy(lookup_copy, lookup);

    pch = strtok(lookup_copy," ,");
    while (pch != NULL)
    {
        if (value == 0)
        {
            printf("%s\n",pch);
            break;
        }
        else
        {
            pch = strtok(NULL, " ,.-");
            value--;
        }
    }

    free(lookup_copy);
}
#endif

Disclaimer: don't do this.

What does "#include <iostream>" do?

That is a C++ standard library header file for input output streams. It includes functionality to read and write from streams. You only need to include it if you wish to use streams.

Purge or recreate a Ruby on Rails database

I use:

  • rails db:drop to delete the databases.
  • rails db:create to create the databases based on config/database.yml

The previous commands may be replaced with rails db:reset.

Don't forget to run rails db:migrate to run the migrations.

How to get the last day of the month?

The easiest way (without having to import calendar), is to get the first day of the next month, and then subtract a day from it.

import datetime as dt
from dateutil.relativedelta import relativedelta

thisDate = dt.datetime(2017, 11, 17)

last_day_of_the_month = dt.datetime(thisDate.year, (thisDate + relativedelta(months=1)).month, 1) - dt.timedelta(days=1)
print last_day_of_the_month

Output:

datetime.datetime(2017, 11, 30, 0, 0)

PS: This code runs faster as compared to the import calendarapproach; see below:

import datetime as dt
import calendar
from dateutil.relativedelta import relativedelta

someDates = [dt.datetime.today() - dt.timedelta(days=x) for x in range(0, 10000)]

start1 = dt.datetime.now()
for thisDate in someDates:
    lastDay = dt.datetime(thisDate.year, (thisDate + relativedelta(months=1)).month, 1) - dt.timedelta(days=1)

print ('Time Spent= ', dt.datetime.now() - start1)


start2 = dt.datetime.now()
for thisDate in someDates:
    lastDay = dt.datetime(thisDate.year, 
                          thisDate.month, 
                          calendar.monthrange(thisDate.year, thisDate.month)[1])

print ('Time Spent= ', dt.datetime.now() - start2)

OUTPUT:

Time Spent=  0:00:00.097814
Time Spent=  0:00:00.109791

This code assumes that you want the date of the last day of the month (i.e., not just the DD part, but the entire YYYYMMDD date)

Laravel: Validation unique on update

I read the previous post, but none approach the real problem. We need use the rule unique to apply on add and edit case. I use this rule on edit and add case and work fine.

In my solution i use rule function from Request Class.

  1. I sent id over hidden input form field on edit form.
  2. On the Rule function, we find by unique column and get the record.
  3. Now evaluate the situation. If exist record and id are equal the unique must be not activate (that's mean edit record).

On the code:

public function rules()
    {
        //
        $user = User::where('email', $this->email)->first();
        //
        $this->id = isset($this->id) ? $this->id : null;
        $emailRule = (($user != null) && ($user->id == $this->id)) ? 'required|email:rfc,dns|max:255' : 'required|unique:users|email:rfc,dns|max:255';
        //        
        return [
            //
            'email'            =>  $emailRule,                
            //
        ];
        //


    }

How to do a LIKE query with linq?

You could use SqlMethods.Like(matchExpression,pattern)

var results = from c in db.costumers
              where SqlMethods.Like(c.FullName, "%"+FirstName+"%,"+LastName)
              select c;

The use of this method outside of LINQ to SQL will always throw a NotSupportedException exception.

Can promises have multiple arguments to onFulfilled?

Great question, and great answer by Benjamin, Kris, et al - many thanks!

I'm using this in a project and have created a module based on Benjamin Gruenwald's code. It's available on npmjs:

npm i -S promise-spread

Then in your code, do

require('promise-spread');

If you're using a library such as any-promise

var Promise = require('any-promise');
require('promise-spread')(Promise);

Maybe others find this useful, too!

Git submodule update

To update each submodule, you could invoke the following command (at the root of the repository):

git submodule -q foreach git pull -q origin master

You can remove the -q option to follow the whole process.

Remove last character from string. Swift language

The easiest way to trim the last character of the string is:

title = title[title.startIndex ..< title.endIndex.advancedBy(-1)]

Fastest way to duplicate an array in JavaScript - slice vs. 'for' loop

It depends on the browser. If you look in the blog post Array.prototype.slice vs manual array creation, there is a rough guide to performance of each:

Enter image description here

Results:

Enter image description here

Updating .class file in jar

  1. Use jar -xvf to extract the files to a directory.
  2. Make your changes and replace the classes.
  3. Use jar -cvf to create a new jar file.

Why does comparing strings using either '==' or 'is' sometimes produce a different result?

is is identity testing and == is equality testing (see the Python documentation).

In most cases, if a is b, then a == b. But there are exceptions, for example:

>>> nan = float('nan')
>>> nan is nan
True
>>> nan == nan
False

So, you can only use is for identity tests, never equality tests.

Installing RubyGems in Windows

Installing Ruby

Go to http://rubyinstaller.org/downloads/

Make sure that you check "Add ruby ... to your PATH". enter image description here

Now you can use "ruby" in your "cmd".

If you installed ruby 1.9.3 I expect that the ruby is downloaded in C:\Ruby193.

Installing Gem

install Development Kit in rubyinstaller. Make new folder such as C:\RubyDevKit and unzip.

Go to the devkit directory and type ruby dk.rb init to generate config.yml.

If you installed devkit for 1.9.3, I expect that the config.yml will be written as C:\Ruby193.

If not, please correct path to your ruby folders.

After reviewing the config.yml, you can finally type ruby dk.rb install.

Now you can use "gem" in your "cmd". It's done!

Clearing the terminal screen?

There is no way to clear the screen but, a really easy way to fake it can be printing as much Serial.println(); as you need to keep all the old data out of the screen.

Comparing two strings in C?

The name of the array indicates the starting address. Starting address of both namet2 and nameIt2 are different. So the equal to (==) operator checks whether the addresses are the same or not. For comparing two strings, a better way is to use strcmp(), or we can compare character by character using a loop.

SimpleDateFormat returns 24-hour date: how to get 12-hour date?

Yep, confirmed that simply using hh instead of HH fixed my issue.

Changed from this:

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm aa");

To this:

SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa");

You can still use HH to store the time if you don't want to bother storing and dealing with the AM/PM. Then when you retrieve it, use hh.

How to change value of a request parameter in laravel

Use merge():

$request->merge([
    'user_id' => $modified_user_id_here,
]);

Simple! No need to transfer the entire $request->all() to another variable.

Can't compile C program on a Mac after upgrade to Mojave

After trying every answer I could find here and online, I was still getting errors for some missing headers. When trying to compile pyRFR, I was getting errors about stdexcept not being found, which apparently was not installed in /usr/include with the other headers. However, I found where it was hiding in Mojave and added this to the end of my ~/.bash_profile file:

export CPATH=/Library/Developer/CommandLineTools/usr/include/c++/v1

Having done that, I can now compile pyRFR and other C/C++ programs. According to echo | gcc -E -Wp,-v -, gcc was looking in the old location for these headers (without the /c++/v1), but not the new location, so adding that to CFLAGS fixed it.

There is already an open DataReader associated with this Command which must be closed first

Well for me it was my own bug. I was trying to run an INSERT using SqlCommand.executeReader() when I should have been using SqlCommand.ExecuteNonQuery(). It was opened and never closed, causing the error. Watch out for this oversight.