Programs & Examples On #Formbuilder

How to set a class attribute to a Symfony2 form input

Like this:

{{ form_widget(form.description, { 'attr': {'class': 'form-control', 'rows': '5', 'style': 'resize:none;'} }) }}

How to place Text and an Image next to each other in HTML?

You want to use css float for this, you can put it directly in your code.

<body>
<img src="website_art.png" height= "75" width="235" style="float:left;"/>
<h3 style="float:right;">The Art of Gaming</h3>
</body>

But I would really suggest learning the basics of css and splitting all your styling out to a separate style sheet, and use classes. It will help you in the future. A good place to start is w3schools or, perhaps later down the path, Mozzila Dev. Network (MDN).

HTML:

<body>
  <img src="website_art.png" class="myImage"/>
  <h3 class="heading">The Art of Gaming</h3>
</body>

CSS:

.myImage {
  float: left;
  height: 75px;
  width: 235px;
  font-family: Veranda;
}
.heading {
  float:right;
}

Disable/turn off inherited CSS3 transitions

If you want to disable a single transition property, you can do:

transition: color 0s;

(since a zero second transition is the same as no transition.)

How to get first two characters of a string in oracle query?

Just use SUBSTR function. It takes 3 parameters: String column name, starting index and length of substring:

select SUBSTR(OrderNo, 1, 2) FROM shipment;

How To: Execute command line in C#, get STD OUT results

Just for fun, here's my completed solution for getting PYTHON output - under a button click - with error reporting. Just add a button called "butPython" and a label called "llHello"...

    private void butPython(object sender, EventArgs e)
    {
        llHello.Text = "Calling Python...";
        this.Refresh();
        Tuple<String,String> python = GoPython(@"C:\Users\BLAH\Desktop\Code\Python\BLAH.py");
        llHello.Text = python.Item1; // Show result.
        if (python.Item2.Length > 0) MessageBox.Show("Sorry, there was an error:" + Environment.NewLine + python.Item2);
    }

    public Tuple<String,String> GoPython(string pythonFile, string moreArgs = "")
    {
        ProcessStartInfo PSI = new ProcessStartInfo();
        PSI.FileName = "py.exe";
        PSI.Arguments = string.Format("\"{0}\" {1}", pythonFile, moreArgs);
        PSI.CreateNoWindow = true;
        PSI.UseShellExecute = false;
        PSI.RedirectStandardError = true;
        PSI.RedirectStandardOutput = true;
        using (Process process = Process.Start(PSI))
            using (StreamReader reader = process.StandardOutput)
            {
                string stderr = process.StandardError.ReadToEnd(); // Error(s)!!
                string result = reader.ReadToEnd(); // What we want.
                return new Tuple<String,String> (result,stderr); 
            }
    }

How to merge two sorted arrays into a sorted array?

Algorithm could be enhanced in many ways. For instance, it is reasonable to check, if a[m-1]<b[0] or b[n-1]<a[0]. In any of those cases, there is no need to do more comparisons. Algorithm could just copy source arrays in the resulting one in the right order.

More complicated enhancements may include searching for interleaving parts and run merge algorithm for them only. It could save up much time, when sizes of merged arrays differ in scores of times.

How do I sort a list of datetime or date objects?

You're getting None because list.sort() it operates in-place, meaning that it doesn't return anything, but modifies the list itself. You only need to call a.sort() without assigning it to a again.

There is a built in function sorted(), which returns a sorted version of the list - a = sorted(a) will do what you want as well.

CASE (Contains) rather than equal statement

Pseudo code, something like:

CASE
  When CHARINDEX('lactulose', dbo.Table.Column) > 0 Then 'BP Medication'
ELSE ''
END AS 'Medication Type'

This does not care where the keyword is found in the list and avoids depending on formatting of spaces and commas.

Getting Current date, time , day in laravel

How about

    $date = Carbon::now();
    return $date->toArray();

will give you

{
  "year": 2019,
  "month": 1,
  "day": 27,
  "dayOfWeek": 0,
  "dayOfYear": 26,
  "hour": 10,
  "minute": 28,
  "second": 55,
  "englishDayOfWeek": "Sunday",
  "micro": 967721,
  "timestamp": 1548570535,
  "formatted": "2019-01-27 10:28:55",
  "timezone": {
    "timezone_type": 3,
    "timezone": "Asia/Dubai"
  }
}

The same props are accessible through


    return [
             'date' => $date->format('Y-m-d'),
              'year' => $date->year,
              'month' => $date->month,
              'day' => $date->day,
              'hour' => $date->hour,
              'isSaturday' => $date->isSaturday(),
          ];

Difference between wait and sleep

Wait() and sleep() Differences?

Thread.sleep() Once its work completed then only its release the lock to everyone. until its never release the lock to anyone.

  Sleep() take the key, its never release the key to anyone, when its work completed then only its release then only take the key waiting stage threads.

Object.wait() When its going to waiting stage, its will be release the key and its waiting for some of the seconds based on the parameter.

For Example:

you are take the coffee in yours right hand, you can take another anyone of the same hand, when will your put down then only take another object same type here. also. this is sleep() you sleep time you didn't any work, you are doing only sleeping.. same here also.

wait(). when you are put down and take another one mean while you are waiting , that's wait

you are play movie or anything in yours system same as player you can't play more than one at a time right, thats its here, when you close and choose another anyone movie or song mean while is called wait

How to restart VScode after editing extension's config?

  1. Open the Command Palette

    Ctrl + Shift + P

  2. Then type:

    Reload Window
    

How to select last child element in jQuery?

You can also do this:

<ul id="example">
    <li>First</li>
    <li>Second</li>
    <li>Third</li>
    <li>Fourth</li>
</ul>

// possibility 1
$('#example li:last').val();
// possibility 2
$('#example').children().last()
// possibility 3
$('#example li:last-child').val();

:last

.children().last()

:last-child

Initialise a list to a specific length in Python

In a talk about core containers internals in Python at PyCon 2012, Raymond Hettinger is suggesting to use [None] * n to pre-allocate the length you want.

Slides available as PPT or via Google

The whole slide deck is quite interesting. The presentation is available on YouTube, but it doesn't add much to the slides.

How to compare two dates to find time difference in SQL Server 2005, date manipulation

I used following logic and it worked for me like marvel:

CONVERT(TIME, DATEADD(MINUTE, DATEDIFF(MINUTE, AP.Time_IN, AP.Time_OUT), 0)) 

Amazon S3 boto - how to create a folder?

Apparently you can now create folders in S3. I'm not sure since when, but I have a bucket in "Standard" zone and can choose Create Folder from Action dropdown.

How to convert milliseconds to "hh:mm:ss" format?

Java 9

    Duration timeLeft = Duration.ofMillis(3600000);
    String hhmmss = String.format("%02d:%02d:%02d", 
            timeLeft.toHours(), timeLeft.toMinutesPart(), timeLeft.toSecondsPart());
    System.out.println(hhmmss);

This prints:

01:00:00

You are doing right in letting library methods do the conversions involved for you. java.time, the modern Java date and time API, or more precisely, its Duration class does it more elegantly and in a less error-prone way than TimeUnit.

The toMinutesPart and toSecondsPart methods I used were introduced in Java 9.

Java 6, 7 and 8

    long hours = timeLeft.toHours();
    timeLeft = timeLeft.minusHours(hours);
    long minutes = timeLeft.toMinutes();
    timeLeft = timeLeft.minusMinutes(minutes);
    long seconds = timeLeft.toSeconds();
    String hhmmss = String.format("%02d:%02d:%02d", hours, minutes, seconds);
    System.out.println(hhmmss);

The output is the same as above.

Question: How can that work in Java 6 and 7?

  • In Java 8 and later and on newer Android devices (from API level 26, I’m told) java.time comes built-in.
  • In Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

Default FirebaseApp is not initialized

Another possible solution - try different Android Studio if you are using some betas. Helped for me. New Android Studio simply didn't add Firebase properly. In my case 3.3preview

After some more investigation I found the problem was that new Android studio starts project with newer Google Services version and it looks it was the original problem. As @Ammar Bukhari suggested this change helped:

classpath 'com.google.gms:google-services:4.1.0' -> classpath 'com.google.gms:google-services:4.0.0'

Why Is Subtracting These Two Times (in 1927) Giving A Strange Result?

As others said, it's a time change in 1927 in Shanghai.

It was 23:54:07 in Shanghai, in the local standard time, but then after 5 minutes and 52 seconds, it turned to the next day at 00:00:00, and then local standard time changed back to 23:54:08. So, that's why the difference between the two times is 343 seconds, not 1 second, as you would have expected.

The time can also mess up in other places like the US. The US has Daylight Saving Time. When the Daylight Saving Time starts the time goes forward 1 hour. But after a while, the Daylight Saving Time ends, and it goes backward 1 hour back to the standard time zone. So sometimes when comparing times in the US the difference is about 3600 seconds not 1 second.

But there is something different about these two-time changes. The latter changes continuously and the former was just a change. It didn't change back or change again by the same amount.

It's better to use UTC unless if needed to use non-UTC time like in display.

scp or sftp copy multiple files with single command

Problem: Copying multiple directories from remote server to local machine using a single SCP command and retaining each directory as it is in the remote server.

Solution: SCP can do this easily. This solves the annoying problem of entering password multiple times when using SCP with multiple folders. Consequently, this also saves a lot of time!

e.g.

# copies folders t1, t2, t3 from `test` to your local working directory
# note that there shouldn't be any space in between the folder names;
# we also escape the braces.
# please note the dot at the end of the SCP command

~$ cd ~/working/directory
~$ scp -r [email protected]:/work/datasets/images/test/\{t1,t2,t3\}  .

PS: Motivated by this great answer: scp or sftp copy multiple files with single command


Based on the comments, this also works fine in Git Bash on Windows

How to iterate through table in Lua?

If you want to refer to a nested table by multiple keys you can just assign them to separate keys. The tables are not duplicated, and still reference the same values.

arr = {}
apples = {'a', "red", 5 }
arr.apples = apples
arr[1] = apples

This code block lets you iterate through all the key-value pairs in a table (http://lua-users.org/wiki/TablesTutorial):

for k,v in pairs(t) do
 print(k,v)
end

CSS Font Border?

I created a comparison of all the solutions mentioned here to have a quick overview:

<h1>with mixin</h1>
<h2>with text-shadow</h2>
<h3>with css text-stroke-width</h3>

https://codepen.io/Grienauer/pen/GRRdRJr

Java String remove all non numeric characters

Try this code:

String str = "a12.334tyz.78x";
str = str.replaceAll("[^\\d.]", "");

Now str will contain "12.334.78".

Passing an array as a function parameter in JavaScript

const args = ['p0', 'p1', 'p2'];
call_me.apply(this, args);

See MDN docs for Function.prototype.apply().


If the environment supports ECMAScript 6, you can use a spread argument instead:

call_me(...args);

How to disable Hyper-V in command line?

This command works

Disable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V-All

Run it then agree to restart the computer when prompted.

I ran it in elevated permissions PowerShell on Windows 10, but it should also work on Win 8 or 7.

Null check in an enhanced for loop

With Java 8 Optional:

for (Object object : Optional.ofNullable(someList).orElse(Collections.emptyList())) {
    // do whatever
}

npm ERR! code UNABLE_TO_GET_ISSUER_CERT_LOCALLY

After trying out every solution I could find:

  • Turning off strict ssl: npm config set strict-ssl=false
  • Changing the registry to http instead of https: npm config set registry http://registry.npmjs.org/
  • Changing my cafile setting: npm config set cafile /path/to/your/cert.pem
  • Stop rejecting unknown CAs: set NODE_TLS_REJECT_UNAUTHORIZED=0

The solution that seems to be working the best for me now is to use the NODE_EXTRA_CA_CERTS environment variable which extends the existing CAs rather than replacing them with the cafile option in your .npmrc file. You can set it by entering this in your terminal: NODE_EXTRA_CA_CERTS=path/to/your/cert.pem

Of course, setting this variable every time can be annoying, so I added it to my bash profile so that it will be set every time I open terminal. If you don’t already have a ~/.bash_profile file, create one. Then at the end of that file add export NODE_EXTRA_CA_CERTS=path/to/your/cert.pem. Then, remove the cafile setting in your .npmrc.

Difference between HttpModule and HttpClientModule

There is a library which allows you to use HttpClient with strongly-typed callbacks.

The data and the error are available directly via these callbacks.

A reason for existing

When you use HttpClient with Observable, you have to use .subscribe(x=>...) in the rest of your code.

This is because Observable<HttpResponse<T>> is tied to HttpResponse.

This tightly couples the http layer with the rest of your code.

This library encapsulates the .subscribe(x => ...) part and exposes only the data and error through your Models.

With strongly-typed callbacks, you only have to deal with your Models in the rest of your code.

The library is called angular-extended-http-client.

angular-extended-http-client library on GitHub

angular-extended-http-client library on NPM

Very easy to use.

Sample usage

The strongly-typed callbacks are

Success:

  • IObservable<T>
  • IObservableHttpResponse
  • IObservableHttpCustomResponse<T>

Failure:

  • IObservableError<TError>
  • IObservableHttpError
  • IObservableHttpCustomError<TError>

Add package to your project and in your app module

import { HttpClientExtModule } from 'angular-extended-http-client';

and in the @NgModule imports

  imports: [
    .
    .
    .
    HttpClientExtModule
  ],

Your Models

//Normal response returned by the API.
export class RacingResponse {
    result: RacingItem[];
}

//Custom exception thrown by the API.
export class APIException {
    className: string;
}

Your Service

In your Service, you just create params with these callback types.

Then, pass them on to the HttpClientExt's get method.

import { Injectable, Inject } from '@angular/core'
import { RacingResponse, APIException } from '../models/models'
import { HttpClientExt, IObservable, IObservableError, ResponseType, ErrorType } from 'angular-extended-http-client';
.
.

@Injectable()
export class RacingService {

    //Inject HttpClientExt component.
    constructor(private client: HttpClientExt, @Inject(APP_CONFIG) private config: AppConfig) {

    }

    //Declare params of type IObservable<T> and IObservableError<TError>.
    //These are the success and failure callbacks.
    //The success callback will return the response objects returned by the underlying HttpClient call.
    //The failure callback will return the error objects returned by the underlying HttpClient call.
    getRaceInfo(success: IObservable<RacingResponse>, failure?: IObservableError<APIException>) {
        let url = this.config.apiEndpoint;

        this.client.get(url, ResponseType.IObservable, success, ErrorType.IObservableError, failure);
    }
}

Your Component

In your Component, your Service is injected and the getRaceInfo API called as shown below.

  ngOnInit() {    
    this.service.getRaceInfo(response => this.result = response.result,
                                error => this.errorMsg = error.className);

  }

Both, response and error returned in the callbacks are strongly typed. Eg. response is type RacingResponse and error is APIException.

You only deal with your Models in these strongly-typed callbacks.

Hence, The rest of your code only knows about your Models.

Also, you can still use the traditional route and return Observable<HttpResponse<T>> from Service API.

What is "X-Content-Type-Options=nosniff"?

A really simple explanation that I found useful: the nosniff response header is a way to keep a website more secure.

From Security Researcher, Scott Helme, here:

It prevents Google Chrome and Internet Explorer from trying to mime-sniff the content-type of a response away from the one being declared by the server.

"E: Unable to locate package python-pip" on Ubuntu 18.04

To solve the problem of:

E: Unable to locate package python-pip

you should do this. This works with the python2.7 and you not going to get disappointed by it. follow the steps that are mention below. go to get-pip.py and copy all the code from it.
open the terminal using CTRL + ALT +T

vi get-pip.py

paste the copied code here and then exit from the vi editor by pressing

ESC then :wq => press Enter

lastly, now run the code and see the magic

sudo python get-pip.py

It automatically adds the pip command in your Linux.
you can see the output of my machine

How to add action listener that listens to multiple buttons

Here is a modified form of the source based on my comment. Note that GUIs should be constructed & updated on the EDT, though I did not go that far.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JFrame;

public class Calc {

    public static void main(String[] args) {

        JFrame calcFrame = new JFrame();

        // usually a good idea.
        calcFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        final JButton button1 = new JButton("1");
        button1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                JOptionPane.showMessageDialog(
                    button1, "..is the loneliest number");
            }
        });

        calcFrame.add(button1);

        // don't do this..
        // calcFrame.setSize(100, 100);

        // important!
        calcFrame.pack();

        calcFrame.setVisible(true);
    }
}

How do I add indices to MySQL tables?

You say you have an index, the explain says otherwise. However, if you really do, this is how to continue:

If you have an index on the column, and MySQL decides not to use it, it may by because:

  1. There's another index in the query MySQL deems more appropriate to use, and it can use only one. The solution is usually an index spanning multiple columns if their normal method of retrieval is by value of more then one column.
  2. MySQL decides there are to many matching rows, and thinks a tablescan is probably faster. If that isn't the case, sometimes an ANALYZE TABLE helps.
  3. In more complex queries, it decides not to use it based on extremely intelligent thought-out voodoo in the query-plan that for some reason just not fits your current requirements.

In the case of (2) or (3), you could coax MySQL into using the index by index hint sytax, but if you do, be sure run some tests to determine whether it actually improves performance to use the index as you hint it.

How to close a GUI when I push a JButton?

See JFrame.setDefaultCloseOperation(DISPOSE_ON_CLOSE)1. You might also use EXIT_ON_CLOSE, but it is better to explicitly clean up any running threads, then when the last GUI element becomes invisible, the EDT & JRE will end.

The 'button' to invoke this operation is already on a frame.

  1. See this answer to How to best position Swing GUIs? for a demo. of the DISPOSE_ON_CLOSE functionality.

    The JRE will end after all 3 frames are closed by clicking the X button.

What HTTP status response code should I use if the request is missing a required parameter?

In one of our API project we decide to set a 409 Status to some request, when we can't full fill it at 100% because of missing parameter.

HTTP Status Code "409 Conflict" was for us a good try because it's definition require to include enough information for the user to recognize the source of the conflict.

Reference: w3.org/Protocols/

So among other response like 400 or 404 we chose 409 to enforce the need for looking over some notes in the request helpful to set up a new and right request.

Any way our case it was particular because we need to send out some data eve if the request was not completely correct, and we need to enforce the client to look at the message and understand what was wrong in the request.

In general if we have only some missing parameter we go for a 400 and an array of missing parameter. But when we need to send some more information, like a particular case message and we want to be more sure the client will take care of it we send a 409

The 'packages' element is not declared

Change the node to and create a file, packages.xsd, in the same folder (and include it in the project) with the following contents:

<?xml version="1.0" encoding="utf-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"
      targetNamespace="urn:packages" xmlns="urn:packages">
  <xs:element name="packages">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="package" maxOccurs="unbounded">
          <xs:complexType>
            <xs:attribute name="id" type="xs:string" use="required" />
            <xs:attribute name="version" type="xs:string" use="required" />
            <xs:attribute name="targetFramework" type="xs:string" use="optional" />
            <xs:attribute name="allowedVersions" type="xs:string" use="optional" />
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

Any way of using frames in HTML5?

I know your class is over, but in professional coding, let this be a lesson:

  • "Deprecated" means "avoid use; it's going to be removed in the future"
  • Deprecated things still work - just don't expect support or future-proofing
  • If the requirement requires it, and you can't negotiate it away, just use the deprecated construct.
    • If you're really concerned, develop the alternative implementation on the side and keep it ready for the inevitable failure
    • Charge for the extra work now. By requesting a deprecated feature, they are asking you to double the work. You're going to see it again anyway, so might as well front-load it.
    • When the failure happens, let the interested party know that this was what you feared; that you prepared for it, but it'll take some time
    • Deploy your solution as quickly as you can (there will be bugs)
    • Gain rep for preventing excessive downtime.

How to send password using sftp batch file

If you are generating a heap of commands to be run, then call that script from a terminal, you can try the following.

sftp login@host < /path/to/command/list

You will then be asked to enter your password (as per normal) however all the commands in the script run after that.

This is clearly not a completely automated option that can be used in a cron job, but it can be used from a terminal.

Log4j2 configuration - No log4j2 configuration file found

Was following the documentations - Apache Log4j2 Configuratoin and Apache Log4j2 Maven in configuring log4j2 with yaml. As per the documentation, the following maven dependencies are required:

  <dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>2.8.1</version>
  </dependency>
  <dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.8.1</version>
  </dependency>

and

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-yaml</artifactId>
    <version>2.8.6</version>
</dependency>

Just adding these didn't pick the configuration and always gave error. The way of debugging configuration by adding -Dorg.apache.logging.log4j.simplelog.StatusLogger.level=TRACE helped in seeing the logs. Later had to download the source using Maven and debugging helped in understanding the depended classes of log4j2. They are listed in org.apache.logging.log4j.core.config.yaml.YamlConfigurationFactory:

com.fasterxml.jackson.databind.ObjectMapper
com.fasterxml.jackson.databind.JsonNode
com.fasterxml.jackson.core.JsonParser
com.fasterxml.jackson.dataformat.yaml.YAMLFactory

Adding dependency mapping for jackson-dataformat-yaml will not have the first two classes. Hence, add the jackson-databind dependency to get yaml configuration working:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.8.6</version>
</dependency>

You may add the version by referring to the Test Dependencies section of log4j-api version item from MVN Repository. E.g. for 2.8.1 version of log4j-api, refer this link and locate the jackson-databind version.

Moreover, you can use the below Java code to check if the classes are available in the classpath:

System.out.println(ClassLoader.getSystemResource("log4j2.yml")); //Check if file is available in CP
ClassLoader cl = Thread.currentThread().getContextClassLoader(); //Code as in log4j2 API. Version: 2.8.1
 String [] classes = {"com.fasterxml.jackson.databind.ObjectMapper",
 "com.fasterxml.jackson.databind.JsonNode",
 "com.fasterxml.jackson.core.JsonParser",
 "com.fasterxml.jackson.dataformat.yaml.YAMLFactory"};

 for(String className : classes) {
     cl.loadClass(className);
 }

How to submit a form on enter when the textarea has focus?

You can't do this without JavaScript. Stackoverflow is using the jQuery JavaScript library which attachs functions to HTML elements on page load.

Here's how you could do it with vanilla JavaScript:

<textarea onkeydown="if (event.keyCode == 13) { this.form.submit(); return false; }"></textarea>

Keycode 13 is the enter key.

Here's how you could do it with jQuery like as Stackoverflow does:

<textarea class="commentarea"></textarea>

with

$(document).ready(function() {
    $('.commentarea').keydown(function(event) {
        if (event.which == 13) {
            this.form.submit();
            event.preventDefault();
         }
    });
});

SQL Server Express CREATE DATABASE permission denied in database 'master'

After I performed the following instructions in SSMS, everything works fine:

create login [IIS APPPOOL\MyWebAPP] from windows;

exec sp_addsrvrolemember N'IIS APPPOOL\MyWebAPP', sysadmin

Error - is not marked as serializable

Leaving my specific solution of this for prosperity, as it's a tricky version of this problem:

Type 'System.Linq.Enumerable+WhereSelectArrayIterator[T...] was not marked as serializable

Due to a class with an attribute IEnumerable<int> eg:

[Serializable]
class MySessionData{
    public int ID;
    public IEnumerable<int> RelatedIDs; //This can be an issue
}

Originally the problem instance of MySessionData was set from a non-serializable list:

MySessionData instance = new MySessionData(){ 
    ID = 123,
    RelatedIDs = nonSerizableList.Select<int>(item => item.ID)
};

The cause here is the concrete class that the Select<int>(...) returns, has type data that's not serializable, and you need to copy the id's to a fresh List<int> to resolve it.

RelatedIDs = nonSerizableList.Select<int>(item => item.ID).ToList();

Serializing an object as UTF-8 XML in .NET

Very good answer using inheritance, just remember to override the initializer

public class Utf8StringWriter : StringWriter
{
    public Utf8StringWriter(StringBuilder sb) : base (sb)
    {
    }
    public override Encoding Encoding { get { return Encoding.UTF8; } }
}

Restoring MySQL database from physical files

With MySql 5.1 (Win7). To recreate DBs (InnoDbs) I've replaced all contents of following dirs (my.ini params):

datadir="C:/ProgramData/MySQL/MySQL Server 5.1/Data/"
innodb_data_home_dir="C:/MySQL Datafiles/"

After that I started MySql Service and all works fine.

How to Install Sublime Text 3 using Homebrew

An update

Turns out now brew cask install sublime-text installs the most up to date version (e.g. 3) by default and brew cask is now part of the standard brew-installation.

Excel formula to search if all cells in a range read "True", if not, then show "False"

=COUNTIFS(1:1,FALSE)=0

This will return TRUE or FALSE (Looks for FALSE, if count isn't 0 (all True) it will be false

Change image size with JavaScript

If you want to resize an image after it is loaded, you can attach to the onload event of the <img> tag. Note that it may not be supported in all browsers (Microsoft's reference claims it is part of the HTML 4.0 spec, but the HTML 4.0 spec doesn't list the onload event for <img>).

The code below is tested and working in: IE 6, 7 & 8, Firefox 2, 3 & 3.5, Opera 9 & 10, Safari 3 & 4 and Google Chrome:

<img src="yourImage.jpg" border="0" height="real_height" width="real_width"
    onload="resizeImg(this, 200, 100);">

<script type="text/javascript">
function resizeImg(img, height, width) {
    img.height = height;
    img.width = width;
}
</script>

Maven Java EE Configuration Marker with Java Server Faces 1.2

The m2e plugin generate project configuration every time when you update project (Maven->Update Project ... That action overrides facets setting configured manually in Eclipse. Therefore you have to configure it on pom level. By setting properties in pom file you can tell m2e plugin what to do.

Enable/Disable the JAX-RS/JPA/JSF Configurators at the pom.xml level The optional JAX-RS, JPA and JSF configurators can be enabled or disabled at a workspace level from Window > Preferences > Maven > Java EE Integration. Now, you can have a finer grain control on these configurators directly from your pom.xml properties :

Adding false in your pom properties section will disable the JAX-RS configurator Adding false in your pom properties section will disable the JPA configurator Adding false in your pom properties section will disable the JSF configurator The pom settings always override the workspace preferences. So if you have, for instance the JPA configurator disabled at the workspace level, using true will enable it on your project anyway. (http://wiki.eclipse.org/M2E-WTP/New_and_Noteworthy/1.0.0)

How to append new data onto a new line

import subprocess
subprocess.check_output('echo "' + YOURTEXT + '" >> hello.txt',shell=True)

Binding Listbox to List<object> in WinForms

For a UWP app:

XAML

<ListBox x:Name="List" DisplayMemberPath="Source" ItemsSource="{x:Bind Results}"/>

C#

public ObservableCollection<Type> Results

How to get a barplot with several variables side by side grouped by a factor

You can plot the means without resorting to external calculations and additional tables using stat_summary(...). In fact, stat_summary(...) was designed for exactly what you are doing.

library(ggplot2)
library(reshape2)            # for melt(...)
gg <- melt(df,id="gender")   # df is your original table
ggplot(gg, aes(x=variable, y=value, fill=factor(gender))) + 
  stat_summary(fun.y=mean, geom="bar",position=position_dodge(1)) + 
  scale_color_discrete("Gender")
  stat_summary(fun.ymin=min,fun.ymax=max,geom="errorbar",
               color="grey80",position=position_dodge(1), width=.2)

To add "error bars" you cna also use stat_summary(...) (here, I'm using the min and max value rather than sd because you have so little data).

ggplot(gg, aes(x=variable, y=value, fill=factor(gender))) + 
  stat_summary(fun.y=mean, geom="bar",position=position_dodge(1)) + 
  stat_summary(fun.ymin=min,fun.ymax=max,geom="errorbar",
               color="grey40",position=position_dodge(1), width=.2) +
  scale_fill_discrete("Gender")

How to form tuple column from two columns in Pandas

Get comfortable with zip. It comes in handy when dealing with column data.

df['new_col'] = list(zip(df.lat, df.long))

It's less complicated and faster than using apply or map. Something like np.dstack is twice as fast as zip, but wouldn't give you tuples.

how to use "AND", "OR" for RewriteCond on Apache?

After many struggles and to achive a general, flexible and more readable solution, in my case I ended up saving the ORs results into ENV variables and doing the ANDs of those variables.

# RESULT_ONE = A OR B
RewriteRule ^ - [E=RESULT_ONE:False]
RewriteCond ...A... [OR]
RewriteCond ...B...
RewriteRule ^ - [E=RESULT_ONE:True]

# RESULT_TWO = C OR D
RewriteRule ^ - [E=RESULT_TWO:False]
RewriteCond ...C... [OR]
RewriteCond ...D...
RewriteRule ^ - [E=RESULT_TWO:True]

# if ( RESULT_ONE AND RESULT_TWO ) then ( RewriteRule ...something... )
RewriteCond %{ENV:RESULT_ONE} =True
RewriteCond %{ENV:RESULT_TWO} =True
RewriteRule ...something...

Requirements:

How do I get indices of N maximum values in a NumPy array?

Here's a more complicated way that increases n if the nth value has ties:

>>>> def get_top_n_plus_ties(arr,n):
>>>>     sorted_args = np.argsort(-arr)
>>>>     thresh = arr[sorted_args[n]]
>>>>     n_ = np.sum(arr >= thresh)
>>>>     return sorted_args[:n_]
>>>> get_top_n_plus_ties(np.array([2,9,8,3,0,2,8,3,1,9,5]),3)
array([1, 9, 2, 6])

Split a string by another string in C#

Regex.Split(string, "xx")

is the way I do it usually.


Of course you'll need:

using System.Text.RegularExpressions;

or :

System.Text.RegularExpressions.Regex.Split(string, "xx")

but then again I need that library all the time.

jquery ajax get responsetext from http url

Since jQuery AJAX requests fail if they are cross-domain, you can use cURL (in PHP) to set up a proxy server.

Suppose a PHP file responder.php has these contents:

$url = "https://www.google.com";
$ch      = curl_init( $url );
curl_set_opt($ch, CURLOPT_RETURNTRANSFER, "true")
$response= curl_exec( $ch );
curl_close( $ch );
return $response;

Your AJAX request should be to this responder.php file so that it executes the cross-domain request.

Convert LocalDateTime to LocalDateTime in UTC

There is an even simpler way

LocalDateTime.now(Clock.systemUTC())

500 internal server error, how to debug

You can turn on your PHP errors with error_reporting:

error_reporting(E_ALL);
ini_set('display_errors', 'on');

Edit: It's possible that even after putting this, errors still don't show up. This can be caused if there is a fatal error in the script. From PHP Runtime Configuration:

Although display_errors may be set at runtime (with ini_set()), it won't have any affect if the script has fatal errors. This is because the desired runtime action does not get executed.

You should set display_errors = 1 in your php.ini file and restart the server.

Rails: Get Client IP address

I would just use the request.remote_ip that's simple and it works. Any reason you need another method?

See: Get real IP address in local Rails development environment for some other things you can do with client server ip's.

Get all validation errors from Angular 2 FormGroup

Try This , it will call validation for all control in form :

validateAllFormControl(formGroup: FormGroup) {         
  Object.keys(formGroup.controls).forEach(field => {  
    const control = formGroup.get(field);             
    if (control instanceof FormControl) {             
      control.markAsTouched({ onlySelf: true });
    } else if (control instanceof FormGroup) {        
      this.validateAllFormControl(control);            
    }
  });
}

Count table rows

select count(*) from YourTable

Reverting single file in SVN to a particular revision

You want to do

svn merge -r [revision to revert from]:[revision to revert to] [path/filename]

Once you do that, you will have that revision of the file in a committable state. Commit the file.

How to find my php-fpm.sock?

Check the config file, the config path is /etc/php5/fpm/pool.d/www.conf, there you'll find the path by config and if you want you can change it.

EDIT:
well you're correct, you need to replace listen = 127.0.0.1:9000 to listen = /var/run/php5-fpm/php5-fpm.sock, then you need to run sudo service php5-fpm restart, and make sure it says that it restarted correctly, if not then make sure that /var/run/ has a folder called php5-fpm, or make it listen to /var/run/php5-fpm.sock cause i don't think the folder inside /var/run is created automatically, i remember i had to edit the start up script to create that folder, otherwise even if you mkdir /var/run/php5-fpm after restart that folder will disappear and the service starting will fail.

Format numbers in django templates

If you don't want to get involved with locales here is a function that formats numbers:

def int_format(value, decimal_points=3, seperator=u'.'):
    value = str(value)
    if len(value) <= decimal_points:
        return value
    # say here we have value = '12345' and the default params above
    parts = []
    while value:
        parts.append(value[-decimal_points:])
        value = value[:-decimal_points]
    # now we should have parts = ['345', '12']
    parts.reverse()
    # and the return value should be u'12.345'
    return seperator.join(parts)

Creating a custom template filter from this function is trivial.

How to increase Bootstrap Modal Width?

I suppose this happens due to the max-width of a modal being set to 500px and max-width of modal-lg is 800px I suppose setting it to auto will make your modal responsive

Maven: repository element was not specified in the POM inside distributionManagement?

For me, this was something as simple as a missing version for my artifact - "1.1-SNAPSHOT"

Forward host port to docker container

I had a similar problem accessing a LDAP-Server from a docker container. I set a fixed IP for the container and added a firewall rule.

docker-compose.yml:

version: '2'
services:
  containerName:
    image: dockerImageName:latest
    extra_hosts:
      - "dockerhost:192.168.50.1"
    networks:
      my_net:
        ipv4_address: 192.168.50.2
networks:
  my_net:
    ipam:
      config:
      - subnet: 192.168.50.0/24

iptables rule:

iptables -A INPUT -j ACCEPT -p tcp -s 192.168.50.2 -d $192.168.50.1 --dport portnumberOnHost

Inside the container access dockerhost:portnumberOnHost

Microsoft Web API: How do you do a Server.MapPath?

You can try like:

var path="~/Image/test.png"; System.Web.Hosting.HostingEnvironment.MapPath( @ + path)

How to retrieve an Oracle directory path?

The ALL_DIRECTORIES data dictionary view will have information about all the directories that you have access to. That includes the operating system path

SELECT owner, directory_name, directory_path
  FROM all_directories

Check if bash variable equals 0

You can try this:

: ${depth?"Error Message"} ## when your depth variable is not even declared or is unset.

NOTE: Here it's just ? after depth.

or

: ${depth:?"Error Message"} ## when your depth variable is declared but is null like: "depth=". 

NOTE: Here it's :? after depth.

Here if the variable depth is found null it will print the error message and then exit.

How to filter wireshark to see only dns queries that are sent/received from/by my computer?

I would go through the packet capture and see if there are any records that I know I should be seeing to validate that the filter is working properly and to assuage any doubts.

That said, please try the following filter and see if you're getting the entries that you think you should be getting:

dns and ip.dst==159.25.78.7 or dns and ip.src==159.57.78.7

Want to move a particular div to right

You can use float on that particular div, e.g.

<div style="float:right;">

Float the div you want more space to have to the left as well:

<div style="float:left;">

If all else fails give the div on the right position:absolute and then move it as right as you want it to be.

<div style="position:absolute; left:-500px; top:30px;"> 

etc. Obviously put the style in a seperate stylesheet but this is just a quicker example.

How to use basic authorization in PHP curl

Can you try this,

 $ch = curl_init($url);
 ...
 curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);  
 ...

REF: http://php.net/manual/en/function.curl-setopt.php

Spark difference between reduceByKey vs groupByKey vs aggregateByKey vs combineByKey

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

Note : One similarity is they all are wide operations.

Offset a background image from the right using CSS

If you have proportioned elements, you could use:

.valid {
    background-position: 98% center;
}

.half .valid {
    background-position: 96% center;
}

In this example, .valid would be the class with the picture and .half would be a row with half the size of the standard one.

Dirty, but works as a charm and it's reasonably manageable.

Difference between Pragma and Cache-Control headers?

There is no difference, except that Pragma is only defined as applicable to the requests by the client, whereas Cache-Control may be used by both the requests of the clients and the replies of the servers.

So, as far as standards go, they can only be compared from the perspective of the client making a requests and the server receiving a request from the client. The http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.32 defines the scenario as follows:

HTTP/1.1 caches SHOULD treat "Pragma: no-cache" as if the client had sent "Cache-Control: no-cache". No new Pragma directives will be defined in HTTP.

  Note: because the meaning of "Pragma: no-cache as a response
  header field is not actually specified, it does not provide a
  reliable replacement for "Cache-Control: no-cache" in a response

The way I would read the above:

  • if you're writing a client and need no-cache:

    • just use Pragma: no-cache in your requests, since you may not know if Cache-Control is supported by the server;
    • but in replies, to decide on whether to cache, check for Cache-Control
  • if you're writing a server:

    • in parsing requests from the clients, check for Cache-Control; if not found, check for Pragma: no-cache, and execute the Cache-Control: no-cache logic;
    • in replies, provide Cache-Control.

Of course, reality might be different from what's written or implied in the RFC!

How can I add a class to a DOM element in JavaScript?

If doing a lot of element creations, you can create your own basic createElementWithClass function.

function createElementWithClass(type, className) {
  const element = document.createElement(type);
  element.className = className
  return element;
}

Very basic I know, but being able to call the following is less cluttering.

const myDiv = createElementWithClass('div', 'some-class')

as opposed to a lot of

 const element1 = document.createElement('div');
 element.className = 'a-class-name'

over and over.

Find nearest value in numpy array

This is a vectorized version of unutbu's answer:

def find_nearest(array, values):
    array = np.asarray(array)

    # the last dim must be 1 to broadcast in (array - values) below.
    values = np.expand_dims(values, axis=-1) 

    indices = np.abs(array - values).argmin(axis=-1)

    return array[indices]


image = plt.imread('example_3_band_image.jpg')

print(image.shape) # should be (nrows, ncols, 3)

quantiles = np.linspace(0, 255, num=2 ** 2, dtype=np.uint8)

quantiled_image = find_nearest(quantiles, image)

print(quantiled_image.shape) # should be (nrows, ncols, 3)

How can I convert a zero-terminated byte array to string?

Simplistic solution:

str := fmt.Sprintf("%s", byteArray)

I'm not sure how performant this is though.

Add a link to an image in a css style sheet

You can not do that...

via css the URL you put on the background-image is just for the image.

Via HTML you have to add the href for your hyperlink in this way:

<a href="http://home.com" id="logo">Your logo</a>

With text-indent and some other css you can adjust your a element to show just the image and clicking on it you will go to your link.


EDIT:

I'm here again to show you and explain why my solution is much better:

<a href="http://home.com" id="logo">Your logo name</a>

This block of HTML is SEO friendly because you have some text inside your link!

How to style it with css:

#logo {
  background-image: url(images/logo.png);
  display: block;
  margin: 0 auto;
  text-indent: -9999px;
  width: 981px;
  height: 180px;
}

Then if you don't care about SEO good to choose the other answer.

grant remote access of MySQL database from any IP address

For example in my CentOS

sudo gedit /etc/mysql/my.cnf

comment out the following lines

#bind-address = 127.0.0.1

then

sudo service mysqld restart

How do I find out where login scripts live?

The default location for logon scripts is the netlogon share of a domain controller. On the server this is located:

%SystemRoot%'SYSVOL'sysvol''scripts

It can presumably be changes from this default but I've never met anyone that had a reason to.

To get list of domain controllers programatically see this article: http://www.microsoft.com/technet/scriptcenter/resources/qanda/dec04/hey1216.mspx

How to apply CSS to iframe?

As many answers are written for the same domains, I'll write how to do this in cross domains.

First, you need to know the Post Message API. We need a messenger to communicate between two windows.

Here's a messenger I created.

/**
 * Creates a messenger between two windows
 *  which have two different domains
 */
class CrossMessenger {

    /**
     * 
     * @param {object} otherWindow - window object of the other
     * @param {string} targetDomain - domain of the other window
     * @param {object} eventHandlers - all the event names and handlers
     */
    constructor(otherWindow, targetDomain, eventHandlers = {}) {
        this.otherWindow = otherWindow;
        this.targetDomain = targetDomain;
        this.eventHandlers = eventHandlers;

        window.addEventListener("message", (e) => this.receive.call(this, e));
    }

    post(event, data) {

        try {
            // data obj should have event name
            var json = JSON.stringify({
                event,
                data
            });
            this.otherWindow.postMessage(json, this.targetDomain);

        } catch (e) {}
    }

    receive(e) {
        var json;
        try {
            json = JSON.parse(e.data ? e.data : "{}");
        } catch (e) {
            return;
        }
        var eventName = json.event,
            data = json.data;

        if (e.origin !== this.targetDomain)
            return;

        if (typeof this.eventHandlers[eventName] === "function") 
            this.eventHandlers[eventName](data);
    }

}

Using this in two windows to communicate can solve your problem.

In the main windows,

var msger = new CrossMessenger(iframe.contentWindow, "https://iframe.s.domain");

var cssContent = Array.prototype.map.call(yourCSSElement.sheet.cssRules, css_text).join('\n');
msger.post("cssContent", {
   css: cssContent
})

Then, receive the event from the Iframe.

In the Iframe:

var msger = new CrossMessenger(window.parent, "https://parent.window.domain", {
    cssContent: (data) => {
        var cssElem = document.createElement("style");
        cssElem.innerHTML = data.css;
        document.head.appendChild(cssElem);
    }
})

See the Complete Javascript and Iframes tutorial for more details.

vim line numbers - how to have them on by default?

Add set number to your .vimrc file in your home directory.
If the .vimrc file is not in your home directory create one with vim .vimrc and add the commands you want at open.

Here's a site that explains the vimrc and how to use it.

Creating a static class with no instances

There are two ways to do that (Python 2.6+):

static method

class Klass(object):
    @staticmethod
    def static_method():
        print "Hello World"

Klass.static_method()

module

your module file, called klass.py

def static_method():
    print "Hello World"

your code:

import klass

klass.static_method()

How to switch between hide and view password

Did you try with setTransformationMethod? It's inherited from TextView and want a TransformationMethod as a parameter.

You can find more about TransformationMethods here.

It also has some cool features, like character replacing.

Change header text of columns in a GridView

You should do that in GridView's RowDataBound event which is triggered for every GridViewRow after it was databound.

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Header)
    {
        e.Row.Cells[0].Text = "Date";
    }
}

or you can set AutogenerateColumns to false and add the columns declaratively on aspx:

<asp:gridview id="GridView1" 
  onrowdatabound="GridView1_RowDataBound"
  autogeneratecolumns="False"
  emptydatatext="No data available." 
   runat="server">
    <Columns>
         <asp:BoundField DataField="DateField" HeaderText="Date" 
            SortExpression="DateField" />
    </Columns>
</asp:gridview>

vagrant login as root by default

Solution:
Add the following to your Vagrantfile:

config.ssh.username = 'root'
config.ssh.password = 'vagrant'
config.ssh.insert_key = 'true'

When you vagrant ssh henceforth, you will login as root and should expect the following:

==> mybox: Waiting for machine to boot. This may take a few minutes...
    mybox: SSH address: 127.0.0.1:2222
    mybox: SSH username: root
    mybox: SSH auth method: password
    mybox: Warning: Connection timeout. Retrying...
    mybox: Warning: Remote connection disconnect. Retrying...
==> mybox: Inserting Vagrant public key within guest...
==> mybox: Key inserted! Disconnecting and reconnecting using new SSH key...
==> mybox: Machine booted and ready!

Update 23-Jun-2015: This works for version 1.7.2 as well. Keying security has improved since 1.7.0; this technique overrides back to the previous method which uses a known private key. This solution is not intended to be used for a box that is accessible publicly without proper security measures done prior to publishing.

Reference:

Append values to query string

The provided answers have issues with relative Url's, such as "/some/path/" This is a limitation of the Uri and UriBuilder class, which is rather hard to understand, since I don't see any reason why relative urls would be problematic when it comes to query manipulation.

Here is a workaround that works for both absolute and relative paths, written and tested in .NET 4:

(small note: this should also work in .NET 4.5, you will only have to change propInfo.GetValue(values, null) to propInfo.GetValue(values))

  public static class UriExtensions{
    /// <summary>
    ///     Adds query string value to an existing url, both absolute and relative URI's are supported.
    /// </summary>
    /// <example>
    /// <code>
    ///     // returns "www.domain.com/test?param1=val1&amp;param2=val2&amp;param3=val3"
    ///     new Uri("www.domain.com/test?param1=val1").ExtendQuery(new Dictionary&lt;string, string&gt; { { "param2", "val2" }, { "param3", "val3" } }); 
    /// 
    ///     // returns "/test?param1=val1&amp;param2=val2&amp;param3=val3"
    ///     new Uri("/test?param1=val1").ExtendQuery(new Dictionary&lt;string, string&gt; { { "param2", "val2" }, { "param3", "val3" } }); 
    /// </code>
    /// </example>
    /// <param name="uri"></param>
    /// <param name="values"></param>
    /// <returns></returns>
    public static Uri ExtendQuery(this Uri uri, IDictionary<string, string> values) {
      var baseUrl = uri.ToString();
      var queryString = string.Empty;
      if (baseUrl.Contains("?")) {
        var urlSplit = baseUrl.Split('?');
        baseUrl = urlSplit[0];
        queryString = urlSplit.Length > 1 ? urlSplit[1] : string.Empty;
      }

      NameValueCollection queryCollection = HttpUtility.ParseQueryString(queryString);
      foreach (var kvp in values ?? new Dictionary<string, string>()) {
        queryCollection[kvp.Key] = kvp.Value;
      }
      var uriKind = uri.IsAbsoluteUri ? UriKind.Absolute : UriKind.Relative;
      return queryCollection.Count == 0 
        ? new Uri(baseUrl, uriKind) 
        : new Uri(string.Format("{0}?{1}", baseUrl, queryCollection), uriKind);
    }

    /// <summary>
    ///     Adds query string value to an existing url, both absolute and relative URI's are supported.
    /// </summary>
    /// <example>
    /// <code>
    ///     // returns "www.domain.com/test?param1=val1&amp;param2=val2&amp;param3=val3"
    ///     new Uri("www.domain.com/test?param1=val1").ExtendQuery(new { param2 = "val2", param3 = "val3" }); 
    /// 
    ///     // returns "/test?param1=val1&amp;param2=val2&amp;param3=val3"
    ///     new Uri("/test?param1=val1").ExtendQuery(new { param2 = "val2", param3 = "val3" }); 
    /// </code>
    /// </example>
    /// <param name="uri"></param>
    /// <param name="values"></param>
    /// <returns></returns>
    public static Uri ExtendQuery(this Uri uri, object values) {
      return ExtendQuery(uri, values.GetType().GetProperties().ToDictionary
      (
          propInfo => propInfo.Name,
          propInfo => { var value = propInfo.GetValue(values, null); return value != null ? value.ToString() : null; }
      ));
    }
  }

And here is a suite of unit tests to test the behavior:

  [TestFixture]
  public class UriExtensionsTests {
    [Test]
    public void Add_to_query_string_dictionary_when_url_contains_no_query_string_and_values_is_empty_should_return_url_without_changing_it() {
      Uri url = new Uri("http://www.domain.com/test");
      var values = new Dictionary<string, string>();
      var result = url.ExtendQuery(values);
      Assert.That(result, Is.EqualTo(new Uri("http://www.domain.com/test")));
    }

    [Test]
    public void Add_to_query_string_dictionary_when_url_contains_hash_and_query_string_values_are_empty_should_return_url_without_changing_it() {
      Uri url = new Uri("http://www.domain.com/test#div");
      var values = new Dictionary<string, string>();
      var result = url.ExtendQuery(values);
      Assert.That(result, Is.EqualTo(new Uri("http://www.domain.com/test#div")));
    }

    [Test]
    public void Add_to_query_string_dictionary_when_url_contains_no_query_string_should_add_values() {
      Uri url = new Uri("http://www.domain.com/test");
      var values = new Dictionary<string, string> { { "param1", "val1" }, { "param2", "val2" } };
      var result = url.ExtendQuery(values);
      Assert.That(result, Is.EqualTo(new Uri("http://www.domain.com/test?param1=val1&param2=val2")));
    }

    [Test]
    public void Add_to_query_string_dictionary_when_url_contains_hash_and_no_query_string_should_add_values() {
      Uri url = new Uri("http://www.domain.com/test#div");
      var values = new Dictionary<string, string> { { "param1", "val1" }, { "param2", "val2" } };
      var result = url.ExtendQuery(values);
      Assert.That(result, Is.EqualTo(new Uri("http://www.domain.com/test#div?param1=val1&param2=val2")));
    }

    [Test]
    public void Add_to_query_string_dictionary_when_url_contains_query_string_should_add_values_and_keep_original_query_string() {
      Uri url = new Uri("http://www.domain.com/test?param1=val1");
      var values = new Dictionary<string, string> { { "param2", "val2" } };
      var result = url.ExtendQuery(values);
      Assert.That(result, Is.EqualTo(new Uri("http://www.domain.com/test?param1=val1&param2=val2")));
    }

    [Test]
    public void Add_to_query_string_dictionary_when_url_is_relative_contains_no_query_string_should_add_values() {
      Uri url = new Uri("/test", UriKind.Relative);
      var values = new Dictionary<string, string> { { "param1", "val1" }, { "param2", "val2" } };
      var result = url.ExtendQuery(values);
      Assert.That(result, Is.EqualTo(new Uri("/test?param1=val1&param2=val2", UriKind.Relative)));
    }

    [Test]
    public void Add_to_query_string_dictionary_when_url_is_relative_and_contains_query_string_should_add_values_and_keep_original_query_string() {
      Uri url = new Uri("/test?param1=val1", UriKind.Relative);
      var values = new Dictionary<string, string> { { "param2", "val2" } };
      var result = url.ExtendQuery(values);
      Assert.That(result, Is.EqualTo(new Uri("/test?param1=val1&param2=val2", UriKind.Relative)));
    }

    [Test]
    public void Add_to_query_string_dictionary_when_url_is_relative_and_contains_query_string_with_existing_value_should_add_new_values_and_update_existing_ones() {
      Uri url = new Uri("/test?param1=val1", UriKind.Relative);
      var values = new Dictionary<string, string> { { "param1", "new-value" }, { "param2", "val2" } };
      var result = url.ExtendQuery(values);
      Assert.That(result, Is.EqualTo(new Uri("/test?param1=new-value&param2=val2", UriKind.Relative)));
    }

    [Test]
    public void Add_to_query_string_object_when_url_contains_no_query_string_should_add_values() {
      Uri url = new Uri("http://www.domain.com/test");
      var values = new { param1 = "val1", param2 = "val2" };
      var result = url.ExtendQuery(values);
      Assert.That(result, Is.EqualTo(new Uri("http://www.domain.com/test?param1=val1&param2=val2")));
    }


    [Test]
    public void Add_to_query_string_object_when_url_contains_query_string_should_add_values_and_keep_original_query_string() {
      Uri url = new Uri("http://www.domain.com/test?param1=val1");
      var values = new { param2 = "val2" };
      var result = url.ExtendQuery(values);
      Assert.That(result, Is.EqualTo(new Uri("http://www.domain.com/test?param1=val1&param2=val2")));
    }

    [Test]
    public void Add_to_query_string_object_when_url_is_relative_contains_no_query_string_should_add_values() {
      Uri url = new Uri("/test", UriKind.Relative);
      var values = new { param1 = "val1", param2 = "val2" };
      var result = url.ExtendQuery(values);
      Assert.That(result, Is.EqualTo(new Uri("/test?param1=val1&param2=val2", UriKind.Relative)));
    }

    [Test]
    public void Add_to_query_string_object_when_url_is_relative_and_contains_query_string_should_add_values_and_keep_original_query_string() {
      Uri url = new Uri("/test?param1=val1", UriKind.Relative);
      var values = new { param2 = "val2" };
      var result = url.ExtendQuery(values);
      Assert.That(result, Is.EqualTo(new Uri("/test?param1=val1&param2=val2", UriKind.Relative)));
    }

    [Test]
    public void Add_to_query_string_object_when_url_is_relative_and_contains_query_string_with_existing_value_should_add_new_values_and_update_existing_ones() {
      Uri url = new Uri("/test?param1=val1", UriKind.Relative);
      var values = new { param1 = "new-value", param2 = "val2" };
      var result = url.ExtendQuery(values);
      Assert.That(result, Is.EqualTo(new Uri("/test?param1=new-value&param2=val2", UriKind.Relative)));
    }
  }

What is initial scale, user-scalable, minimum-scale, maximum-scale attribute in meta tag?

This meta tag is used by all responsive web pages, that is those that are designed to layout well across device types - phone, tablet, and desktop. The attributes do what they say. However, as MDN's Using the viewport meta tag to control layout on mobile browsers indicates,

On high dpi screens, pages with initial-scale=1 will effectively be zoomed by browsers.

I've found that the following ensures that the page displays with zero zoom by default.

<meta name="viewport" content="width=device-width, initial-scale=0.86, maximum-scale=3.0, minimum-scale=0.86">

Can we make unsigned byte in Java

You can also:

public static int unsignedToBytes(byte a)
{
    return (int) ( ( a << 24) >>> 24);
}    

Explanation:

let's say a = (byte) 133;

In memory it's stored as: "1000 0101" (0x85 in hex)

So its representation translates unsigned=133, signed=-123 (as 2's complement)

a << 24

When left shift is performed 24 bits to the left, the result is now a 4 byte integer which is represented as:

"10000101 00000000 00000000 00000000" (or "0x85000000" in hex)

then we have

( a << 24) >>> 24

and it shifts again on the right 24 bits but fills with leading zeros. So it results to:

"00000000 00000000 00000000 10000101" (or "0x00000085" in hex)

and that is the unsigned representation which equals to 133.

If you tried to cast a = (int) a; then what would happen is it keeps the 2's complement representation of byte and stores it as int also as 2's complement:

(int) "10000101" ---> "11111111 11111111 11111111 10000101"

And that translates as: -123

Using Java 8's Optional with Stream::flatMap

I'd like to promote factory methods for creating helpers for functional APIs:

Optional<R> result = things.stream()
        .flatMap(streamopt(this::resolve))
        .findFirst();

The factory method:

<T, R> Function<T, Stream<R>> streamopt(Function<T, Optional<R>> f) {
    return f.andThen(Optional::stream); // or the J8 alternative:
    // return t -> f.apply(t).map(Stream::of).orElseGet(Stream::empty);
}

Reasoning:

  • As with method references in general, compared to lambda expressions, you can't accidentaly capture a variable from the accessible scope, like:

    t -> streamopt(resolve(o))

  • It's composable, you can e.g. call Function::andThen on the factory method result:

    streamopt(this::resolve).andThen(...)

    Whereas in the case of a lambda, you'd need to cast it first:

    ((Function<T, Stream<R>>) t -> streamopt(resolve(t))).andThen(...)

How to restart kubernetes nodes?

I had an onpremises HA installation, a master and a worker stopped working returning a NOTReady status. Checking the kubelet logs on the nodes I found out this problem:

failed to run Kubelet: Running with swap on is not supported, please disable swap! or set --fail-swap-on flag to false

Disabling swap on nodes with

swapoff -a

and restarting the kubelet

systemctl restart kubelet

did the work.

How to check if an array value exists?

You could use the PHP in_array function

if( in_array( "bla" ,$yourarray ) )
{
    echo "has bla";
}

How to implement swipe gestures for mobile devices?

I made this function for my needs.

Feel free to use it. Works great on mobile devices.

function detectswipe(el,func) {
  swipe_det = new Object();
  swipe_det.sX = 0; swipe_det.sY = 0; swipe_det.eX = 0; swipe_det.eY = 0;
  var min_x = 30;  //min x swipe for horizontal swipe
  var max_x = 30;  //max x difference for vertical swipe
  var min_y = 50;  //min y swipe for vertical swipe
  var max_y = 60;  //max y difference for horizontal swipe
  var direc = "";
  ele = document.getElementById(el);
  ele.addEventListener('touchstart',function(e){
    var t = e.touches[0];
    swipe_det.sX = t.screenX; 
    swipe_det.sY = t.screenY;
  },false);
  ele.addEventListener('touchmove',function(e){
    e.preventDefault();
    var t = e.touches[0];
    swipe_det.eX = t.screenX; 
    swipe_det.eY = t.screenY;    
  },false);
  ele.addEventListener('touchend',function(e){
    //horizontal detection
    if ((((swipe_det.eX - min_x > swipe_det.sX) || (swipe_det.eX + min_x < swipe_det.sX)) && ((swipe_det.eY < swipe_det.sY + max_y) && (swipe_det.sY > swipe_det.eY - max_y) && (swipe_det.eX > 0)))) {
      if(swipe_det.eX > swipe_det.sX) direc = "r";
      else direc = "l";
    }
    //vertical detection
    else if ((((swipe_det.eY - min_y > swipe_det.sY) || (swipe_det.eY + min_y < swipe_det.sY)) && ((swipe_det.eX < swipe_det.sX + max_x) && (swipe_det.sX > swipe_det.eX - max_x) && (swipe_det.eY > 0)))) {
      if(swipe_det.eY > swipe_det.sY) direc = "d";
      else direc = "u";
    }

    if (direc != "") {
      if(typeof func == 'function') func(el,direc);
    }
    direc = "";
    swipe_det.sX = 0; swipe_det.sY = 0; swipe_det.eX = 0; swipe_det.eY = 0;
  },false);  
}

function myfunction(el,d) {
  alert("you swiped on element with id '"+el+"' to "+d+" direction");
}

To use the function just use it like

detectswipe('an_element_id',myfunction);

detectswipe('an_other_element_id',my_other_function);

If a swipe is detected the function "myfunction" is called with parameter element-id and "l,r,u,d" (left,right,up,down).

Example: http://jsfiddle.net/rvuayqeo/1/


I (UlysseBN) made a new version of this script based on this one which use more modern JavaScript, it looks like it behaves better on some cases. If you think it should rather be an edit of this answer let me know, if you are the original author and you end up editing, I'll delete my answer.

Set cellpadding and cellspacing in CSS?

Also, if you want cellspacing="0", don't forget to add border-collapse: collapse in your table's stylesheet.

How to rename a table column in Oracle 10g

alter table table_name rename column oldColumn to newColumn;

Drop all data in a pandas dataframe

If your goal is to drop the dataframe, then you need to pass all columns. For me: the best way is to pass a list comprehension to the columns kwarg. This will then work regardless of the different columns in a df.

import pandas as pd

web_stats = {'Day': [1, 2, 3, 4, 2, 6],
             'Visitors': [43, 43, 34, 23, 43, 23],
             'Bounce_Rate': [3, 2, 4, 3, 5, 5]}
df = pd.DataFrame(web_stats)

df.drop(columns=[i for i in check_df.columns])

best practice font size for mobile

The font sizes in your question are an example of what ratio each header should be in comparison to each other, rather than what size they should be themselves (in pixels).

So in response to your question "Is there a 'best practice' for these for mobile phones? - say iphone screen size?", yes there probably is - but you might find what someone says is "best practice" does not work for your layout.

However, to help get you on the right track, this article about building responsive layouts provides a good example of how to calculate the base font-size in pixels in relation to device screen sizes.

The suggested font-sizes for screen resolutions suggested from that article are as follows:

@media (min-width: 858px) {
    html {
        font-size: 12px;
    }
}

@media (min-width: 780px) {
    html {
        font-size: 11px;
    }
}

@media (min-width: 702px) {
    html {
        font-size: 10px;
    }
}

@media (min-width: 724px) {
    html {
        font-size: 9px;
    }
}

@media (max-width: 623px) {
    html {
        font-size: 8px;
    }
}

The default for KeyValuePair

I recommend more understanding way using extension method:

public static class KeyValuePairExtensions
{
    public static bool IsNull<T, TU>(this KeyValuePair<T, TU> pair)
    {
        return pair.Equals(new KeyValuePair<T, TU>());
    }
}

And then just use:

var countries = new Dictionary<string, string>
{
    {"cz", "prague"},
    {"de", "berlin"}
};

var country = countries.FirstOrDefault(x => x.Key == "en");

if(country.IsNull()){

}

Use sed to replace all backslashes with forward slashes

I had to use [\\] or [/] to be able to make this work, FYI.

awk '!/[\\]/' file > temp && mv temp file

and

awk '!/[/]/' file > temp && mv temp file

I was using awk to remove backlashes and forward slashes from a list.

jQuery AJAX single file upload

A. Grab file data from the file field

The first thing to do is bind a function to the change event on your file field and a function for grabbing the file data:

// Variable to store your files
var files;

// Add events
$('input[type=file]').on('change', prepareUpload);

// Grab the files and set them to our variable
function prepareUpload(event)
{
  files = event.target.files;
}

This saves the file data to a file variable for later use.

B. Handle the file upload on submit

When the form is submitted you need to handle the file upload in its own AJAX request. Add the following binding and function:

$('form').on('submit', uploadFiles);

// Catch the form submit and upload the files
function uploadFiles(event)
{
  event.stopPropagation(); // Stop stuff happening
    event.preventDefault(); // Totally stop stuff happening

// START A LOADING SPINNER HERE

// Create a formdata object and add the files
var data = new FormData();
$.each(files, function(key, value)
{
    data.append(key, value);
});

$.ajax({
    url: 'submit.php?files',
    type: 'POST',
    data: data,
    cache: false,
    dataType: 'json',
    processData: false, // Don't process the files
    contentType: false, // Set content type to false as jQuery will tell the server its a query string request
    success: function(data, textStatus, jqXHR)
    {
        if(typeof data.error === 'undefined')
        {
            // Success so call function to process the form
            submitForm(event, data);
        }
        else
        {
            // Handle errors here
            console.log('ERRORS: ' + data.error);
        }
    },
    error: function(jqXHR, textStatus, errorThrown)
    {
        // Handle errors here
        console.log('ERRORS: ' + textStatus);
        // STOP LOADING SPINNER
    }
});
}

What this function does is create a new formData object and appends each file to it. It then passes that data as a request to the server. 2 attributes need to be set to false:

  • processData - Because jQuery will convert the files arrays into strings and the server can't pick it up.
  • contentType - Set this to false because jQuery defaults to application/x-www-form-urlencoded and doesn't send the files. Also setting it to multipart/form-data doesn't seem to work either.

C. Upload the files

Quick and dirty php script to upload the files and pass back some info:

<?php // You need to add server side validation and better error handling here

$data = array();

if(isset($_GET['files']))
{  
$error = false;
$files = array();

$uploaddir = './uploads/';
foreach($_FILES as $file)
{
    if(move_uploaded_file($file['tmp_name'], $uploaddir .basename($file['name'])))
    {
        $files[] = $uploaddir .$file['name'];
    }
    else
    {
        $error = true;
    }
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
}
else
{
    $data = array('success' => 'Form was submitted', 'formData' => $_POST);
}

echo json_encode($data);

?>

IMP: Don't use this, write your own.

D. Handle the form submit

The success method of the upload function passes the data sent back from the server to the submit function. You can then pass that to the server as part of your post:

function submitForm(event, data)
{
  // Create a jQuery object from the form
$form = $(event.target);

// Serialize the form data
var formData = $form.serialize();

// You should sterilise the file names
$.each(data.files, function(key, value)
{
    formData = formData + '&filenames[]=' + value;
});

$.ajax({
    url: 'submit.php',
    type: 'POST',
    data: formData,
    cache: false,
    dataType: 'json',
    success: function(data, textStatus, jqXHR)
    {
        if(typeof data.error === 'undefined')
        {
            // Success so call function to process the form
            console.log('SUCCESS: ' + data.success);
        }
        else
        {
            // Handle errors here
            console.log('ERRORS: ' + data.error);
        }
    },
    error: function(jqXHR, textStatus, errorThrown)
    {
        // Handle errors here
        console.log('ERRORS: ' + textStatus);
    },
    complete: function()
    {
        // STOP LOADING SPINNER
    }
});
}

Final note

This script is an example only, you'll need to handle both server and client side validation and some way to notify users that the file upload is happening. I made a project for it on Github if you want to see it working.

Referenced From

Refresh an asp.net page on button click

That on code behind redirect to the same page.

Response.Redirect(Request.RawUrl);

How can I rename a single column in a table at select?

Another option you can choose:

select price = table1.price , other_price = table2.price from .....

Reference:

In case you are curious about the performance or otherwise of aliasing a column using “=” versus “as”.

How to convert NSDate into unix timestamp iphone sdk?

- (void)GetCurrentTimeStamp
    {
        NSDateFormatter *objDateformat = [[NSDateFormatter alloc] init];
        [objDateformat setDateFormat:@"yyyy-MM-dd"];
        NSString    *strTime = [objDateformat stringFromDate:[NSDate date]];
        NSString    *strUTCTime = [self GetUTCDateTimeFromLocalTime:strTime];//You can pass your date but be carefull about your date format of NSDateFormatter.
        NSDate *objUTCDate  = [objDateformat dateFromString:strUTCTime];
        long long milliseconds = (long long)([objUTCDate timeIntervalSince1970] * 1000.0);

        NSString *strTimeStamp = [Nsstring stringwithformat:@"%lld",milliseconds];
        NSLog(@"The Timestamp is = %@",strTimestamp);
    }

 - (NSString *) GetUTCDateTimeFromLocalTime:(NSString *)IN_strLocalTime
    {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        NSDate  *objDate    = [dateFormatter dateFromString:IN_strLocalTime];
        [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
        NSString *strDateTime   = [dateFormatter stringFromDate:objDate];
        return strDateTime;
    }

NOTE :- The Timestamp must be in UTC Zone, So I convert our local Time to UTC Time.

How can I shuffle an array?

Use the modern version of the Fisher–Yates shuffle algorithm:

/**
 * Shuffles array in place.
 * @param {Array} a items An array containing the items.
 */
function shuffle(a) {
    var j, x, i;
    for (i = a.length - 1; i > 0; i--) {
        j = Math.floor(Math.random() * (i + 1));
        x = a[i];
        a[i] = a[j];
        a[j] = x;
    }
    return a;
}

ES2015 (ES6) version

/**
 * Shuffles array in place. ES6 version
 * @param {Array} a items An array containing the items.
 */
function shuffle(a) {
    for (let i = a.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [a[i], a[j]] = [a[j], a[i]];
    }
    return a;
}

Note however, that swapping variables with destructuring assignment causes significant performance loss, as of October 2017.

Use

var myArray = ['1','2','3','4','5','6','7','8','9'];
shuffle(myArray);

Implementing prototype

Using Object.defineProperty (method taken from this SO answer) we can also implement this function as a prototype method for arrays, without having it show up in loops such as for (i in arr). The following will allow you to call arr.shuffle() to shuffle the array arr:

Object.defineProperty(Array.prototype, 'shuffle', {
    value: function() {
        for (let i = this.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [this[i], this[j]] = [this[j], this[i]];
        }
        return this;
    }
});

Check if string is upper, lower, or mixed case in Python

There are a number of "is methods" on strings. islower() and isupper() should meet your needs:

>>> 'hello'.islower()
True

>>> [m for m in dir(str) if m.startswith('is')]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']

Here's an example of how to use those methods to classify a list of strings:

>>> words = ['The', 'quick', 'BROWN', 'Fox', 'jumped', 'OVER', 'the', 'Lazy', 'DOG']
>>> [word for word in words if word.islower()]
['quick', 'jumped', 'the']
>>> [word for word in words if word.isupper()]
['BROWN', 'OVER', 'DOG']
>>> [word for word in words if not word.islower() and not word.isupper()]
['The', 'Fox', 'Lazy']

Convert Array to Object

I would do this simply with Array.of(). Array of has the ability to use it's context as a constructor.

NOTE 2 The of function is an intentionally generic factory method; it does not require that its this value be the Array constructor. Therefore it can be transferred to or inherited by other constructors that may be called with a single numeric argument.

So we may bind Array.of() to a function and generate an array like object.

_x000D_
_x000D_
function dummy(){};_x000D_
var thingy = Array.of.apply(dummy,[1,2,3,4]);_x000D_
console.log(thingy);
_x000D_
_x000D_
_x000D_

By utilizing Array.of() one can even do array sub-classing.

How to bind Events on Ajax loaded Content?

If the content is appended after .on() is called, you'll need to create a delegated event on a parent element of the loaded content. This is because event handlers are bound when .on() is called (i.e. usually on page load). If the element doesn't exist when .on() is called, the event will not be bound to it!

Because events propagate up through the DOM, we can solve this by creating a delegated event on a parent element (.parent-element in the example below) that we know exists when the page loads. Here's how:

$('.parent-element').on('click', '.mylink', function(){
  alert ("new link clicked!");
})

Some more reading on the subject:

PHP move_uploaded_file() error?

$uploadfile = $_SERVER['DOCUMENT_ROOT'].'/Thesis/images/';
$profic = uniqid(rand()).$_FILES["pic"]["name"]; 

if(is_uploaded_file($_FILES["pic"]["tmp_name"]))
{
    $moved = move_uploaded_file($_FILES["pic"]["tmp_name"], $uploadfile.$profic);
    if($moved)
    {
        echo "sucess";
    }
    else
    {
        echo 'failed';
    }
}

data type not understood

Try:

mmatrix = np.zeros((nrows, ncols))

Since the shape parameter has to be an int or sequence of ints

http://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html

Otherwise you are passing ncols to np.zeros as the dtype.

What does `dword ptr` mean?

It is a 32bit declaration. If you type at the top of an assembly file the statement [bits 32], then you don't need to type DWORD PTR. So for example:

[bits 32]
.
.
and  [ebp-4], 0

Latex Multiple Linebreaks

Line break accepts an optional argument in brackets, a vertical length:

line 1
\\[4in]
line 2

To make this more scalable with respect to font size, you can use other lengths, such as \\[3\baselineskip], or \\[3ex].

What does the star operator mean, in a function call?

One small point: these are not operators. Operators are used in expressions to create new values from existing values (1+2 becomes 3, for example. The * and ** here are part of the syntax of function declarations and calls.

Detect if Android device has Internet connection

If all above answers get you FATAL EXCEPTIONs like android.os.NetworkOnMainThreadException, this answer will really help you.
Because I got this error while trying to implement this.

The reason for this error is that the Network related codes cannot be on the main thread.
So, you need to create a new Thread as I shown below:

Thread thread = new Thread(new Runnable() {

@Override
public void run() {
    try  {
        //Your code goes here
    } catch (Exception e) {
        e.printStackTrace();
    }
}});


And put your code in the place I commented.

Creating a chart in Excel that ignores #N/A or blank cells

There is another much less known solution which has merit in some places. Use the #NULL! error which does not plot and does not create a zero point for the plot.

So your plot column is filled with the following construct. Assume real data in column A and that the plotted version is in column C.

=If(Isnumber(A2),A2,A2 A3)

That space is a little known operator to produce the intersection of the two cell addresses or ranges. If there is no intersection then it produces the message #NULL!

Cells containing #NULL! are skipped for plotting purposes.

Aside (For Microsoft) just need to get the maths equations to ignore such cells somehow?

Is it possible to specify condition in Count()?

If you can't just limit the query itself with a where clause, you can use the fact that the count aggregate only counts the non-null values:

select count(case Position when 'Manager' then 1 else null end)
from ...

You can also use the sum aggregate in a similar way:

select sum(case Position when 'Manager' then 1 else 0 end)
from ...

Dialog throwing "Unable to add window — token null is not for an application” with getApplication() as context

If you are using a fragment and using AlertDialog/Toast message then use getActivity() in the context parameter.

like this

ProgressDialog pdialog;
pdialog = new ProgressDialog(getActivity());
pdialog.setCancelable(true);
pdialog.setMessage("Loading ....");
pdialog.show();

Get Android .apk file VersionName or VersionCode WITHOUT installing apk

Kotlin:

var ver: String = packageManager.getPackageInfo(packageName, 0).versionName

Python OpenCV2 (cv2) wrapper to get image size?

I'm afraid there is no "better" way to get this size, however it's not that much pain.

Of course your code should be safe for both binary/mono images as well as multi-channel ones, but the principal dimensions of the image always come first in the numpy array's shape. If you opt for readability, or don't want to bother typing this, you can wrap it up in a function, and give it a name you like, e.g. cv_size:

import numpy as np
import cv2

# ...

def cv_size(img):
    return tuple(img.shape[1::-1])

If you're on a terminal / ipython, you can also express it with a lambda:

>>> cv_size = lambda img: tuple(img.shape[1::-1])
>>> cv_size(img)
(640, 480)

Writing functions with def is not fun while working interactively.

Edit

Originally I thought that using [:2] was OK, but the numpy shape is (height, width[, depth]), and we need (width, height), as e.g. cv2.resize expects, so - we must use [1::-1]. Even less memorable than [:2]. And who remembers reverse slicing anyway?

Why can't I define my workbook as an object?

It's actually a sensible question. Here's the answer from Excel 2010 help:

"The Workbook object is a member of the Workbooks collection. The Workbooks collection contains all the Workbook objects currently open in Microsoft Excel."

So, since that workbook isn't open - at least I assume it isn't - it can't be set as a workbook object. If it was open you'd just set it like:

Set wbk = workbooks("Master Benchmark Data Sheet.xlsx")

How do I make an image smaller with CSS?

CSS 3 introduces the background-size property, but support is not universal.

Having the browser resize the image is inefficient though, the large image still has to be downloaded. You should resize it server side (caching the result) and use that instead. It will use less bandwidth and work in more browsers.

How can I shrink the drawable on a button?

You can call setBounds on the "compound" drawables to modify the size of the image.

Try this code to autosize the drawable of your button:

DroidUtils.scaleButtonDrawables((Button) findViewById(R.id.ButtonTest), 1.0);

defined by this function:

public final class DroidUtils {

    /** scale the Drawables of a button to "fit"
     *  For left and right drawables: height is scaled 
     *  eg. with fitFactor 1 the image has max. the height of the button.
     *  For top and bottom drawables: width is scaled: 
     *  With fitFactor 0.9 the image has max. 90% of the width of the button 
     *  */
    public static void scaleButtonDrawables(Button btn, double fitFactor) {
        Drawable[] drawables = btn.getCompoundDrawables();

        for (int i = 0; i < drawables.length; i++) {
            if (drawables[i] != null) {
                int imgWidth = drawables[i].getIntrinsicWidth();
                int imgHeight = drawables[i].getIntrinsicHeight();
                if ((imgHeight > 0) && (imgWidth > 0)) {    //might be -1
                    float scale;
                    if ((i == 0) || (i == 2)) { //left or right -> scale height
                        scale = (float) (btn.getHeight() * fitFactor) / imgHeight;
                    } else { //top or bottom -> scale width
                        scale = (float) (btn.getWidth() * fitFactor) / imgWidth;                    
                    }
                    if (scale < 1.0) {
                        Rect rect = drawables[i].getBounds();
                        int newWidth = (int)(imgWidth * scale);
                        int newHeight = (int)(imgHeight * scale);
                        rect.left = rect.left + (int)(0.5 * (imgWidth - newWidth)); 
                        rect.top = rect.top + (int)(0.5 * (imgHeight - newHeight));
                        rect.right = rect.left + newWidth;
                        rect.bottom = rect.top + newHeight;
                        drawables[i].setBounds(rect);
                    }
                }
            }
        }
    }
}

Be aware, that this may not be called in onCreate() of an activity, because button height and width are not (yet) available there. Call this in on onWindowFocusChanged() or use this solution to call the function.

Edited:

The first incarnation of this function did not work correctly. It used userSeven7s code to scale the image, but returning ScaleDrawable.getDrawable() does not seem to work (neither does returning ScaleDrawable) for me.

The modified code uses setBounds to provide the bounds for the image. Android fits the image into these bounds.

How do I connect to a specific Wi-Fi network in Android programmatically?

You need to create WifiConfiguration instance like this:

String networkSSID = "test";
String networkPass = "pass";

WifiConfiguration conf = new WifiConfiguration();
conf.SSID = "\"" + networkSSID + "\"";   // Please note the quotes. String should contain ssid in quotes

Then, for WEP network you need to do this:

conf.wepKeys[0] = "\"" + networkPass + "\""; 
conf.wepTxKeyIndex = 0;
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); 

For WPA network you need to add passphrase like this:

conf.preSharedKey = "\""+ networkPass +"\"";

For Open network you need to do this:

conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);

Then, you need to add it to Android wifi manager settings:

WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE); 
wifiManager.addNetwork(conf);

And finally, you might need to enable it, so Android connects to it:

List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
for( WifiConfiguration i : list ) {
    if(i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
         wifiManager.disconnect();
         wifiManager.enableNetwork(i.networkId, true);
         wifiManager.reconnect();               

         break;
    }           
 }

UPD: In case of WEP, if your password is in hex, you do not need to surround it with quotes.

Get a list of all git commits, including the 'lost' ones

What saved my life was the following command:

git reflog

There you find a screen with history commits done to git like this one:

enter image description here

At this point, you only have to find the HEAD@{X} that you need, create a temporary branch and move to it like this:

git checkout -b temp_branch HEAD@{X}

That way you will have a temporary branch with your lost commit without rebasing or breaking even more your git repository.

Hope this helps...

Bash script error [: !=: unary operator expected

Or for what seems like rampant overkill, but is actually simplistic ... Pretty much covers all of your cases, and no empty string or unary concerns.

In the case the first arg is '-v', then do your conditional ps -ef, else in all other cases throw the usage.

#!/bin/sh
case $1 in
  '-v') if [ "$1" = -v ]; then
         echo "`ps -ef | grep -v '\['`"
        else
         echo "`ps -ef | grep '\[' | grep root`"
        fi;;
     *) echo "usage: $0 [-v]"
        exit 1;; #It is good practice to throw a code, hence allowing $? check
esac

If one cares not where the '-v' arg is, then simply drop the case inside a loop. The would allow walking all the args and finding '-v' anywhere (provided it exists). This means command line argument order is not important. Be forewarned, as presented, the variable arg_match is set, thus it is merely a flag. It allows for multiple occurrences of the '-v' arg. One could ignore all other occurrences of '-v' easy enough.

#!/bin/sh

usage ()
 {
  echo "usage: $0 [-v]"
  exit 1
 }

unset arg_match

for arg in $*
 do
  case $arg in
    '-v') if [ "$arg" = -v ]; then
           echo "`ps -ef | grep -v '\['`"
          else
           echo "`ps -ef | grep '\[' | grep root`"
          fi
          arg_match=1;; # this is set, but could increment.
       *) ;;
  esac
done

if [ ! $arg_match ]
 then
  usage
fi

But, allow multiple occurrences of an argument is convenient to use in situations such as:

$ adduser -u:sam -s -f -u:bob -trace -verbose

We care not about the order of the arguments, and even allow multiple -u arguments. Yes, it is a simple matter to also allow:

$ adduser -u sam -s -f -u bob -trace -verbose

Does Ruby have a string.startswith("abc") built in method?

If this is for a non-Rails project, I'd use String#index:

"foobar".index("foo") == 0  # => true

How to set JAVA_HOME in Linux for all users

The answer is given previous posts is valid. But not one answer is complete with respect to:

  1. Changing the /etc/profile is not recommended simply because of the reason (as stated in /etc/profile):
  • It's NOT a good idea to change this file unless you know what you are doing. It's much better to create a custom.sh shell script in /etc/profile.d/ to make custom changes to your environment, as this will prevent the need for merging in future updates.*
  1. So as stated above create /etc/profile.d/custom.sh file for custom changes.

  2. Now, to always keep updated with newer versions of Java being installed, never put the absolute path, instead use:

#if making jdk as java home

export JAVA_HOME=$(readlink -f /usr/bin/javac | sed "s:/bin/javac::")

OR

#if making jre as java home

export JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:/bin/java::")

  1. And remember to have #! /bin/bash on the custom.sh file

Read int values from a text file in C

A simple solution using fscanf:

void read_ints (const char* file_name)
{
  FILE* file = fopen (file_name, "r");
  int i = 0;

  fscanf (file, "%d", &i);    
  while (!feof (file))
    {  
      printf ("%d ", i);
      fscanf (file, "%d", &i);      
    }
  fclose (file);        
}

How to change checkbox's border style in CSS?

Here is a pure CSS (no images) cross-browser solution based on Martin's Custom Checkboxes and Radio Buttons with CSS3 LINK: http://martinivanov.net/2012/12/21/imageless-custom-checkboxes-and-radio-buttons-with-css3-revisited/

Here is a jsFiddle: http://jsfiddle.net/DJRavine/od26wL6n/

I have tested this on the following browsers:

  • FireFox (41.0.2) (42)
  • Google Chrome (46.0.2490.80 m)
  • Opera (33.0.1990.43)
  • Internet Explorer (11.0.10240.16431 [Update Versions: 11.0.22])
  • Microsoft Edge (20.10240.16384.0)
  • Safari Mobile iPhone iOS9 (601.1.46)

_x000D_
_x000D_
label,_x000D_
input[type="radio"] + span,_x000D_
input[type="radio"] + span::before,_x000D_
label,_x000D_
input[type="checkbox"] + span,_x000D_
input[type="checkbox"] + span::before_x000D_
{_x000D_
    display: inline-block;_x000D_
    vertical-align: middle;_x000D_
}_x000D_
 _x000D_
label *,_x000D_
label *_x000D_
{_x000D_
    cursor: pointer;_x000D_
}_x000D_
 _x000D_
input[type="radio"],_x000D_
input[type="checkbox"]_x000D_
{_x000D_
    opacity: 0;_x000D_
    position: absolute;_x000D_
}_x000D_
 _x000D_
input[type="radio"] + span,_x000D_
input[type="checkbox"] + span_x000D_
{_x000D_
    font: normal 11px/14px Arial, Sans-serif;_x000D_
    color: #333;_x000D_
}_x000D_
 _x000D_
label:hover span::before,_x000D_
label:hover span::before_x000D_
{_x000D_
    -moz-box-shadow: 0 0 2px #ccc;_x000D_
    -webkit-box-shadow: 0 0 2px #ccc;_x000D_
    box-shadow: 0 0 2px #ccc;_x000D_
}_x000D_
 _x000D_
label:hover span,_x000D_
label:hover span_x000D_
{_x000D_
    color: #000;_x000D_
}_x000D_
 _x000D_
input[type="radio"] + span::before,_x000D_
input[type="checkbox"] + span::before_x000D_
{_x000D_
    content: "";_x000D_
    width: 12px;_x000D_
    height: 12px;_x000D_
    margin: 0 4px 0 0;_x000D_
    border: solid 1px #a8a8a8;_x000D_
    line-height: 14px;_x000D_
    text-align: center;_x000D_
     _x000D_
    -moz-border-radius: 100%;_x000D_
    -webkit-border-radius: 100%;_x000D_
    border-radius: 100%;_x000D_
     _x000D_
    background: #f6f6f6;_x000D_
    background: -moz-radial-gradient(#f6f6f6, #dfdfdf);_x000D_
    background: -webkit-radial-gradient(#f6f6f6, #dfdfdf);_x000D_
    background: -ms-radial-gradient(#f6f6f6, #dfdfdf);_x000D_
    background: -o-radial-gradient(#f6f6f6, #dfdfdf);_x000D_
    background: radial-gradient(#f6f6f6, #dfdfdf);_x000D_
}_x000D_
 _x000D_
input[type="radio"]:checked + span::before,_x000D_
input[type="checkbox"]:checked + span::before_x000D_
{_x000D_
    color: #666;_x000D_
}_x000D_
 _x000D_
input[type="radio"]:disabled + span,_x000D_
input[type="checkbox"]:disabled + span_x000D_
{_x000D_
    cursor: default;_x000D_
     _x000D_
    -moz-opacity: .4;_x000D_
    -webkit-opacity: .4;_x000D_
    opacity: .4;_x000D_
}_x000D_
 _x000D_
input[type="checkbox"] + span::before_x000D_
{_x000D_
    -moz-border-radius: 2px;_x000D_
    -webkit-border-radius: 2px;_x000D_
    border-radius: 2px;_x000D_
}_x000D_
 _x000D_
input[type="radio"]:checked + span::before_x000D_
{_x000D_
    content: "\2022";_x000D_
    font-size: 30px;_x000D_
    margin-top: -1px;_x000D_
}_x000D_
 _x000D_
input[type="checkbox"]:checked + span::before_x000D_
{_x000D_
    content: "\2714";_x000D_
    font-size: 12px;_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
input[class="blue"] + span::before_x000D_
{_x000D_
    border: solid 1px blue;_x000D_
    background: #B2DBFF;_x000D_
    background: -moz-radial-gradient(#B2DBFF, #dfdfdf);_x000D_
    background: -webkit-radial-gradient(#B2DBFF, #dfdfdf);_x000D_
    background: -ms-radial-gradient(#B2DBFF, #dfdfdf);_x000D_
    background: -o-radial-gradient(#B2DBFF, #dfdfdf);_x000D_
    background: radial-gradient(#B2DBFF, #dfdfdf);_x000D_
}_x000D_
input[class="blue"]:checked + span::before_x000D_
{_x000D_
    color: darkblue;_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
input[class="red"] + span::before_x000D_
{_x000D_
    border: solid 1px red;_x000D_
    background: #FF9593;_x000D_
    background: -moz-radial-gradient(#FF9593, #dfdfdf);_x000D_
    background: -webkit-radial-gradient(#FF9593, #dfdfdf);_x000D_
    background: -ms-radial-gradient(#FF9593, #dfdfdf);_x000D_
    background: -o-radial-gradient(#FF9593, #dfdfdf);_x000D_
    background: radial-gradient(#FF9593, #dfdfdf);_x000D_
}_x000D_
input[class="red"]:checked + span::before_x000D_
{_x000D_
    color: darkred;_x000D_
}
_x000D_
 <label><input type="radio" checked="checked" name="radios-01" /><span>checked radio button</span></label>_x000D_
 <label><input type="radio" name="radios-01" /><span>unchecked radio button</span></label>_x000D_
 <label><input type="radio" name="radios-01" disabled="disabled" /><span>disabled radio button</span></label>_x000D_
_x000D_
<br/>_x000D_
_x000D_
 <label><input type="radio" checked="checked" name="radios-02"  class="blue" /><span>checked radio button</span></label>_x000D_
 <label><input type="radio" name="radios-02" class="blue" /><span>unchecked radio button</span></label>_x000D_
 <label><input type="radio" name="radios-02" disabled="disabled" class="blue" /><span>disabled radio button</span></label>_x000D_
_x000D_
<br/>_x000D_
_x000D_
 <label><input type="radio" checked="checked" name="radios-03"  class="red" /><span>checked radio button</span></label>_x000D_
 <label><input type="radio" name="radios-03" class="red" /><span>unchecked radio button</span></label>_x000D_
 <label><input type="radio" name="radios-03" disabled="disabled" class="red" /><span>disabled radio button</span></label>_x000D_
_x000D_
<br/>_x000D_
 _x000D_
<label><input type="checkbox" checked="checked" name="checkbox-01" /><span>selected checkbox</span></label>_x000D_
<label><input type="checkbox" name="checkbox-02" /><span>unselected checkbox</span></label>_x000D_
<label><input type="checkbox" name="checkbox-03" disabled="disabled" /><span>disabled checkbox</span></label>_x000D_
_x000D_
<br/>_x000D_
 _x000D_
<label><input type="checkbox" checked="checked" name="checkbox-01" class="blue" /><span>selected checkbox</span></label>_x000D_
<label><input type="checkbox" name="checkbox-02" class="blue" /><span>unselected checkbox</span></label>_x000D_
<label><input type="checkbox" name="checkbox-03" disabled="disabled" class="blue" /><span>disabled checkbox</span></label>_x000D_
_x000D_
<br/>_x000D_
 _x000D_
<label><input type="checkbox" checked="checked" name="checkbox-01" class="red" /><span>selected checkbox</span></label>_x000D_
<label><input type="checkbox" name="checkbox-02" class="red" /><span>unselected checkbox</span></label>_x000D_
<label><input type="checkbox" name="checkbox-03" disabled="disabled" class="red" /><span>disabled checkbox</span></label>
_x000D_
_x000D_
_x000D_

Update query with PDO and MySQL

  1. Your UPDATE syntax is wrong
  2. You probably meant to update a row not all of them so you have to use WHERE clause to target your specific row

Change

UPDATE `access_users`   
      (`contact_first_name`,`contact_surname`,`contact_email`,`telephone`) 
      VALUES (:firstname, :surname, :telephone, :email)

to

UPDATE `access_users`   
   SET `contact_first_name` = :firstname,
       `contact_surname` = :surname,
       `contact_email` = :email,
       `telephone` = :telephone 
 WHERE `user_id` = :user_id -- you probably have some sort of id 

What is the best way to implement "remember me" for a website?

I would store a user ID and a token. When the user comes back to the site, compare those two pieces of information against something persistent like a database entry.

As for security, just don't put anything in there that will allow someone to modify the cookie to gain extra benefits. For example, don't store their user groups or their password. Anything that can be modified that would circumvent your security should not be stored in the cookie.

How do I split a string, breaking at a particular character?

Since the splitting on commas question is duplicated to this question, adding this here.

If you want to split on a character and also handle extra whitespace that might follow that character, which often happens with commas, you can use replace then split, like this:

var items = string.replace(/,\s+/, ",").split(',')

How to make my font bold using css?

Sine you are new to html here are three ready to use examples on how to use CSS together with html. You can simply put them into a file, save it and open it up with the browser of your choice:

This one directly embeds your CSS style into your tags/elements. Generally this is not a very nice approach, because you should always separate the content/html from design.

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="de">     
    <head>      
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />   
        <title>Hi, I'm bold!</title>  
    </head>           
    <body>
        <p style="font-weight:bold;">Hi, I'm very bold!</p>
    </body>
</html> 

The next one is a more general approach and works on all "p" (stands for paragraph) tags in your document and additionaly makes them HUGE. Btw. Google uses this approach on his search:

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="de">     
    <head>      
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />   
        <title>Hi, I'm bold!</title>  
        <style type="text/css">
            p {
              font-weight:bold;
              font-size:26px;
            }
        </style>
    </head>   
    <body>
        <p>Hi, I'm very bold and HUGE!</p>
    </body>
</html>  

You probably will take a couple of days playing around with the first examples, however here is the last one. In this you finally fully seperate design (css) and content (html) from each other in two different files. stackoverflow takes this approach.

In one file you put all the CSS (call it 'hello_world.css'):

  p {
    font-weight:bold;
    font-size:26px;
  }

In another file you should put the html (call it 'hello_world.html'):

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="de">     
    <head>      
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />   
        <title>Hi, I'm bold!</title>  
        <link rel="stylesheet" type="text/css" href="hello_world.css" />  
    </head>       
    <body>
        <p>Hi, I'm very bold and HUGE!</p>
    </body>
</html> 

Hope this helps a little. To address specific elements in your document and not all tags you should make yourself familiar with the class, id and name attributes. Have fun!

Combine two tables for one output

In your expected output, you've got the second last row sum incorrect, it should be 40 according to the data in your tables, but here is the query:

Select  ChargeNum, CategoryId, Sum(Hours)
From    (
    Select  ChargeNum, CategoryId, Hours
    From    KnownHours
    Union
    Select  ChargeNum, 'Unknown' As CategoryId, Hours
    From    UnknownHours
) As a
Group By ChargeNum, CategoryId
Order By ChargeNum, CategoryId

And here is the output:

ChargeNum  CategoryId 
---------- ---------- ----------------------
111111     1          40
111111     2          50
111111     Unknown    70
222222     1          40
222222     Unknown    25.5

java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener

I had a similar problem when running a spring web application in an Eclipse managed tomcat. I solved this problem by adding maven dependencies in the project's web deployment assembly.

  1. Open the project's properties (e.g., right-click on the project's name in the project explorer and select "Properties").
  2. Select "Deployment Assembly".
  3. Click the "Add..." button on the right margin.
  4. Select "Java Build Path Entries" from the menu of Directive Type and click "Next".
  5. Select "Maven Dependencies" from the Java Build Path Entries menu and click "Finish".

You should see "Maven Dependencies" added to the Web Deployment Assembly definition.

Android Studio and android.support.v4.app.Fragment: cannot resolve symbol

I got the same problem since I updated to latest version of Android Studio 0.3.7. So you can try with my stuffs.

Ensure you have updated to latest version Android Support Repository - 3 Android Support Library - 19

As your attachment picture above, you did it already. Then adding the following setting to your build.gradle

dependencies {
    compile 'com.android.support:support-v4:19.0.0'
}

One more thing: Please make sure your Android SDK is targeting to right SDK folder

Trying to use INNER JOIN and GROUP BY SQL with SUM Function, Not Working

Use subquery

SELECT * FROM RES_DATA inner join (SELECT [CUSTOMER ID], sum([TOTAL AMOUNT]) FROM INV_DATA group by [CUSTOMER ID]) T on RES_DATA.[CUSTOMER ID] = t.[CUSTOMER ID]

Is it ok to use `any?` to check if an array is not empty?

any? isn't the same as not empty? in some cases.

>> [nil, 1].any?
=> true
>> [nil, nil].any?
=> false

From the documentation:

If the block is not given, Ruby adds an implicit block of {|obj| obj} (that is any? will return true if at least one of the collection members is not false or nil).

How can I find the number of days between two Date objects in Ruby?

In Ruby 2.1.3 things have changed:

> endDate = Date.new(2014, 1, 2)
 => #<Date: 2014-01-02 ((2456660j,0s,0n),+0s,2299161j)> 
> beginDate = Date.new(2014, 1, 1)
 => #<Date: 2014-01-01 ((2456659j,0s,0n),+0s,2299161j)> 
> days = endDate - beginDate
 => (1/1) 
> days.class
 => Rational 
> days.to_i
 => 1 

Get value of a merged cell of an excel from its cell address in vba

Even if it is really discouraged to use merge cells in Excel (use Center Across Selection for instance if needed), the cell that "contains" the value is the one on the top left (at least, that's a way to express it).

Hence, you can get the value of merged cells in range B4:B11 in several ways:

  • Range("B4").Value
  • Range("B4:B11").Cells(1).Value
  • Range("B4:B11").Cells(1,1).Value

You can also note that all the other cells have no value in them. While debugging, you can see that the value is empty.

Also note that Range("B4:B11").Value won't work (raises an execution error number 13 if you try to Debug.Print it) because it returns an array.

Programmatically stop execution of python script?

You want sys.exit(). From Python's docs:

>>> import sys
>>> print sys.exit.__doc__
exit([status])

Exit the interpreter by raising SystemExit(status).
If the status is omitted or None, it defaults to zero (i.e., success).
If the status is numeric, it will be used as the system exit status.
If it is another kind of object, it will be printed and the system
exit status will be one (i.e., failure).

So, basically, you'll do something like this:

from sys import exit

# Code!

exit(0) # Successful exit

Save Screen (program) output to a file

The selected answer doesn't work quite well with multiple sessions and doesn't allow to specify a custom log file name.

For multiple screen sessions, this is my formula:

  1. Create a configuration file for each process:

    logfile test.log
    logfile flush 1
    log on
    logtstamp after 1
    logtstamp string "[ %t: %Y-%m-%d %c:%s ]\012"
    logtstamp on
    

    If you want to do it "on the fly", you can change logfile automatically. \012 means "new line", as using \n will print it on the log file: source.

  2. Start your command with the "-c" and "-L" flags:

    screen -c ./test.conf -dmSL 'Test' ./test.pl
    

    That's it. You will see "test.log" after the first flush:

    ...
    6 Something is happening...
    [ test.pl: 2016-06-01 13:02:53 ]
    7 Something else...
    [ test.pl: 2016-06-01 13:02:54 ]
    8 Nothing here
    [ test.pl: 2016-06-01 13:02:55 ]
    9 Something is happening...
    [ test.pl: 2016-06-01 13:02:56 ]
    10 Something else...
    [ test.pl: 2016-06-01 13:02:57 ]
    11 Nothing here
    [ test.pl: 2016-06-01 13:02:58 ]
    ...
    

I found that "-L" is still required even when "log on" is on the configuration file.

I couldn't find a list of the time format variables (like %m) used by screen. If you have a link of those formats, please post it bellow.

Extra

In case you want to do it "on the fly", you can use this script:

#!/bin/bash
if [[ $2 == "" ]]; then
    echo "Usage: $0 name command";
    exit 1;
fi
name=$1
command=$2
path="/var/log";
config="logfile ${path}/${name}.log
logfile flush 1
log on
logtstamp after 1
logtstamp string \"[ %t: %Y-%m-%d %c:%s ]\012\"
logtstamp on";
echo "$config" > /tmp/log.conf
screen -c /tmp/log.conf -dmSL "$name" $command
rm /tmp/log.conf

To use it, save it (screen.sh) and set +x permissions:

./screen.sh TEST ./test.pl

... and will execute ./test.pl and create a log file in /var/log/TEST.log

GitHub - failed to connect to github 443 windows/ Failed to connect to gitHub - No Error

Well I did following steps

  1. Google the error

  2. Got to SO Links(here, here) which suggested the same thing, that I have to update the Git Config for proxy setting

  3. Damn, can not see proxy information from control panel. IT guys must have hidden it. I can not even change the setting to not to use proxy.

  4. Found this wonderful tutorial of finding which proxy your are connected to

  5. Updated the http.proxy key in git config by following command

git config --global http.proxy http[s]://userName:password@proxyaddress:port

  1. Error - could not resolve proxy some@proxyaddress:port. It turned out my password had @ symbol in it.

  2. Encode @ in your password to %40, because git splits the proxy setting by @

  3. If your userName is a email address, which has @, also encode it to %40. (see this answer)

git config --global http.proxy http[s]://userName(encoded):password(encoded)@proxyaddress:port

Baam ! It worked !

Note - I just wanted to answer this question for souls like me, who would come looking for answer on SO :D

Converting HTML element to string in JavaScript / JQuery

Try a slight different approach:

//set string and append it as object
var myHtmlString = '<iframe id="myFrame" width="854" height="480" src="http://www.youtube.com/embed/gYKqrjq5IjU?feature=oembed" frameborder="0" allowfullscreen></iframe>';
$('body').append(myHtmlString);

//as you noticed you can't just get it back
var myHtmlStringBack = $('#myFrame').html(); 
alert(myHtmlStringBack); // will be empty (a bug in jquery?) but...

//since an id was added to your iframe so you can retrieve its attributes back...
var width = $('#myFrame').attr('width');
var height = $('#myFrame').attr('height');
var src = $('#myFrame').attr('src');
var myReconstructedString = '<iframe id="myFrame" width="'+ width +'" height="'+ height +'" src="'+ src+'" frameborder="0" allowfullscreen></iframe>';
alert(myReconstructedString);

How do I call a dynamically-named method in Javascript?

A simple function to call a function dynamically with parameters:

this.callFunction = this.call_function = function(name) {
    var args = Array.prototype.slice.call(arguments, 1);
    return window[name].call(this, ...args);
};

function sayHello(name, age) {
    console.log('hello ' + name + ', your\'e age is ' + age);
    return some;
}

console.log(call_function('sayHello', 'john', 30)); // hello john, your'e age is 30

Multiple INNER JOIN SQL ACCESS

Thanks HansUp for your answer, it is very helpful and it works!

I found three patterns working in Access, yours is the best, because it works in all cases.

  • INNER JOIN, your variant. I will call it "closed set pattern". It is possible to join more than two tables to the same table with good performance only with this pattern.

    SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
    FROM
         ((class
           INNER JOIN person AS cr 
           ON class.C_P_ClassRep=cr.P_Nr
         )
         INNER JOIN person AS cr2
         ON class.C_P_ClassRep2nd=cr2.P_Nr
      )
    

    ;

  • INNER JOIN "chained-set pattern"

    SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
    FROM person AS cr
    INNER JOIN ( class 
       INNER JOIN ( person AS cr2
       ) ON class.C_P_ClassRep2nd=cr2.P_Nr
    ) ON class.C_P_ClassRep=cr.P_Nr
    ;
    
  • CROSS JOIN with WHERE

    SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
    FROM class, person AS cr, person AS cr2
    WHERE class.C_P_ClassRep=cr.P_Nr AND class.C_P_ClassRep2nd=cr2.P_Nr
    ;
    

Android Studio - ADB Error - "...device unauthorized. Please check the confirmation dialog on your device."

Remove the Debug permissions on the Device, with the cell phone connected, then put them back, and ask if you want to allow the PC to have debug, accept and ready permissions: D

FlutterError: Unable to load asset

if you're developing flutter packages, please add package param after image path like this:

AssetImage('images/heart.png', package: 'my_icons') // my_icons is your plugin name, in flutter plugin is also a package.

Here is the link from flutter docs https://flutter.dev/assets-and-images/#from-packages

How to use data-binding with Fragment

The data binding implementation must be in the onCreateView method of the fragment, delete any data Binding that exist in your OnCreate method, your onCreateView should look like this:

public View onCreateView(LayoutInflater inflater, 
                         @Nullable ViewGroup container, 
                         @Nullable Bundle savedInstanceState) {
    MartianDataBinding binding = DataBindingUtil.inflate(
            inflater, R.layout.martian_data, container, false);
    View view = binding.getRoot();
    //here data must be an instance of the class MarsDataProvider
    binding.setMarsdata(data);
    return view;
}

How do I print the content of httprequest request?

More details that help in logging

    String client = request.getRemoteAddr();
    logger.info("###### requested client: {} , Session ID : {} , URI :" + request.getMethod() + ":" + request.getRequestURI() + "", client, request.getSession().getId());

    Map params = request.getParameterMap();
    Iterator i = params.keySet().iterator();
    while (i.hasNext()) {
        String key = (String) i.next();
        String value = ((String[]) params.get(key))[0];
        logger.info("###### Request Param Name : {} , Value :  {} ", key, value);
    }

Using LIMIT within GROUP BY to get N results per group?

The following post: sql: selcting top N record per group describes the complicated way of achieving this without subqueries.

It improves on other solutions offered here by:

  • Doing everything in a single query
  • Being able to properly utilize indexes
  • Avoiding subqueries, notoriously known to produce bad execution plans in MySQL

It is however not pretty. A good solution would be achievable were Window Functions (aka Analytic Functions) enabled in MySQL -- but they are not. The trick used in said post utilizes GROUP_CONCAT, which is sometimes described as "poor man's Window Functions for MySQL".

Simple Random Samples from a Sql database

There's a very interesting discussion of this type of issue here: http://www.titov.net/2005/09/21/do-not-use-order-by-rand-or-how-to-get-random-rows-from-table/

I think with absolutely no assumptions about the table that your O(n lg n) solution is the best. Though actually with a good optimizer or a slightly different technique the query you list may be a bit better, O(m*n) where m is the number of random rows desired, as it wouldn't necesssarily have to sort the whole large array, it could just search for the smallest m times. But for the sort of numbers you posted, m is bigger than lg n anyway.

Three asumptions we might try out:

  1. there is a unique, indexed, primary key in the table

  2. the number of random rows you want to select (m) is much smaller than the number of rows in the table (n)

  3. the unique primary key is an integer that ranges from 1 to n with no gaps

With only assumptions 1 and 2 I think this can be done in O(n), though you'll need to write a whole index to the table to match assumption 3, so it's not necesarily a fast O(n). If we can ADDITIONALLY assume something else nice about the table, we can do the task in O(m log m). Assumption 3 would be an easy nice additional property to work with. With a nice random number generator that guaranteed no duplicates when generating m numbers in a row, an O(m) solution would be possible.

Given the three assumptions, the basic idea is to generate m unique random numbers between 1 and n, and then select the rows with those keys from the table. I don't have mysql or anything in front of me right now, so in slightly pseudocode this would look something like:


create table RandomKeys (RandomKey int)
create table RandomKeysAttempt (RandomKey int)

-- generate m random keys between 1 and n
for i = 1 to m
  insert RandomKeysAttempt select rand()*n + 1

-- eliminate duplicates
insert RandomKeys select distinct RandomKey from RandomKeysAttempt

-- as long as we don't have enough, keep generating new keys,
-- with luck (and m much less than n), this won't be necessary
while count(RandomKeys) < m
  NextAttempt = rand()*n + 1
  if not exists (select * from RandomKeys where RandomKey = NextAttempt)
    insert RandomKeys select NextAttempt

-- get our random rows
select *
from RandomKeys r
join table t ON r.RandomKey = t.UniqueKey

If you were really concerned about efficiency, you might consider doing the random key generation in some sort of procedural language and inserting the results in the database, as almost anything other than SQL would probably be better at the sort of looping and random number generation required.

How to remove numbers from a string?

Just want to add since it might be of interest to someone, that you may think about the problem the other way as well. I am not sure if that is of interest here, but I find it relevant.

What I mean by the other way is to say "strip anything that aren't what I am looking for, i.e. if you only want the 'ding' you could say:

var strippedText = ("1 ding ?").replace(/[^a-zA-Z]/g, '');

Which basically mean "remove anything which is nog a,b,c,d....Z (any letter).

Tkinter: How to use threads to preventing main event loop from "freezing"

When you join the new thread in the main thread, it will wait until the thread finishes, so the GUI will block even though you are using multithreading.

If you want to place the logic portion in a different class, you can subclass Thread directly, and then start a new object of this class when you press the button. The constructor of this subclass of Thread can receive a Queue object and then you will be able to communicate it with the GUI part. So my suggestion is:

  1. Create a Queue object in the main thread
  2. Create a new thread with access to that queue
  3. Check periodically the queue in the main thread

Then you have to solve the problem of what happens if the user clicks two times the same button (it will spawn a new thread with each click), but you can fix it by disabling the start button and enabling it again after you call self.prog_bar.stop().

import Queue

class GUI:
    # ...

    def tb_click(self):
        self.progress()
        self.prog_bar.start()
        self.queue = Queue.Queue()
        ThreadedTask(self.queue).start()
        self.master.after(100, self.process_queue)

    def process_queue(self):
        try:
            msg = self.queue.get(0)
            # Show result of the task if needed
            self.prog_bar.stop()
        except Queue.Empty:
            self.master.after(100, self.process_queue)

class ThreadedTask(threading.Thread):
    def __init__(self, queue):
        threading.Thread.__init__(self)
        self.queue = queue
    def run(self):
        time.sleep(5)  # Simulate long running process
        self.queue.put("Task finished")

count (non-blank) lines-of-code in bash

It's kinda going to depend on the number of files you have in the project. In theory you could use

grep -c '.' <list of files>

Where you can fill the list of files by using the find utility.

grep -c '.' `find -type f`

Would give you a line count per file.

Why do you create a View in a database?

I only have 10 or so views in my production databases. I use several for columns I use all the time. One set I use come from 7 tables, some with outer joins and rather than rewrite that constantly I only have to call that view in a select and make one or 2 joins. To me it is just a time saver.

How to use color picker (eye dropper)?

Currently, the eyedropper tool is not working in my version of Chrome (as described above), though it worked for me in the past. I hear it is being updated in the latest version of Chrome.

However, I'm able to grab colors easily in Firefox.

  1. Open page in Firefox
  2. Hamburger Menu -> Web Developer -> Eyedropper
  3. Drag eyedropper tool over the image... Click.
    Color is copied to your clipboard, and eyedropper tool goes away.
  4. Paste color code

In case you cannot get the eyedropper tool to work in Chrome, this is a good work around.
I also find it easier to access :-)

append multiple values for one key in a dictionary

You can use setdefault.

for line in list:  
    d.setdefault(year, []).append(value)

This works because setdefault returns the list as well as setting it on the dictionary, and because a list is mutable, appending to the version returned by setdefault is the same as appending it to the version inside the dictionary itself. If that makes any sense.

What is the difference between .yaml and .yml extension?

File extensions do not have any bearing or impact on the content of the file. You can hold YAML content in files with any extension: .yml, .yaml or indeed anything else.

The (rather sparse) YAML FAQ recommends that you use .yaml in preference to .yml, but for historic reasons many Windows programmers are still scared of using extensions with more than three characters and so opt to use .yml instead.

So, what really matters is what is inside the file, rather than what its extension is.

How do I create a new class in IntelliJ without using the mouse?

If you are already in the Project View, press Alt+Insert (New) | Class. Project View can be activated via Alt+1.

To create a new class in the same directory as the current one use Ctrl+Alt+Insert (New...).

You can also do it from the Navigation Bar, press Alt+Home, then choose package with arrow keys, then press Alt+Insert.

Another useful shortcut is View | Select In (Alt+F1), Project (1), then Alt+Insert to create a class near the existing one or use arrow keys to navigate through the packages.

And yet another way is to just type the class name in the existing code where you want to use it, IDEA will highlight it in red as it doesn't exist yet, then press Alt+Enter for the Intention Actions pop-up, choose Create Class.

How to add "class" to host element?

Günter's answer is great (question is asking for dynamic class attribute) but I thought I would add just for completeness...

If you're looking for a quick and clean way to add one or more static classes to the host element of your component (i.e., for theme-styling purposes) you can just do:

@Component({
   selector: 'my-component',
   template: 'app-element',
   host: {'class': 'someClass1'}
})
export class App implements OnInit {
...
}

And if you use a class on the entry tag, Angular will merge the classes, i.e.,

<my-component class="someClass2">
  I have both someClass1 & someClass2 applied to me
</my-component>

How to extract a single value from JSON response?

Only suggestion is to access your resp_dict via .get() for a more graceful approach that will degrade well if the data isn't as expected.

resp_dict = json.loads(resp_str)
resp_dict.get('name') # will return None if 'name' doesn't exist

You could also add some logic to test for the key if you want as well.

if 'name' in resp_dict:
    resp_dict['name']
else:
    # do something else here.

How to read numbers separated by space using scanf

scanf uses any whitespace as a delimiter, so if you just say scanf("%d", &var) it will skip any whitespace and then read an integer (digits up to the next non-digit) and nothing more.

Note that whitespace is any whitespace -- spaces, tabs, newlines, or carriage returns. Any of those are whitespace and any one or more of them will serve to delimit successive integers.

Programmatically create a UIView with color gradient

In Swift 3.1 I have added this extension to UIView

import Foundation
import UIKit
import CoreGraphics


extension UIView {
    func gradientOfView(withColours: UIColor...) {

        var cgColours = [CGColor]()

        for colour in withColours {
            cgColours.append(colour.cgColor)
        }
        let grad = CAGradientLayer()
        grad.frame = self.bounds
        grad.colors = cgColours
        self.layer.insertSublayer(grad, at: 0)
    }
}

which I then call with

    class OverviewVC: UIViewController {

        override func viewDidLoad() {
            super.viewDidLoad()

            self.view.gradientOfView(withColours: UIColor.red,UIColor.green, UIColor.blue)

        }
}

Xcode 10: A valid provisioning profile for this executable was not found

I had the case where my app would deploy to my iPhone but not my watch. Deploying to the watch would give the "A valid provisioning profile for this executable was not found." error. This is with XCode Version 11.2.1 and using the free developer account.

Here is what I did to get it deployed to my watch:

1) I deleted my provisioning profile in XCode. I did this by going to Window -> Devices And Simulators. Then right Click on the iPhone name and choose "Show Provisioning Profiles". From there I could delete the file

2) In The Devices and Simulators screen I also deleted my app from the "Installed Apps" section.

3) Did a "clean build folder" (Product -> Clean Build Folder)

4) In the "Build Settings" -> "Signing section" I made sure each target (iPhone, Tests and Watch) had the same settings (development team, code signing style, provisioning profile was set to automatic etc).

build settings details

5) Ensured the ~/Library/MobileDevice/Provisioning Profiles directory was empty.

6) Unplugged phone from computer

7) Rebooted computer, phone and watch

8) Plugged phone back into computer, and went through the "trust this machine" prompts on phone and watch.

9) Ran app. It worked!

SSL: error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch

It happened to me when I combined the bundle.crt and main cert. The reason was I copied the main cert below the bundle.crt. It should be the other way around

1/ main cert 2/ bundle.crt

Angular get object from array by Id

getDimensions(id) {
    var obj = questions.filter(function(node) {
        return node.id==id;
    });

    return obj;   
}

CocoaPods Errors on Project Build

  1. open .xcodeproj file in sublime text
  2. remove these two lines, if you have clean pods folders, i mean if you got the errors above after you removed pods folder

Paste in insert mode?

You can also use the mouse middle button to paste in insert mode (Linux only).

Converting a Date object to a calendar object

Here's your method:

public static Calendar toCalendar(Date date){ 
  Calendar cal = Calendar.getInstance();
  cal.setTime(date);
  return cal;
}

Everything else you are doing is both wrong and unnecessary.

BTW, Java Naming conventions suggest that method names start with a lower case letter, so it should be: dateToCalendar or toCalendar (as shown).


OK, let's milk your code, shall we?

DateFormat formatter = new SimpleDateFormat("yyyyMMdd");
date = (Date)formatter.parse(date.toString()); 

DateFormat is used to convert Strings to Dates (parse()) or Dates to Strings (format()). You are using it to parse the String representation of a Date back to a Date. This can't be right, can it?

Add an incremental number in a field in INSERT INTO SELECT query in SQL Server

You can use the row_number() function for this.

INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
    SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
            row_number() over (order by (select NULL))
    FROM PM_Ingrediants 
    WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
                             )

If you want to start with the maximum already in the table then do:

INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
    SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
           coalesce(const.maxs, 0) + row_number() over (order by (select NULL))
    FROM PM_Ingrediants cross join
         (select max(sequence) as maxs from PM_Ingrediants_Arrangement_Temp) const
    WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
                             )

Finally, you can just make the sequence column an auto-incrementing identity column. This saves the need to increment it each time:

create table PM_Ingrediants_Arrangement_Temp ( . . .
    sequence int identity(1, 1) -- and might consider making this a primary key too
    . . .
)

How do I get class name in PHP?

Since PHP 5.5 you can use class name resolution via ClassName::class.

See new features of PHP5.5.

<?php

namespace Name\Space;

class ClassName {}

echo ClassName::class;

?>

If you want to use this feature in your class method use static::class:

<?php

namespace Name\Space;

class ClassName {
   /**
    * @return string
    */
   public function getNameOfClass()
   {
      return static::class;
   }
}

$obj = new ClassName();
echo $obj->getNameOfClass();

?>

For older versions of PHP, you can use get_class().

Echo a blank (empty) line to the console from a Windows batch file

Note: Though my original answer attracted several upvotes, I decided that I could do much better. You can find my original (simplistic and misguided) answer in the edit history.

If Microsoft had the intent of providing a means of outputting a blank line from cmd.exe, Microsoft surely would have documented such a simple operation. It is this omission that motivated me to ask this question.

So, because a means for outputting a blank line from cmd.exe is not documented, arguably one should consider any suggestion for how to accomplish this to be a hack. That means that there is no known method for outputting a blank line from cmd.exe that is guaranteed to work (or work efficiently) in all situations.

With that in mind, here is a discussion of methods that have been recommended for outputting a blank line from cmd.exe. All recommendations are based on variations of the echo command.


echo.

While this will work in many if not most situations, it should be avoided because it is slower than its alternatives and actually can fail (see here, here, and here). Specifically, cmd.exe first searches for a file named echo and tries to start it. If a file named echo happens to exist in the current working directory, echo. will fail with:

'echo.' is not recognized as an internal or external command,
operable program or batch file.

echo:
echo\

At the end of this answer, the author argues that these commands can be slow, for instance if they are executed from a network drive location. A specific reason for the potential slowness is not given. But one can infer that it may have something to do with accessing the file system. (Perhaps because : and \ have special meaning in a Windows file system path?)

However, some may consider these to be safe options since : and \ cannot appear in a file name. For that or another reason, echo: is recommended by SS64.com here.


echo(
echo+
echo,
echo/
echo;
echo=
echo[
echo]

This lengthy discussion includes what I believe to be all of these. Several of these options are recommended in this SO answer as well. Within the cited discussion, this post ends with what appears to be a recommendation for echo( and echo:.

My question at the top of this page does not specify a version of Windows. My experimentation on Windows 10 indicates that all of these produce a blank line, regardless of whether files named echo, echo+, echo,, ..., echo] exist in the current working directory. (Note that my question predates the release of Windows 10. So I concede the possibility that older versions of Windows may behave differently.)

In this answer, @jeb asserts that echo( always works. To me, @jeb's answer implies that other options are less reliable but does not provide any detail as to why that might be. Note that @jeb contributed much valuable content to other references I have cited in this answer.


Conclusion: Do not use echo.. Of the many other options I encountered in the sources I have cited, the support for these two appears most authoritative:

echo(
echo:

But I have not found any strong evidence that the use of either of these will always be trouble-free.


Example Usage:

@echo off
echo Here is the first line.
echo(
echo There is a blank line above this line.

Expected output:

Here is the first line.

There is a blank line above this line.

twig: IF with multiple conditions

If I recall correctly Twig doesn't support || and && operators, but requires or and and to be used respectively. I'd also use parentheses to denote the two statements more clearly although this isn't technically a requirement.

{%if ( fields | length > 0 ) or ( trans_fields | length > 0 ) %}

Expressions

Expressions can be used in {% blocks %} and ${ expressions }.

Operator    Description
==          Does the left expression equal the right expression?
+           Convert both arguments into a number and add them.
-           Convert both arguments into a number and substract them.
*           Convert both arguments into a number and multiply them.
/           Convert both arguments into a number and divide them.
%           Convert both arguments into a number and calculate the rest of the integer division.
~           Convert both arguments into a string and concatenate them.
or          True if the left or the right expression is true.
and         True if the left and the right expression is true.
not         Negate the expression.

For more complex operations, it may be best to wrap individual expressions in parentheses to avoid confusion:

{% if (foo and bar) or (fizz and (foo + bar == 3)) %}

How should I copy Strings in Java?

Strings are immutable objects so you can copy them just coping the reference to them, because the object referenced can't change ...

So you can copy as in your first example without any problem :

String s = "hello";
String backup_of_s = s;
s = "bye";

How does tuple comparison work in Python?

I had some confusion before regarding integer comparsion, so I will explain it to be more beginner friendly with an example

a = ('A','B','C') # see it as the string "ABC" b = ('A','B','D')

A is converted to its corresponding ASCII ord('A') #65 same for other elements

So, >> a>b # True you can think of it as comparing between string (It is exactly, actually)

the same thing goes for integers too.

x = (1,2,2) # see it the string "123" y = (1,2,3) x > y # False

because (1 is not greater than 1, move to the next, 2 is not greater than 2, move to the next 2 is less than three -lexicographically -)

The key point is mentioned in the answer above

think of it as an element is before another alphabetically not element is greater than an element and in this case consider all the tuple elements as one string.

Error creating bean with name 'entityManagerFactory

This sounds like a ClassLoader conflict. I'd bet you have the javax.persistence api 1.x on the classpath somewhere, whereas Spring is trying to access ValidationMode, which was only introduced in JPA 2.0.

Since you use Maven, do mvn dependency:tree, find the artifact:

<dependency>
    <groupId>javax.persistence</groupId>
    <artifactId>persistence-api</artifactId>
    <version>1.0</version>
</dependency>

And remove it from your setup. (See Excluding Dependencies)

AFAIK there is no such general distribution for JPA 2, but you can use this Hibernate-specific version:

<dependency>
    <groupId>org.hibernate.javax.persistence</groupId>
    <artifactId>hibernate-jpa-2.0-api</artifactId>
    <version>1.0.1.Final</version>
</dependency>

OK, since that doesn't work, you still seem to have some JPA-1 version in there somewhere. In a test method, add this code:

System.out.println(EntityManager.class.getProtectionDomain()
                                      .getCodeSource()
                                      .getLocation());

See where that points you and get rid of that artifact.


Ahh, now I finally see the problem. Get rid of this:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jpa</artifactId>
    <version>2.0.8</version>
</dependency>

and replace it with

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>3.2.5.RELEASE</version>
</dependency>

On a different note, you should set all test libraries (spring-test, easymock etc.) to

<scope>test</scope>

How do I determine if my python shell is executing in 32bit or 64bit?

Platform Architecture is not the reliable way. Instead us:

$ arch -i386 /usr/local/bin/python2.7
Python 2.7.9 (v2.7.9:648dcafa7e5f, Dec 10 2014, 10:10:46)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import platform, sys
>>> platform.architecture(), sys.maxsize
(('64bit', ''), 2147483647)
>>> ^D
$ arch -x86_64 /usr/local/bin/python2.7
Python 2.7.9 (v2.7.9:648dcafa7e5f, Dec 10 2014, 10:10:46)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import platform, sys
>>> platform.architecture(), sys.maxsize
(('64bit', ''), 9223372036854775807)

Any way to make plot points in scatterplot more transparent in R?

Transparency can be coded in the color argument as well. It is just two more hex numbers coding a transparency between 0 (fully transparent) and 255 (fully visible). I once wrote this function to add transparency to a color vector, maybe it is usefull here?

addTrans <- function(color,trans)
{
  # This function adds transparancy to a color.
  # Define transparancy with an integer between 0 and 255
  # 0 being fully transparant and 255 being fully visable
  # Works with either color and trans a vector of equal length,
  # or one of the two of length 1.

  if (length(color)!=length(trans)&!any(c(length(color),length(trans))==1)) stop("Vector lengths not correct")
  if (length(color)==1 & length(trans)>1) color <- rep(color,length(trans))
  if (length(trans)==1 & length(color)>1) trans <- rep(trans,length(color))

  num2hex <- function(x)
  {
    hex <- unlist(strsplit("0123456789ABCDEF",split=""))
    return(paste(hex[(x-x%%16)/16+1],hex[x%%16+1],sep=""))
  }
  rgb <- rbind(col2rgb(color),trans)
  res <- paste("#",apply(apply(rgb,2,num2hex),2,paste,collapse=""),sep="")
  return(res)
}

Some examples:

cols <- sample(c("red","green","pink"),100,TRUE)

# Fully visable:
plot(rnorm(100),rnorm(100),col=cols,pch=16,cex=4)

# Somewhat transparant:
plot(rnorm(100),rnorm(100),col=addTrans(cols,200),pch=16,cex=4)

# Very transparant:
plot(rnorm(100),rnorm(100),col=addTrans(cols,100),pch=16,cex=4)

How to get an object's properties in JavaScript / jQuery?

Get FireBug for Mozilla Firefox.

use console.log(obj);

Decoding a Base64 string in Java

Modify the package you're using:

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

And then use it like this:

byte[] decoded = Base64.decodeBase64("YWJjZGVmZw==");
System.out.println(new String(decoded, "UTF-8") + "\n");

Setting the filter to an OpenFileDialog to allow the typical image formats?

This is extreme, but I built a dynamic, database-driven filter using a 2 column database table named FILE_TYPES, with field names EXTENSION and DOCTYPE:

---------------------------------
| EXTENSION  |  DOCTYPE         |
---------------------------------
|   .doc     |  Document        |
|   .docx    |  Document        |
|   .pdf     |  Document        |
|   ...      |  ...             |
|   .bmp     |  Image           |
|   .jpg     |  Image           |
|   ...      |  ...             |
---------------------------------

Obviously I had many different types and extensions, but I'm simplifying it for this example. Here is my function:

    private static string GetUploadFilter()
    {
        // Desired format:
        // "Document files (*.doc, *.docx, *.pdf)|*.doc;*.docx;*.pdf|"
        // "Image files (*.bmp, *.jpg)|*.bmp;*.jpg|"

        string filter = String.Empty;
        string nameFilter = String.Empty;
        string extFilter = String.Empty;

        // Used to get extensions
        DataTable dt = new DataTable();
        dt = DataLayer.Get_DataTable("SELECT * FROM FILE_TYPES ORDER BY EXTENSION");

        // Used to cycle through doctype groupings ("Images", "Documents", etc.)
        DataTable dtDocTypes = new DataTable();
        dtDocTypes = DataLayer.Get_DataTable("SELECT DISTINCT DOCTYPE FROM FILE_TYPES ORDER BY DOCTYPE");

        // For each doctype grouping...
        foreach (DataRow drDocType in dtDocTypes.Rows)
        {
            nameFilter = drDocType["DOCTYPE"].ToString() + " files (";

            // ... add its associated extensions
            foreach (DataRow dr in dt.Rows)
            {
                if (dr["DOCTYPE"].ToString() == drDocType["DOCTYPE"].ToString())
                {
                    nameFilter += "*" + dr["EXTENSION"].ToString() + ", ";
                    extFilter += "*" + dr["EXTENSION"].ToString() + ";";
                }                    
            }

            // Remove endings put in place in case there was another to add, and end them with pipe characters:
            nameFilter = nameFilter.TrimEnd(' ').TrimEnd(',');
            nameFilter += ")|";
            extFilter = extFilter.TrimEnd(';');
            extFilter += "|";

            // Add the name and its extensions to our main filter
            filter += nameFilter + extFilter;

            extFilter = ""; // clear it for next round; nameFilter will be reset to the next DOCTYPE on next pass
        }

        filter = filter.TrimEnd('|');
        return filter;
    }

    private void UploadFile(string fileType, object sender)
    {            
        Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
        string filter = GetUploadFilter();
        dlg.Filter = filter;

        if (dlg.ShowDialog().Value == true)
        {
            string fileName = dlg.FileName;

            System.IO.FileStream fs = System.IO.File.OpenRead(fileName);
            byte[] array = new byte[fs.Length];

            // This will give you just the filename
            fileName = fileName.Split('\\')[fileName.Split('\\').Length - 1];
            ...

Should yield a filter that looks like this:

enter image description here

Cross-Origin Request Headers(CORS) with PHP headers

I got the same error, and fixed it with the following PHP in my back-end script:

header('Access-Control-Allow-Origin: *');

header('Access-Control-Allow-Methods: GET, POST');

header("Access-Control-Allow-Headers: X-Requested-With");

How to set the background image of a html 5 canvas to .png image

You can use this plugin, but for printing purpose i have added some code like <button onclick="window.print();">Print</button> and for saving image <button onclick="savePhoto();">Save Picture</button>

     function savePhoto() {
     var canvas = document.getElementById("canvas");
     var img    = canvas.toDataURL("image/png");
     window.location = img;}

checkout this plugin http://www.williammalone.com/articles/create-html5-canvas-javascript-drawing-app

Reducing the gap between a bullet and text in a list item

You could try the following. But it requires you to put a <span> element inside the <li> elements

<html>
<head>
<style type="text/css">
ul.a li span{
position:relative;
left:-0.5em;

}
</style>
</head>

<body>

<ul class="a">
  <li><span>Coffee</span></li>
  <li><span>Tea</span></li>
  <li><span>Coca Cola</span></li>
</ul>
</body>
</html>

Binary Search Tree - Java Implementation

You can use a TreeMap data structure. TreeMap is implemented as a red black tree, which is a self-balancing binary search tree.

HTTP GET with request body

Elasticsearch accepts GET requests with a body. It even seems that this is the preferred way: Elasticsearch guide

Some client libraries (like the Ruby driver) can log the cry command to stdout in development mode and it is using this syntax extensively.

How to specify jdk path in eclipse.ini on windows 8 when path contains space

if you are using mac, proceed with following steps:

  1. Move to following directory:

    /sts-bundle/STS.app/Contents/Eclipse
    
  2. Add the java home explicitly in STS.ini file:

    -vm
    /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/bin
    -vmargs
    

Make sure not to add all the statements in single line

SASS :not selector

I tried re-creating this, and .someclass.notip was being generated for me but .someclass:not(.notip) was not, for as long as I did not have the @mixin tip() defined. Once I had that, it all worked.

http://sassmeister.com/gist/9775949

$dropdown-width: 100px;
$comp-tip: true;

@mixin tip($pos:right) {

}

@mixin dropdown-pos($pos:right) {
  &:not(.notip) {
    @if $comp-tip == true{
      @if $pos == right {
        top:$dropdown-width * -0.6;
        background-color: #f00;
        @include tip($pos:$pos);
      }
    }
  }
  &.notip {
    @if $pos == right {
      top: 0;
      left:$dropdown-width * 0.8;
      background-color: #00f;
    }
  }
}

.someclass { @include dropdown-pos(); }

EDIT: http://sassmeister.com/ is a good place to debug your SASS because it gives you error messages. Undefined mixin 'tip'. it what I get when I remove @mixin tip($pos:right) { }

Why are only a few video games written in Java?

Even games written on the .Net platform are often highly optimized for speed like direct access to memory and bus. .Net allows to use C / C++ and mix it with higher level languages such as C#.

Game development studios often work close together with hardware vendors, which do provide access to low level interfaces of their products. This is a world, where you have to use ASM and C for device communication. A virtual environment would slow down these program parts.

Anyway, modern 3D games in fact do use higher level languages. Often, you'll find the game logic written in languages like Lua or Python. But the core (I/O, threads, task scheduling) of the typical 3D game will be written in low level languages for the next 25 years or as long devices do not allow abstraction and virtualization by themself (which will come).

#1227 - Access denied; you need (at least one of) the SUPER privilege(s) for this operation

remove DEFINER=root@localhost from all calls including procedures

How to get user agent in PHP

You can use the jQuery ajax method link if you want to pass data from client to server. In this case you can use $_SERVER['HTTP_USER_AGENT'] variable to found browser user agent.

Cannot drop database because it is currently in use

before dropping a database, you drop the connection to that database first.

I have found a solution at http://www.kodyaz.com/articles/kill-all-processes-of-a-database.aspx

DECLARE @DatabaseName nvarchar(50)
SET @DatabaseName = N'YOUR_DABASE_NAME'

DECLARE @SQL varchar(max)

SELECT @SQL = COALESCE(@SQL,'') + 'Kill ' + Convert(varchar, SPId) + ';'
FROM MASTER..SysProcesses
WHERE DBId = DB_ID(@DatabaseName) AND SPId <> @@SPId

--SELECT @SQL 
EXEC(@SQL)

Trigger event on body load complete js/jquery

$(document).ready(function() {
    // do needed things
});

This will trigger once the DOM structure is ready.

Build error, This project references NuGet

Why should you need manipulations with packages.config or .csproj files?
The error explicitly says: Use NuGet Package Restore to download them.
Use it accordingly this instruction: https://docs.microsoft.com/en-us/nuget/consume-packages/package-restore-troubleshooting:

Quick solution for Visual Studio users
1.Select the Tools > NuGet Package Manager > Package Manager Settings menu command.
2.Set both options under Package Restore.
3.Select OK.
4.Build your project again.

Git copy changes from one branch to another

git checkout BranchB
git merge BranchA
git push origin BranchB

This is all if you intend to not merge your changes back to master. Generally it is a good practice to merge all your changes back to master, and create new branches off of that.

Also, after the merge command, you will have some conflicts, which you will have to edit manually and fix.

Make sure you are in the branch where you want to copy all the changes to. git merge will take the branch you specify and merge it with the branch you are currently in.

What is the difference between supervised learning and unsupervised learning?

Supervised learning: say a kid goes to kinder-garden. here teacher shows him 3 toys-house,ball and car. now teacher gives him 10 toys. he will classify them in 3 box of house,ball and car based on his previous experience. so kid was first supervised by teachers for getting right answers for few sets. then he was tested on unknown toys. aa

Unsupervised learning: again kindergarten example.A child is given 10 toys. he is told to segment similar ones. so based on features like shape,size,color,function etc he will try to make 3 groups say A,B,C and group them. bb

The word Supervise means you are giving supervision/instruction to machine to help it find answers. Once it learns instructions, it can easily predict for new case.

Unsupervised means there is no supervision or instruction how to find answers/labels and machine will use its intelligence to find some pattern in our data. Here it will not make prediction, it will just try to find clusters which has similar data.

How to disable 'X-Frame-Options' response header in Spring Security?

Most likely you don't want to deactivate this Header completely, but use SAMEORIGIN. If you are using the Java Configs (Spring Boot) and would like to allow the X-Frame-Options: SAMEORIGIN, then you would need to use the following.


For older Spring Security versions:

http
   .headers()
       .addHeaderWriter(new XFrameOptionsHeaderWriter(XFrameOptionsHeaderWriter.XFrameOptionsMode.SAMEORIGIN))

For newer versions like Spring Security 4.0.2:

http
   .headers()
      .frameOptions()
         .sameOrigin();