Programs & Examples On #Subscribe

0

Angular 2 - Checking for server errors from subscribe

You can achieve with following way

    this.projectService.create(project)
    .subscribe(
        result => {
         console.log(result);
        },
        error => {
            console.log(error);
            this.errors = error
        }
    ); 
}

if (!this.errors) {
    //route to new page
}

Angular 2: How to call a function after get a response from subscribe http.post

get_categories(number){
 return this.http.post( url, body, {headers: headers, withCredentials:true})
      .map(t=>  {
          this.total = t.json();
          return total;
      }).share();
  );     
}

then

this.get_category(1).subscribe(t=> {
      this.callfunc();
});

int array to string

string result = arr.Aggregate("", (s, i) => s + i.ToString());

(Disclaimer: If you have a lot of digits (hundreds, at least) and you care about performance, I suggest eschewing this method and using a StringBuilder, as in JaredPar's answer.)

Correct format specifier for double in printf

%Lf (note the capital L) is the format specifier for long doubles.

For plain doubles, either %e, %E, %f, %g or %G will do.

How to track down access violation "at address 00000000"

The accepted answer does not tell the entire story.

Yes, whenever you see zeros, a NULL pointer is involved. That is because NULL is by definition zero. So calling zero NULL may not be saying much.

What is interesting about the message you get is the fact that NULL is mentioned twice. In fact, the message you report looks a little bit like the messages Windows-brand operating systems show the user.

The message says the address NULL tried to read NULL. So what does that mean? Specifically, how does an address read itself?

We typically think of the instructions at an address reading and writing from memory at certain addresses. Knowing that allows us to parse the error message. The message is trying to articulate that the instruction at address NULL tried to read NULL.

Of course, there is no instruction at address NULL, that is why we think of NULL as special in our code. But every instruction can be thought of as commencing with the attempt to read itself. If the CPUs EIP register is at address NULL, then the CPU will attempt to read the opcode for an instruction from address 0x00000000 (NULL). This attempt to read NULL will fail, and generate the message you have received.

In the debugger, notice that EIP equals 0x00000000 when you receive this message. This confirms the description I have given you.

The question then becomes, "why does my program attempt to execute the NULL address." There are three possibilities which spring to mind:

  • You have attempt to make a function call via a function pointer which you have declared, assigned to NULL, never initialized otherwise, and are dereferencing.
  • Similarly, you may be calling an "abstract" C++ method which has a NULL entry in the object's vtable. These are created in your code with the syntax virtual function_name()=0.
  • In your code, a stack buffer has been overflowed while writing zeros. The zeros have been written beyond the end of the stack buffer, over the preserved return address. When the function later executes its ret instruction, the value 0x00000000 (NULL) is loaded from the overwritten memory spot. This type of error, stack overflow, is the eponym of our forum.

Since you mention that you are calling a third-party library, I will point out that it may be a situation of the library expecting you to provide a non-NULL function pointer as input to some API. These are sometimes known as "call back" functions.

You will have to use the debugger to narrow down the cause of your problem further, but the above possiblities should help you solve the riddle.

ASP.NET: Session.SessionID changes between requests

my problem was that we had this set in web.config

<httpCookies httpOnlyCookies="true" requireSSL="true" />

this means that when debugging in non-SSL (the default), the auth cookie would not get sent back to the server. this would mean that the server would send a new auth cookie (with a new session) for every request back to the client.

the fix is to either set requiressl to false in web.config and true in web.release.config or turn on SSL while debugging:

turn on SSL

Finding out the name of the original repository you cloned from in Git

git remote show origin -n | ruby -ne 'puts /^\s*Fetch.*(:|\/){1}([^\/]+\/[^\/]+).git/.match($_)[2] rescue nil'

It was tested with three different URL styles:

echo "Fetch URL: http://user@pass:gitservice.org:20080/owner/repo.git" | ruby -ne 'puts /^\s*Fetch.*(:|\/){1}([^\/]+\/[^\/]+).git/.match($_)[2] rescue nil'
echo "Fetch URL: Fetch URL: [email protected]:home1-oss/oss-build.git" | ruby -ne 'puts /^\s*Fetch.*(:|\/){1}([^\/]+\/[^\/]+).git/.match($_)[2] rescue nil'
echo "Fetch URL: https://github.com/owner/repo.git" | ruby -ne 'puts /^\s*Fetch.*(:|\/){1}([^\/]+\/[^\/]+).git/.match($_)[2] rescue nil'

AngularJS Error: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https

I would add that one can also use xampp, mamp type of things and put your project in the htdocs folder so it is accessible on localhost

Stream file using ASP.NET MVC FileContentResult in a browser with a name?

Actually, the absolutely easiest way is to do the following...

byte[] content = your_byte[];

FileContentResult result = new FileContentResult(content, "application/octet-stream") 
{
  FileDownloadName = "your_file_name"
};

return result;

macOS on VMware doesn't recognize iOS device

If you went throught alot of pain installing macos on vmware I recommend this tutorial which also provides you with all the file you need. it's straight forward tutorial and works all the way without any problem.

How to Load an Assembly to AppDomain with all references recursively?

It took me a while to understand @user1996230's answer so I decided to provide a more explicit example. In the below example I make a proxy for an object loaded in another AppDomain and call a method on that object from another domain.

class ProxyObject : MarshalByRefObject
{
    private Type _type;
    private Object _object;

    public void InstantiateObject(string AssemblyPath, string typeName, object[] args)
    {
        assembly = Assembly.LoadFrom(AppDomain.CurrentDomain.BaseDirectory + AssemblyPath); //LoadFrom loads dependent DLLs (assuming they are in the app domain's base directory
        _type = assembly.GetType(typeName);
        _object = Activator.CreateInstance(_type, args); ;
    }

    public void InvokeMethod(string methodName, object[] args)
    {
        var methodinfo = _type.GetMethod(methodName);
        methodinfo.Invoke(_object, args);
    }
}

static void Main(string[] args)
{
    AppDomainSetup setup = new AppDomainSetup();
    setup.ApplicationBase = @"SomePathWithDLLs";
    AppDomain domain = AppDomain.CreateDomain("MyDomain", null, setup);
    ProxyObject proxyObject = (ProxyObject)domain.CreateInstanceFromAndUnwrap(typeof(ProxyObject).Assembly.Location,"ProxyObject");
    proxyObject.InstantiateObject("SomeDLL","SomeType", new object[] { "someArgs});
    proxyObject.InvokeMethod("foo",new object[] { "bar"});
}

An unhandled exception of type 'System.IO.FileNotFoundException' occurred in Unknown Module

What I would do is use this tool and step through where you are getting the exception

http://www.reflector.net/

Read this it will tell you how to create PDB's so you do not have to have all your references setup.

http://www.cplotts.com/2011/01/14/net-reflector-pro-debugging-the-net-framework-source-code/

It is a trial and I am not related to redgate at all I just use there software.

How do I check the difference, in seconds, between two dates?

Another approach is to use timestamp values:

end_time.timestamp() - start_time.timestamp()

How do I add a custom script to my package.json file that runs a javascript file?

Lets say in scripts you want to run 2 commands with a single command:

"scripts":{
  "start":"any command",
  "singleCommandToRunTwoCommand":"some command here && npm start"
}

Now go to your terminal and run there npm run singleCommandToRunTwoCommand.

What is the correct syntax for 'else if'?

In python "else if" is spelled "elif".
Also, you need a colon after the elif and the else.

Simple answer to a simple question. I had the same problem, when I first started (in the last couple of weeks).

So your code should read:

def function(a):
    if a == '1':
        print('1a')
    elif a == '2':
        print('2a')
    else:
        print('3a')

function(input('input:'))

Scatter plot with error bars

Using ggplot and a little dplyr for data manipulation:

set.seed(42)
df <- data.frame(x = rep(1:10,each=5), y = rnorm(50))

library(ggplot2)
library(dplyr)

df.summary <- df %>% group_by(x) %>%
    summarize(ymin = min(y),
              ymax = max(y),
              ymean = mean(y))

ggplot(df.summary, aes(x = x, y = ymean)) +
    geom_point(size = 2) +
    geom_errorbar(aes(ymin = ymin, ymax = ymax))

If there's an additional grouping column (OP's example plot has two errorbars per x value, saying the data is sourced from two files), then you should get all the data in one data frame at the start, add the grouping variable to the dplyr::group_by call (e.g., group_by(x, file) if file is the name of the column) and add it as a "group" aesthetic in the ggplot, e.g., aes(x = x, y = ymean, group = file).

Forcing to download a file using PHP

.htaccess Solution

To brute force all CSV files on your server to download, add in your .htaccess file:

AddType application/octet-stream csv

PHP Solution

header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename=example.csv');
header('Pragma: no-cache');
readfile("/path/to/yourfile.csv");

Can not get a simple bootstrap modal to work

I run into this issue too. I was including bootstrap.js AND bootstrap-modal.js. If you already have bootstrap.js, you don't need to include popover.

how to format date in Component of angular 5

Refer to the below link,

https://angular.io/api/common/DatePipe

**Code Sample**

@Component({
 selector: 'date-pipe',
 template: `<div>
   <p>Today is {{today | date}}</p>
   <p>Or if you prefer, {{today | date:'fullDate'}}</p>
   <p>The time is {{today | date:'h:mm a z'}}</p>
 </div>`
})
// Get the current date and time as a date-time value.
export class DatePipeComponent {
  today: number = Date.now();
}

{{today | date:'MM/dd/yyyy'}} output: 17/09/2019

or

{{today | date:'shortDate'}} output: 17/9/19

How to center-justify the last line of text in CSS?

Calculate the length of your text line and create a block which is the same size as the line of text. Center the block. If you have two lines you will need two blocks if they are different lengths. You could use a span tag and a br tag if you don't want extra spaces from the blocks. You can also use the pre tag to format inside a block.

And you can do this: style='text-align:center;'

For vertical see: http://www.w3schools.com/cssref/pr_pos_vertical-align.asp

Here is the best way for blocks and web page layouts, go here and learn flex the new standard which started in 2009. http://www.w3.org/TR/2014/WD-css-flexbox-1-20140325/#justify-content-property

Also w3schools has lots of flex examples.

Python 3.2 Unable to import urllib2 (ImportError: No module named urllib2)

PYTHON 3

import urllib.request

wp = urllib.request.urlopen("http://example.com")

pw = wp.read()

print(pw)

PYTHON 2

import urllib

 import sys

 wp = urllib.urlopen("http://example.com")

 for line in wp:

     sys.stdout.write(line)

While I have tested both the Codes in respective versions.

Understanding .get() method in Python

Start here http://docs.python.org/tutorial/datastructures.html#dictionaries

Then here http://docs.python.org/library/stdtypes.html#mapping-types-dict

Then here http://docs.python.org/library/stdtypes.html#dict.get

characters.get( key, default )

key is a character

default is 0

If the character is in the dictionary, characters, you get the dictionary object.

If not, you get 0.


Syntax:

get(key[, default])

Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.

Correct way to set Bearer token with CURL

This is a cURL function that can send or retrieve data. It should work with any PHP app that supports OAuth:

    function jwt_request($token, $post) {

       header('Content-Type: application/json'); // Specify the type of data
       $ch = curl_init('https://APPURL.com/api/json.php'); // Initialise cURL
       $post = json_encode($post); // Encode the data array into a JSON string
       $authorization = "Authorization: Bearer ".$token; // Prepare the authorisation token
       curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json' , $authorization )); // Inject the token into the header
       curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
       curl_setopt($ch, CURLOPT_POST, 1); // Specify the request method as POST
       curl_setopt($ch, CURLOPT_POSTFIELDS, $post); // Set the posted fields
       curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // This will follow any redirects
       $result = curl_exec($ch); // Execute the cURL statement
       curl_close($ch); // Close the cURL connection
       return json_decode($result); // Return the received data

    }

Use it within one-way or two-way requests:

$token = "080042cad6356ad5dc0a720c18b53b8e53d4c274"; // Get your token from a cookie or database
$post = array('some_trigger'=>'...','some_values'=>'...'); // Array of data with a trigger
$request = jwt_request($token,$post); // Send or retrieve data

How to delete columns in pyspark dataframe

You can use two way:

1: You just keep the necessary columns:

drop_column_list = ["drop_column"]
df = df.select([column for column in df.columns if column not in drop_column_list])  

2: This is the more elegant way.

df = df.drop("col_name")

You should avoid the collect() version, because it will send to the master the complete dataset, it will take a big computing effort!

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

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

You can see in below-attached screenshot

Getting the first and last day of a month, using a given DateTime object

"Last day of month" is actually "First day of *next* month, minus 1". So here's what I use, no need for "DaysInMonth" method:

public static DateTime FirstDayOfMonth(this DateTime value)
{
    return new DateTime(value.Year, value.Month, 1);
}

public static DateTime LastDayOfMonth(this DateTime value)
{
    return value.FirstDayOfMonth()
        .AddMonths(1)
        .AddMinutes(-1);
}

NOTE: The reason I use AddMinutes(-1), not AddDays(-1) here is because usually you need these date functions for reporting for some date-period, and when you build a report for a period, the "end date" should actually be something like Oct 31 2015 23:59:59 so your report works correctly - including all the data from last day of month.

I.e. you actually get the "last moment of the month" here. Not Last day.

OK, I'm going to shut up now.

Set title background color

I have done this by changing style color values in "res" -> "values" -> "colors.xml" enter image description here

This will change colors for entire project which is fine with me.

enter image description here

"SetPropertiesRule" warning message when starting Tomcat from Eclipse

The solution to this problem is very simple. Double click on your tomcat server. It will open the server configuration. Under server options check ‘Publish module contents to separate XML files’ checkbox. Restart your server. This time your page will come without any issues.

Find files in a folder using Java

To elaborate on this response, Apache IO Utils might save you some time. Consider the following example that will recursively search for a file of a given name:

    File file = FileUtils.listFiles(new File("the/desired/root/path"), 
                new NameFileFilter("filename.ext"), 
                FileFilterUtils.trueFileFilter()
            ).iterator().next();

See:

How to read response headers in angularjs?

Updated based on Muhammad's answer...

$http.get('/someUrl').
  success(function(data, status, headers, config) {
    // this callback will be called asynchronously
    // when the response is available
    console.log(headers()['Content-Range']);
  })
  .error(function(data, status, headers, config) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

What’s the best way to check if a file exists in C++? (cross platform)

How about access?

#include <io.h>

if (_access(filename, 0) == -1)
{
    // File does not exist
}

jQuery form validation on button click

You can also achieve other way using button tag

According new html5 attribute you also can add a form attribute like

<form id="formId">
    <input type="text" name="fname">
</form>

<button id="myButton" form='#formId'>My Awesome Button</button>

So the button will be attached to the form.

This should work with the validate() plugin of jQuery like :

var validator = $( "#formId" ).validate();
validator.element( "#myButton" );

It's working too with input tag

Source :

https://developer.mozilla.org/docs/Web/HTML/Element/Button

MongoDB: Server has startup warnings ''Access control is not enabled for the database''

You need to delete your old db folder and recreate new one. It will resolve your issue.

What is an uber jar?

Über is the German word for above or over (it's actually cognate with the English over).

Hence, in this context, an uber-jar is an "over-jar", one level up from a simple JAR (a), defined as one that contains both your package and all its dependencies in one single JAR file. The name can be thought to come from the same stable as ultrageek, superman, hyperspace, and metadata, which all have similar meanings of "beyond the normal".

The advantage is that you can distribute your uber-jar and not care at all whether or not dependencies are installed at the destination, as your uber-jar actually has no dependencies.

All the dependencies of your own stuff within the uber-jar are also within that uber-jar. As are all dependencies of those dependencies. And so on.


(a) I probably shouldn't have to explain what a JAR is to a Java developer but I'll include it for completeness. It's a Java archive, basically a single file that typically contains a number of Java class files along with associated metadata and resources.

Using CSS to affect div style inside iframe

Combining the different solutions, this is what worked for me.

$(document).ready(function () {
    $('iframe').on('load', function() {
        $("iframe").contents().find("#back-link").css("display", "none");
    }); 
});

Modifying list while iterating

I've been bitten before by (someone else's) "clever" code that tries to modify a list while iterating over it. I resolved that I would never do it under any circumstance.

You can use the slice operator mylist[::3] to skip across to every third item in your list.

mylist = [i for i in range(100)]
for i in mylist[::3]:
    print(i)

Other points about my example relate to new syntax in python 3.0.

  • I use a list comprehension to define mylist because it works in Python 3.0 (see below)
  • print is a function in python 3.0

Python 3.0 range() now behaves like xrange() used to behave, except it works with values of arbitrary size. The latter no longer exists.

Git add and commit in one command

For the silver backs in the crowd that are used to things like Subversion... to do a "commit" in the old sense of the word (i.e. -- or in git speak -- to add, commit, and push) in a single step I generally add something like the following in the root of my project (as a bat file in windows e.g. git-commit.bat). Then when I want to add, commit, and push I just type something like git-commit "Added some new stuff" and it all goes to the remote repo.

Also, this way anyone on the project can use the same with out having to change anything locally.

I usually also run git config credential.helper store once so I don't need to give uid/pwd when this is run.

::
:: add, commit, and push to git
::

@echo off
echo.
echo.
echo 
echo Doing commit...
git add -A && git commit -m %1
echo.
echo.
echo Doing push...
git push
echo.
echo.
echo Done.
echo.

How to initialise memory with new operator in C++?

you can always use memset:

int myArray[10];
memset( myArray, 0, 10 * sizeof( int ));

With MySQL, how can I generate a column containing the record index in a table?

You can also use

SELECT @curRow := ifnull(@curRow,0) + 1 Row, ...

to initialise the counter variable.

How to sort a List<Object> alphabetically using Object name field

I found another way to do the type.

if(listAxu.size() > 0){
    Collections.sort(listAxu, Comparator.comparing(IdentityNamed::getDescricao));
}

Plot Normal distribution with Matplotlib

Note: This solution is using pylab, not matplotlib.pyplot

You may try using hist to put your data info along with the fitted curve as below:

import numpy as np
import scipy.stats as stats
import pylab as pl

h = sorted([186, 176, 158, 180, 186, 168, 168, 164, 178, 170, 189, 195, 172,
     187, 180, 186, 185, 168, 179, 178, 183, 179, 170, 175, 186, 159,
     161, 178, 175, 185, 175, 162, 173, 172, 177, 175, 172, 177, 180])  #sorted

fit = stats.norm.pdf(h, np.mean(h), np.std(h))  #this is a fitting indeed

pl.plot(h,fit,'-o')

pl.hist(h,normed=True)      #use this to draw histogram of your data

pl.show()                   #use may also need add this 

enter image description here

Access all Environment properties as a Map or Properties object

I though I'd add one more way. In my case I supply this to com.hazelcast.config.XmlConfigBuilder which only needs java.util.Properties to resolve some properties inside the Hazelcast XML configuration file, i.e. it only calls getProperty(String) method. So, this allowed me to do what I needed:

@RequiredArgsConstructor
public class SpringReadOnlyProperties extends Properties {

  private final org.springframework.core.env.Environment delegate;

  @Override
  public String getProperty(String key) {
    return delegate.getProperty(key);
  }

  @Override
  public String getProperty(String key, String defaultValue) {
    return delegate.getProperty(key, defaultValue);
  }

  @Override
  public synchronized String toString() {
    return getClass().getName() + "{" + delegate + "}";
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    if (!super.equals(o)) return false;
    SpringReadOnlyProperties that = (SpringReadOnlyProperties) o;
    return delegate.equals(that.delegate);
  }

  @Override
  public int hashCode() {
    return Objects.hash(super.hashCode(), delegate);
  }

  private void throwException() {
    throw new RuntimeException("This method is not supported");
  }

  //all methods below throw the exception

  * override all methods *
}

P.S. I ended up not using this specifically for Hazelcast because it only resolves properties for XML file but not at runtime. Since I also use Spring, I decided to go with a custom org.springframework.cache.interceptor.AbstractCacheResolver#getCacheNames. This resolves properties for both situations, at least if you use properties in cache names.

How to get the size of a varchar[n] field in one SQL statement?

select column_name, data_type, character_maximum_length    
from INFORMATION_SCHEMA.COLUMNS
where table_name = 'Table1'

Get User Selected Range

This depends on what you mean by "get the range of selection". If you mean getting the range address (like "A1:B1") then use the Address property of Selection object - as Michael stated Selection object is much like a Range object, so most properties and methods works on it.

Sub test()
    Dim myString As String
    myString = Selection.Address
End Sub

Ruby value of a hash key?

Hashes are indexed using the square brackets ([]). Just as arrays. But instead of indexing with the numerical index, hashes are indexed using either the string literal you used for the key, or the symbol. So if your hash is similar to

hash = { "key1" => "value1", "key2" => "value2" }

you can access the value with

hash["key1"]

or for

hash = { :key1 => "value1", :key2 => "value2"}

or the new format supported in Ruby 1.9

hash = { key1: "value1", key2: "value2" }

you can access the value with

hash[:key1]

How npm start runs a server on port 8000

You can change the port in the console by running the following on Windows:

SET PORT=8000

For Mac, Linux or Windows WSL use the following:

export PORT=8000

The export sets the environment variable for the current shell and all child processes like npm that might use it.

If you want the environment variable to be set just for the npm process, precede the command with the environment variable like this (on Mac and Linux and Windows WSL):

PORT=8000 npm run start

Font Awesome not working, icons showing as squares

It wasn't working for me because I had Allow from none directive for the root directory in my apache config. Here's how I got it to work...

My directory structure:

root/
root/font-awesome/4.4.0/css/font-awesome.min.css
root/font-awesome/4.4.0/fonts/fontawesome-webfont.*
root/dir1/index.html

where my index.html has:

<link rel="stylesheet" href="../font-awesome/4.4.0/css/font-awesome.min.css">

I chose to continue to disallow access to my root and instead added another directory entry in my apache config for root/font-awesome/

<Directory "/path/root/font-awesome/">
    Allow from all
</Directory>

Visual Studio Code Search and Replace with Regular Expressions

Make sure Match Case is selected with Use Regular Expression so this matches. [A-Z]* If match case is not selected, this matches all letters.

How would one write object-oriented code in C?

I'm a bit late to the party, but I want to share my experience on the topic: I work with embedded stuff these days, and the only (reliable) compiler I have is C, so that I want to apply object-oriented approach in my embedded projects written in C.

Most of the solutions I've seen so far use typecasts heavily, so we lose type safety: compiler won't help you if you make a mistake. This is completely unacceptable.

Requirements that I have:

  • Avoid typecasts as much as possible, so we don't lose type safety;
  • Polymorphism: we should be able to use virtual methods, and user of the class should not be aware whether some particular method is virtual or not;
  • Multiple inheritance: I don't use it often, but sometimes I really want some class to implement multiple interfaces (or to extend multiple superclasses).

I've explained my approach in detail in this article: Object-oriented programming in C; plus, there is an utility for autogeneration of boilerplate code for base and derived classes.

Single controller with multiple GET methods in ASP.NET Web API

Go from this:

config.Routes.MapHttpRoute("API Default", "api/{controller}/{id}",
            new { id = RouteParameter.Optional });

To this:

config.Routes.MapHttpRoute("API Default", "api/{controller}/{action}/{id}",
            new { id = RouteParameter.Optional });

Hence, you can now specify which action (method) you want to send your HTTP request to.

posting to "http://localhost:8383/api/Command/PostCreateUser" invokes:

public bool PostCreateUser(CreateUserCommand command)
{
    //* ... *//
    return true;
}

and posting to "http://localhost:8383/api/Command/PostMakeBooking" invokes:

public bool PostMakeBooking(MakeBookingCommand command)
{
    //* ... *//
    return true;
}

I tried this in a self hosted WEB API service application and it works like a charm :)

Java: export to an .jar file in eclipse

FatJar can help you in this case.

In addition to the"Export as Jar" function which is included to Eclipse the Plug-In bundles all dependent JARs together into one executable jar.
The Plug-In adds the Entry "Build Fat Jar" to the Context-Menu of Java-projects

This is useful if your final exported jar includes other external jars.

If you have Ganymede, the Export Jar dialog is enough to export your resources from your project.

After Ganymede, you have:

Export Jar

Multiple inheritance for an anonymous class

Anonymous classes must extend or implement something, like any other Java class, even if it's just java.lang.Object.

For example:

Runnable r = new Runnable() {
   public void run() { ... }
};

Here, r is an object of an anonymous class which implements Runnable.

An anonymous class can extend another class using the same syntax:

SomeClass x = new SomeClass() {
   ...
};

What you can't do is implement more than one interface. You need a named class to do that. Neither an anonymous inner class, nor a named class, however, can extend more than one class.

List tables in a PostgreSQL schema

In all schemas:

=> \dt *.*

In a particular schema:

=> \dt public.*

It is possible to use regular expressions with some restrictions

\dt (public|s).(s|t)
       List of relations
 Schema | Name | Type  | Owner 
--------+------+-------+-------
 public | s    | table | cpn
 public | t    | table | cpn
 s      | t    | table | cpn

Advanced users can use regular-expression notations such as character classes, for example [0-9] to match any digit. All regular expression special characters work as specified in Section 9.7.3, except for . which is taken as a separator as mentioned above, * which is translated to the regular-expression notation .*, ? which is translated to ., and $ which is matched literally. You can emulate these pattern characters at need by writing ? for ., (R+|) for R*, or (R|) for R?. $ is not needed as a regular-expression character since the pattern must match the whole name, unlike the usual interpretation of regular expressions (in other words, $ is automatically appended to your pattern). Write * at the beginning and/or end if you don't wish the pattern to be anchored. Note that within double quotes, all regular expression special characters lose their special meanings and are matched literally. Also, the regular expression special characters are matched literally in operator name patterns (i.e., the argument of \do).

When to use single quotes, double quotes, and backticks in MySQL

Backticks are generally used to indicate an identifier and as well be safe from accidentally using the Reserved Keywords.

For example:

Use `database`;

Here the backticks will help the server to understand that the database is in fact the name of the database, not the database identifier.

Same can be done for the table names and field names. This is a very good habit if you wrap your database identifier with backticks.

Check this answer to understand more about backticks.


Now about Double quotes & Single Quotes (Michael has already mentioned that).

But, to define a value you have to use either single or double quotes. Lets see another example.

INSERT INTO `tablename` (`id, `title`) VALUES ( NULL, title1);

Here I have deliberately forgotten to wrap the title1 with quotes. Now the server will take the title1 as a column name (i.e. an identifier). So, to indicate that it's a value you have to use either double or single quotes.

INSERT INTO `tablename` (`id, `title`) VALUES ( NULL, 'title1');

Now, in combination with PHP, double quotes and single quotes make your query writing time much easier. Let's see a modified version of the query in your question.

$query = "INSERT INTO `table` (`id`, `col1`, `col2`) VALUES (NULL, '$val1', '$val2')";

Now, using double quotes in the PHP, you will make the variables $val1, and $val2 to use their values thus creating a perfectly valid query. Like

$val1 = "my value 1";
$val2 = "my value 2";
$query = "INSERT INTO `table` (`id`, `col1`, `col2`) VALUES (NULL, '$val1', '$val2')";

will make

INSERT INTO `table` (`id`, `col1`, `col2`) VALUES (NULL, 'my value 1', 'my value 2')

UIAlertView first deprecated IOS 9

Make UIAlertController+AlertController Category as:

UIAlertController+AlertController.h

typedef void (^UIAlertCompletionBlock) (UIAlertController *alertViewController, NSInteger buttonIndex);

@interface UIAlertController (AlertController)

+ (instancetype)showAlertIn:(UIViewController *)controller
                  WithTitle:(NSString *)title
                    message:(NSString *)message
          cancelButtonTitle:(NSString *)cancelButtonTitle
          otherButtonTitles:(NSString *)otherButtonTitle
                   tapBlock:(UIAlertCompletionBlock)tapBlock;
@end

UIAlertController+AlertController.m

@implementation UIAlertController (NTAlertController)

+ (instancetype)showAlertIn:(UIViewController *)controller
                  WithTitle:(NSString *)title
                    message:(NSString *)message
          cancelButtonTitle:(NSString *)cancelButtonTitle
          otherButtonTitles:(NSString *)otherButtonTitle
                   tapBlock:(UIAlertCompletionBlock)tapBlock {

    UIAlertController *alertController = [self alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];

    if(cancelButtonTitle != nil) {

        UIAlertAction *cancelButton = [UIAlertAction
                                       actionWithTitle:cancelButtonTitle
                                       style:UIAlertActionStyleCancel
                                       handler:^(UIAlertAction *action)
                                       {
                                           tapBlock(alertController, ALERTACTION_CANCEL); // CANCEL BUTTON CALL BACK ACTION
                                       }];
        [alertController addAction:cancelButton];

    }

    if(otherButtonTitle != nil) {

        UIAlertAction *otherButton = [UIAlertAction
                                   actionWithTitle:otherButtonTitle
                                   style:UIAlertActionStyleDefault
                                   handler:^(UIAlertAction *action)
                                   {
                                       tapBlock(alertController, ALERTACTION_OTHER); // OTHER BUTTON CALL BACK ACTION
                                   }];

        [alertController addAction:otherButton];
    }

    [controller presentViewController:alertController animated:YES completion:nil];

    return alertController;
}

@end

in your ViewController.m

[UIAlertController showAlertIn:self WithTitle:@"" message:@"" cancelButtonTitle:@"Cancel" otherButtonTitles:@"Other" tapBlock:^(UIAlertController *alertController, NSInteger index){

 if(index == ALERTACTION_CANCEL){

 // CANCEL BUTTON ACTION
 }else
if(index == ALERTACTION_OTHER){

 // OTHER BUTTON ACTION
 }

 [alertController dismissViewControllerAnimated:YES completion:nil];

 }];

NOTE: If you want to add more than two buttons then add another more UIAlertAction to the UIAlertController.

Have a reloadData for a UITableView animate when changing

Native UITableView animations in Swift

Insert and delete rows all at once with tableView.performBatchUpdates so they occur simultaneously. Building on the answer from @iKenndac use methods such as:

  • tableView.insertSections
  • tableView.insertRows
  • tableView.deleteSections
  • tableView.deleteRows

Ex:

 tableView.performBatchUpdates({
   tableView.insertSections([0], with: .top)
 })

This inserts a section at the zero position with an animation that loads from the top. This will re-run the cellForRowAt method and check for a new cell at that position. You could reload the entire table view this way with specific animations.

Re: the OP question, a conditional flag would have been needed to show the cells for the alternate table view state.

How do I find a list of Homebrew's installable packages?

From the man page:

search, -S text|/text/
Perform a substring search of formula names for text. If text is surrounded with slashes,
then it is interpreted as a regular expression. If no search term is given,
all available formula are displayed.

For your purposes, brew search will suffice.

Run chrome in fullscreen mode on Windows

Running chrome.exe --start-fullscreen --app=https://google.com will not get you Chrome in fullscreen, but in kiosk mode.

However, running chrome --start-fullscreen --app=https://google.com (notice : it's chrome instead of chrome.exe) worked in my case.

How to use Switch in SQL Server

    select 
       @selectoneCount = case @Temp
       when 1 then (@selectoneCount+1)
       when 2 then (@selectoneCount+1)
       end

   select  @selectoneCount 

What is an HttpHandler in ASP.NET

An HttpHandler (or IHttpHandler) is basically anything that is responsible for serving content. An ASP.NET page (aspx) is a type of handler.

You might write your own, for example, to serve images etc from a database rather than from the web-server itself, or to write a simple POX service (rather than SOAP/WCF/etc)

Using jQuery to center a DIV on the screen

I like adding functions to jQuery so this function would help:

jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", Math.max(0, (($(window).height() - $(this).outerHeight()) / 2) + 
                                                $(window).scrollTop()) + "px");
    this.css("left", Math.max(0, (($(window).width() - $(this).outerWidth()) / 2) + 
                                                $(window).scrollLeft()) + "px");
    return this;
}

Now we can just write:

$(element).center();

Demo: Fiddle (with added parameter)

CustomErrors mode="Off"

Also make sure you're editing web.config and not website.config, as I was doing.

Using the "start" command with parameters passed to the started program

Put the command inside a batch file, and call that with the parameters.

Also, did you try this yet? (Move end quote to encapsulate parameters)

start "c:\program files\Microsoft Virtual PC\Virtual PC.exe -pc MY-PC -launch"

Java Replace Character At Specific Position Of String?

Petar Ivanov's answer to replace a character at a specific index in a string question

String are immutable in Java. You can't change them.

You need to create a new string with the character replaced.

String myName = "domanokz";
String newName = myName.substring(0,4)+'x'+myName.substring(5);

Or you can use a StringBuilder:

StringBuilder myName = new StringBuilder("domanokz");
myName.setCharAt(4, 'x');

System.out.println(myName);

Write to CSV file and export it?

Here's a very simple free open-source CsvExport class for C#. There's an ASP.NET MVC example at the bottom.

https://github.com/jitbit/CsvExport

It takes care about line-breaks, commas, escaping quotes, MS Excel compatibilty... Just add one short .cs file to your project and you're good to go.

(disclaimer: I'm one of the contributors)

Can I get image from canvas element and use it in img src tag?

Corrected the Fiddle - updated shows the Image duplicated into the Canvas...

And right click can be saved as a .PNG

http://jsfiddle.net/gfyWK/67/

<div style="text-align:center">
<img src="http://imgon.net/di-M7Z9.jpg" id="picture" style="display:none;" />
<br />
<div id="for_jcrop">here the image should apear</div>
<canvas id="rotate" style="border:5px double black; margin-top:5px; "></canvas>
</div>

Plus the JS on the fiddle page...

Cheers Si

Currently looking at saving this to File on the server --- ASP.net C# (.aspx web form page) Any advice would be cool....

Retrieving subfolders names in S3 bucket from boto3

The big realisation with S3 is that there are no folders/directories just keys. The apparent folder structure is just prepended to the filename to become the 'Key', so to list the contents of myBucket's some/path/to/the/file/ you can try:

s3 = boto3.client('s3')
for obj in s3.list_objects_v2(Bucket="myBucket", Prefix="some/path/to/the/file/")['Contents']:
    print(obj['Key'])

which would give you something like:

some/path/to/the/file/yo.jpg
some/path/to/the/file/meAndYou.gif
...

What is sr-only in Bootstrap 3?

According to bootstrap's documentation, the class is used to hide information intended only for screen readers from the layout of the rendered page.

Screen readers will have trouble with your forms if you don't include a label for every input. For these inline forms, you can hide the labels using the .sr-only class.

Here is an example styling used:

.sr-only {
  position: absolute;
  width: 1px;
  height: 1px;
  padding: 0;
  margin: -1px;
  overflow: hidden;
  clip: rect(0,0,0,0);
  border: 0;
}

Is it important or can I remove it? Works fine without.

It's important, don't remove it.

You should always consider screen readers for accessibility purposes. Usage of the class will hide the element anyways, therefore you shouldn't see a visual difference.

If you're interested in reading about accessibility:

Extending the User model with custom fields in Django

There is an official recommendation on storing additional information about users. The Django Book also discusses this problem in section Profiles.

How to convert Varchar to Double in sql?

This might be more desirable, that is use float instead

SELECT fullName, CAST(totalBal as float) totalBal FROM client_info ORDER BY totalBal DESC

How can you encode a string to Base64 in JavaScript?

From here:

/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*
**/
var Base64 = {

// private property
_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

// public method for encoding
encode : function (input) {
    var output = "";
    var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
    var i = 0;

    input = Base64._utf8_encode(input);

    while (i < input.length) {

        chr1 = input.charCodeAt(i++);
        chr2 = input.charCodeAt(i++);
        chr3 = input.charCodeAt(i++);

        enc1 = chr1 >> 2;
        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
        enc4 = chr3 & 63;

        if (isNaN(chr2)) {
            enc3 = enc4 = 64;
        } else if (isNaN(chr3)) {
            enc4 = 64;
        }

        output = output +
        this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
        this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

    }

    return output;
},

// public method for decoding
decode : function (input) {
    var output = "";
    var chr1, chr2, chr3;
    var enc1, enc2, enc3, enc4;
    var i = 0;

    input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

    while (i < input.length) {

        enc1 = this._keyStr.indexOf(input.charAt(i++));
        enc2 = this._keyStr.indexOf(input.charAt(i++));
        enc3 = this._keyStr.indexOf(input.charAt(i++));
        enc4 = this._keyStr.indexOf(input.charAt(i++));

        chr1 = (enc1 << 2) | (enc2 >> 4);
        chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
        chr3 = ((enc3 & 3) << 6) | enc4;

        output = output + String.fromCharCode(chr1);

        if (enc3 != 64) {
            output = output + String.fromCharCode(chr2);
        }
        if (enc4 != 64) {
            output = output + String.fromCharCode(chr3);
        }

    }

    output = Base64._utf8_decode(output);

    return output;

},

// private method for UTF-8 encoding
_utf8_encode : function (string) {
    string = string.replace(/\r\n/g,"\n");
    var utftext = "";

    for (var n = 0; n < string.length; n++) {

        var c = string.charCodeAt(n);

        if (c < 128) {
            utftext += String.fromCharCode(c);
        }
        else if((c > 127) && (c < 2048)) {
            utftext += String.fromCharCode((c >> 6) | 192);
            utftext += String.fromCharCode((c & 63) | 128);
        }
        else {
            utftext += String.fromCharCode((c >> 12) | 224);
            utftext += String.fromCharCode(((c >> 6) & 63) | 128);
            utftext += String.fromCharCode((c & 63) | 128);
        }

    }

    return utftext;
},

// private method for UTF-8 decoding
_utf8_decode : function (utftext) {
    var string = "";
    var i = 0;
    var c = c1 = c2 = 0;

    while ( i < utftext.length ) {

        c = utftext.charCodeAt(i);

        if (c < 128) {
            string += String.fromCharCode(c);
            i++;
        }
        else if((c > 191) && (c < 224)) {
            c2 = utftext.charCodeAt(i+1);
            string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
            i += 2;
        }
        else {
            c2 = utftext.charCodeAt(i+1);
            c3 = utftext.charCodeAt(i+2);
            string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
            i += 3;
        }

    }

    return string;
}

}

Also, search on "javascript base64 encoding" turns a lot of other options, the above was the first one.

Google Maps shows "For development purposes only"

Now google maps is free for development only.

If you want to use map free like earlier, then create an account with valid details (billing, payment, etc.) google gives $200 MONTHLY CREDIT Which is EQUIVALENT To FREE USAGE

For more details please see Googles new price details: google map new pricing

Also see the old price details: Old one

How to pass "Null" (a real surname!) to a SOAP web service in ActionScript 3

@doc_180 had the right concept, except he is focused on numbers, whereas the original poster had issues with strings.

The solution is to change the mx.rpc.xml.XMLEncoder file. This is line 121:

    if (content != null)
        result += content;

(I looked at Flex 4.5.1 SDK; line numbers may differ in other versions.)

Basically, the validation fails because 'content is null' and therefore your argument is not added to the outgoing SOAP Packet; thus causing the missing parameter error.

You have to extend this class to remove the validation. Then there is a big snowball up the chain, modifying SOAPEncoder to use your modified XMLEncoder, and then modifying Operation to use your modified SOAPEncoder, and then moidfying WebService to use your alternate Operation class.

I spent a few hours on it, but I need to move on. It'll probably take a day or two.

You may be able to just fix the XMLEncoder line and do some monkey patching to use your own class.

I'll also add that if you switch to using RemoteObject/AMF with ColdFusion, the null is passed without problems.


11/16/2013 update:

I have one more recent addition to my last comment about RemoteObject/AMF. If you are using ColdFusion 10; then properties with a null value on an object are removed from the server-side object. So, you have to check for the properties existence before accessing it or you will get a runtime error.

Check like this:

<cfif (structKeyExists(arguments.myObject,'propertyName')>
 <!--- no property code --->
<cfelse>
 <!--- handle property  normally --->
</cfif>

This is a change in behavior from ColdFusion 9; where the null properties would turn into empty strings.


Edit 12/6/2013

Since there was a question about how nulls are treated, here is a quick sample application to demonstrate how a string "null" will relate to the reserved word null.

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
               xmlns:s="library://ns.adobe.com/flex/spark"
               xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600" initialize="application1_initializeHandler(event)">
    <fx:Script>
        <![CDATA[
            import mx.events.FlexEvent;

            protected function application1_initializeHandler(event:FlexEvent):void
            {
                var s :String = "null";
                if(s != null){
                    trace('null string is not equal to null reserved word using the != condition');
                } else {
                    trace('null string is equal to null reserved word using the != condition');
                }

                if(s == null){
                    trace('null string is equal to null reserved word using the == condition');
                } else {
                    trace('null string is not equal to null reserved word using the == condition');
                }

                if(s === null){
                    trace('null string is equal to null reserved word using the === condition');
                } else {
                    trace('null string is not equal to null reserved word using the === condition');
                }
            }
        ]]>
    </fx:Script>
    <fx:Declarations>
        <!-- Place non-visual elements (e.g., services, value objects) here -->
    </fx:Declarations>
</s:Application>

The trace output is:

null string is not equal to null reserved word using the != condition

null string is not equal to null reserved word using the == condition

null string is not equal to null reserved word using the === condition

Apache Name Virtual Host with SSL

Apache doesn't support SSL on name-based virtual host, only on IP based Virtual Hosts.

Source: Apache 2.2 SSL FAQ question Why is it not possible to use Name-Based Virtual Hosting to identify different SSL virtual hosts?

Unlike SSL, the TLS specification allows for name-based hosts (SNI as mentioned by someone else), but Apache doesn't yet support this feature. It supposedly will in a future release when compiled against openssl 0.9.8.

Also, mod_gnutls claims to support SNI, but I've never actually tried it.

How to exclude rows that don't join with another table?

If you want to select the columns from First Table "which are also present in Second table, then in this case you can also use EXCEPT. In this case, column names can be different as well but data type should be same.

Example:

select ID, FName
from FirstTable
EXCEPT
select ID, SName
from SecondTable

Mac install and open mysql using terminal

This command works for me:

./mysql -u root -p

(PS: I'm working on mac through terminal)

How can I add a table of contents to a Jupyter / JupyterLab notebook?

JupyterLab ToC instructions

There are already many good answers to this question, but they often require tweaks to work properly with notebooks in JupyterLab. I wrote this answer to detail the possible ways of including a ToC in a notebook while working in and exporting from JupyterLab.

As a side panel

The jupyterlab-toc extension adds the ToC as a side panel that can number headings, collapse sections, and be used for navigation (see gif below for a demo). This extension is included by default since JupyterLab 3.0, in older version you can install it with the following command

jupyter labextension install @jupyterlab/toc

enter image description here


In the notebook as a cell

At the time being, this can either be done manually as in Matt Dancho's answer, or automatically via the toc2 jupyter notebook extension in the classic notebook interface.

First, install toc2 as part of the jupyter_contrib_nbextensions bundle:

conda install -c conda-forge jupyter_contrib_nbextensions

Then, launch JupyterLab, go to Help --> Launch Classic Notebook, and open the notebook in which you want to add the ToC. Click the toc2 symbol in the toolbar to bring up the floating ToC window (see the gif below if you can't find it), click the gear icon and check the box for "Add notebook ToC cell". Save the notebook and the ToC cell will be there when you open it in JupyterLab. The inserted cell is a markdown cell with html in it, it will not update automatically.

The default options of the toc2 can be configured in the "Nbextensions" tab in the classic notebook launch page. You can e.g. choose to number headings and to anchor the ToC as a side bar (which I personally think looks cleaner).

enter image description here


In an exported HTML file

nbconvert can be used to export notebooks to HTML following rules of how to format the exported HTML. The toc2 extension mentioned above adds an export format called html_toc, which can be used directly with nbconvert from the command line (after the toc2 extension has been installed):

jupyter nbconvert file.ipynb --to html_toc
# Append `--ExtractOutputPreprocessor.enabled=False`
# to get a single html file instead of a separate directory for images

Remember that shell commands can be added to notebook cells by prefacing them with an exclamation mark !, so you can stick this line in the last cell of the notebook and always have an HTML file with a ToC generated when you hit "Run all cells" (or whatever output you desire from nbconvert). This way, you could use jupyterlab-toc to navigate the notebook while you are working, and still get ToCs in the exported output without having to resort to using the classic notebook interface (for the purists among us).

Note that configuring the default toc2 options as described above, will not change the format of nbconver --to html_toc. You need to open the notebook in the classic notebook interface for the metadata to be written to the .ipynb file (nbconvert reads the metadata when exporting) Alternatively, you can add the metadata manually via the Notebook tools tab of the JupyterLab sidebar, e.g. something like:

    "toc": {
        "number_sections": false,
        "sideBar": true
    }

If you prefer a GUI-driven approach, you should be able to open the classic notebook and click File --> Save as HTML (with ToC) (although note that this menu item was not available for me).


The gifs above are linked from the respective documentation of the extensions.

Pass request headers in a jQuery AJAX GET call

Use beforeSend:

$.ajax({
         url: "http://localhost/PlatformPortal/Buyers/Account/SignIn",
         data: { signature: authHeader },
         type: "GET",
         beforeSend: function(xhr){xhr.setRequestHeader('X-Test-Header', 'test-value');},
         success: function() { alert('Success!' + authHeader); }
      });

http://api.jquery.com/jQuery.ajax/

http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader-method

MySQL config file location - redhat linux server

it is located at /etc/mysql/my.cnf

How to create a custom-shaped bitmap marker with Android map API v2

From lambda answer, I have made something closer to the requirements.

boolean imageCreated = false;

Bitmap bmp = null;
Marker currentLocationMarker;
private void doSomeCustomizationForMarker(LatLng currentLocation) {
    if (!imageCreated) {
        imageCreated = true;
        Bitmap.Config conf = Bitmap.Config.ARGB_8888;
        bmp = Bitmap.createBitmap(400, 400, conf);
        Canvas canvas1 = new Canvas(bmp);

        Paint color = new Paint();
        color.setTextSize(30);
        color.setColor(Color.WHITE);

        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inMutable = true;

        Bitmap imageBitmap=BitmapFactory.decodeResource(getResources(),
                R.drawable.messi,opt);
        Bitmap resized = Bitmap.createScaledBitmap(imageBitmap, 320, 320, true);
        canvas1.drawBitmap(resized, 40, 40, color);

        canvas1.drawText("Le Messi", 30, 40, color);

        currentLocationMarker = mMap.addMarker(new MarkerOptions().position(currentLocation)
                .icon(BitmapDescriptorFactory.fromBitmap(bmp))
                // Specifies the anchor to be at a particular point in the marker image.
                .anchor(0.5f, 1));
    } else {
        currentLocationMarker.setPosition(currentLocation);
    }

}

Sharing a variable between multiple different threads

In addition to the other suggestions - you can also wrap the flag in a control class and make a final instance of it in your parent class:

public class Test {
  class Control {
    public volatile boolean flag = false;
  }
  final Control control = new Control();

  class T1 implements Runnable {
    @Override
    public void run() {
      while ( !control.flag ) {

      }
    }
  }

  class T2 implements Runnable {
    @Override
    public void run() {
      while ( !control.flag ) {

      }
    }
  }

  private void test() {
    T1 main = new T1();
    T2 help = new T2();

    new Thread(main).start();
    new Thread(help).start();
  }

  public static void main(String[] args) throws InterruptedException {
    try {
      Test test = new Test();
      test.test();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

JDBC connection to MSSQL server in windows authentication mode

From your exception trace, it looks like there is multiple possibility for this problem

1). You have to check that your port "1433" is blocked by firewall or not. If you find that it is blocked then you should have to write "Inbound Rule". It if found in control panel -> windows firewall -> Advance Setting (Option found at Left hand side) -> Inbound Rule.

2). In SQL Server configuration Manager, your TCP/IP protocol will find in disable mode. So, you should have to enable it.

PHP file_get_contents() and setting request headers

Yes.

When calling file_get_contents on a URL, one should use the stream_create_context function, which is fairly well documented on php.net.

This is more or less exactly covered on the following page at php.net in the user comments section: http://php.net/manual/en/function.stream-context-create.php

Loading a properties file from Java package

The following two cases relate to loading a properties file from an example class named TestLoadProperties.

Case 1: Loading the properties file using ClassLoader

InputStream inputStream = TestLoadProperties.class.getClassLoader()
                          .getResourceAsStream("A.config");
properties.load(inputStream);

In this case the properties file must be in the root/src directory for successful loading.

Case 2: Loading the properties file without using ClassLoader

InputStream inputStream = getClass().getResourceAsStream("A.config");
properties.load(inputStream);

In this case the properties file must be in the same directory as the TestLoadProperties.class file for successful loading.

Note: TestLoadProperties.java and TestLoadProperties.class are two different files. The former, .java file, is usually found in a project's src/ directory, while the latter, .class file, is usually found in its bin/ directory.

Is it possible to use Visual Studio on macOS?

Yes, you can! There's a Visual Studio for macs and there's Visual Studio Code if you only need a text editor like Sublime Text.

Assign variable value inside if-statement

Yes, you can assign the value of variable inside if.

I wouldn't recommend it. The problem is, it looks like a common error where you try to compare values, but use a single = instead of == or ===.

It will be better if you do something like this:

int v;
if((v = someMethod()) != 0) 
   return true;

How to return Json object from MVC controller to view

<script type="text/javascript">
jQuery(function () {
    var container = jQuery("\#content");
    jQuery(container)
     .kendoGrid({
         selectable: "single row",
         dataSource: new kendo.data.DataSource({
             transport: {
                 read: {
                     url: "@Url.Action("GetMsgDetails", "OutMessage")" + "?msgId=" + msgId,
                     dataType: "json",
                 },
             },
             batch: true,
         }),
         editable: "popup",
         columns: [
            { field: "Id", title: "Id", width: 250, hidden: true },
            { field: "Data", title: "Message Body", width: 100 },
           { field: "mobile", title: "Mobile Number", width: 100 },
         ]
     });
});

Why aren't Xcode breakpoints functioning?

You can check one setting in target setting Apple LLVM Compiler 4.1 Code Generation Section Generate Debug Symbol = YES

How to show the text on a ImageButton?

Actually, android:text is not an argument accepted by ImageButton but, If you're trying to get a button with a specified background (not android default) use the android:background xml attribute, or declare it from the class with .setBackground();

Add primary key to existing table

Please try this-

ALTER TABLE TABLE_NAME DROP INDEX `PRIMARY`, ADD PRIMARY KEY (COLUMN1, COLUMN2,..);

clear table jquery

I needed this:

$('#myTable tbody > tr').remove();

It deletes all rows except the header.

Convert an integer to a byte array

Sorry, this might be a bit late. But I think I found a better implementation on the go docs.

buf := new(bytes.Buffer)
var num uint16 = 1234
err := binary.Write(buf, binary.LittleEndian, num)
if err != nil {
    fmt.Println("binary.Write failed:", err)
}
fmt.Printf("% x", buf.Bytes())

Responsively change div size keeping aspect ratio

(function( $ ) {
  $.fn.keepRatio = function(which) {
      var $this = $(this);
      var w = $this.width();
      var h = $this.height();
      var ratio = w/h;
      $(window).resize(function() {
          switch(which) {
              case 'width':
                  var nh = $this.width() / ratio;
                  $this.css('height', nh + 'px');
                  break;
              case 'height':
                  var nw = $this.height() * ratio;
                  $this.css('width', nw + 'px');
                  break;
          }
      });

  }
})( jQuery );      

$(document).ready(function(){
    $('#foo').keepRatio('width');
});

Working example: http://jsfiddle.net/QtftX/1/

What is the difference between SOAP 1.1, SOAP 1.2, HTTP GET & HTTP POST methods for Android?

Differences in SOAP versions

Both SOAP Version 1.1 and SOAP Version 1.2 are World Wide Web Consortium (W3C) standards. Web services can be deployed that support not only SOAP 1.1 but also support SOAP 1.2. Some changes from SOAP 1.1 that were made to the SOAP 1.2 specification are significant, while other changes are minor.

The SOAP 1.2 specification introduces several changes to SOAP 1.1. This information is not intended to be an in-depth description of all the new or changed features for SOAP 1.1 and SOAP 1.2. Instead, this information highlights some of the more important differences between the current versions of SOAP.

The changes to the SOAP 1.2 specification that are significant include the following updates: SOAP 1.1 is based on XML 1.0. SOAP 1.2 is based on XML Information Set (XML Infoset). The XML information set (infoset) provides a way to describe the XML document with XSD schema. However, the infoset does not necessarily serialize the document with XML 1.0 serialization on which SOAP 1.1 is based.. This new way to describe the XML document helps reveal other serialization formats, such as a binary protocol format. You can use the binary protocol format to compact the message into a compact format, where some of the verbose tagging information might not be required.

In SOAP 1.2 , you can use the specification of a binding to an underlying protocol to determine which XML serialization is used in the underlying protocol data units. The HTTP binding that is specified in SOAP 1.2 - Part 2 uses XML 1.0 as the serialization of the SOAP message infoset.

SOAP 1.2 provides the ability to officially define transport protocols, other than using HTTP, as long as the vendor conforms to the binding framework that is defined in SOAP 1.2. While HTTP is ubiquitous, it is not as reliable as other transports including TCP/IP and MQ. SOAP 1.2 provides a more specific definition of the SOAP processing model that removes many of the ambiguities that might lead to interoperability errors in the absence of the Web Services-Interoperability (WS-I) profiles. The goal is to significantly reduce the chances of interoperability issues between different vendors that use SOAP 1.2 implementations. SOAP with Attachments API for Java (SAAJ) can also stand alone as a simple mechanism to issue SOAP requests. A major change to the SAAJ specification is the ability to represent SOAP 1.1 messages and the additional SOAP 1.2 formatted messages. For example, SAAJ Version 1.3 introduces a new set of constants and methods that are more conducive to SOAP 1.2 (such as getRole(), getRelay()) on SOAP header elements. There are also additional methods on the factories for SAAJ to create appropriate SOAP 1.1 or SOAP 1.2 messages. The XML namespaces for the envelope and encoding schemas have changed for SOAP 1.2. These changes distinguish SOAP processors from SOAP 1.1 and SOAP 1.2 messages and supports changes in the SOAP schema, without affecting existing implementations. Java Architecture for XML Web Services (JAX-WS) introduces the ability to support both SOAP 1.1 and SOAP 1.2. Because JAX-RPC introduced a requirement to manipulate a SOAP message as it traversed through the run time, there became a need to represent this message in its appropriate SOAP context. In JAX-WS, a number of additional enhancements result from the support for SAAJ 1.3.

There is not difine POST AND GET method for particular android....but all here is differance

GET The GET method appends name/value pairs to the URL, allowing you to retrieve a resource representation. The big issue with this is that the length of a URL is limited (roughly 3000 char) resulting in data loss should you have to much stuff in the form on your page, so this method only works if there is a small number parameters.

What does this mean for me? Basically this renders the GET method worthless to most developers in most situations. Here is another way of looking at it: the URL could be truncated (and most likely will be give today's data-centric sites) if the form uses a large number of parameters, or if the parameters contain large amounts of data. Also, parameters passed on the URL are visible in the address field of the browser (YIKES!!!) not the best place for any kind of sensitive (or even non-sensitive) data to be shown because you are just begging the curious user to mess with it.

POST The alternative to the GET method is the POST method. This method packages the name/value pairs inside the body of the HTTP request, which makes for a cleaner URL and imposes no size limitations on the forms output, basically its a no-brainer on which one to use. POST is also more secure but certainly not safe. Although HTTP fully supports CRUD, HTML 4 only supports issuing GET and POST requests through its various elements. This limitation has held Web applications back from making full use of HTTP, and to work around it, most applications overload POST to take care of everything but resource retrieval.

Link to original IBM source

How can you tell when a layout has been drawn?

To avoid deprecated code and warnings you can use:

view.getViewTreeObserver().addOnGlobalLayoutListener(
        new ViewTreeObserver.OnGlobalLayoutListener() {
            @SuppressWarnings("deprecation")
            @Override
            public void onGlobalLayout() {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    view.getViewTreeObserver()
                            .removeOnGlobalLayoutListener(this);
                } else {
                    view.getViewTreeObserver()
                            .removeGlobalOnLayoutListener(this);
                }
                yourFunctionHere();
            }
        });

Vertical Tabs with JQuery?

super simple function that will allow you to create your own tab / accordion structure here: http://jsfiddle.net/nabeezy/v36DF/

bindSets = function (tabClass, tabClassActive, contentClass, contentClassHidden) {
        //Dependent on jQuery
        //PARAMETERS
        //tabClass: 'the class name of the DOM elements that will be clicked',
        //tabClassActive: 'the class name that will be applied to the active tabClass element when clicked (must write your own css)',
        //contentClass: 'the class name of the DOM elements that will be modified when the corresponding tab is clicked',
        //contentClassHidden: 'the class name that will be applied to all contentClass elements except the active one (must write your own css)',
        //MUST call bindSets() after dom has rendered

        var tabs = $('.' + tabClass);
        var tabContent = $('.' + contentClass);
        if(tabs.length !== tabContent.length){console.log('JS bindSets: sets contain a different number of elements')};
        tabs.each(function (index) {
            this.matchedElement = tabContent[index];
            $(this).click(function () {
                tabs.each(function () {
                    this.classList.remove(tabClassActive);
                });
                tabContent.each(function () {
                    this.classList.add(contentClassHidden);
                });
                this.classList.add(tabClassActive);
                this.matchedElement.classList.remove(contentClassHidden);
            });
        })
        tabContent.each(function () {
            this.classList.add(contentClassHidden);
        });

        //tabs[0].click();
    }
bindSets('tabs','active','content','hidden');

Moment js get first and last day of current month

As simple we can use daysInMonth() and endOf()

const firstDay = moment('2016-09-15 00:00', 'YYYY-MM-DD h:m').startOf('month').format('D')
const lastDay = moment('2016-09-15 00:00', 'YYYY-MM-DD h:m').endOf('month').format('D')

Swift Open Link in Safari

since iOS 10 you should use:

guard let url = URL(string: linkUrlString) else {
    return
}
    
if #available(iOS 10.0, *) {
    UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
    UIApplication.shared.openURL(url)
}

Window vs Page vs UserControl for WPF navigation?

Most of all has posted correct answer. I would like to add few links, so that you can refer to them and have clear and better ideas about the same:

UserControl: http://msdn.microsoft.com/en-IN/library/a6h7e207(v=vs.71).aspx

The difference between page and window with respect to WPF: Page vs Window in WPF?

Alter a MySQL column to be AUTO_INCREMENT

Setting column as primary key and auto_increment at the same time:

  mysql> ALTER TABLE persons MODIFY COLUMN personID INT auto_increment PRIMARY KEY;
    Query OK, 10 rows affected (0.77 sec)
    Records: 10  Duplicates: 0  Warnings: 0

    mysql>

How to insert an element after another element in JavaScript without using a library?

2018 Solution (Bad Practice, go to 2020)

I know this question is Ancient, but for any future users, heres a modified prototype this is just a micro polyfill for the .insertAfter function that doesnt exist this prototype directly adds a new function baseElement.insertAfter(element); to the Element prototype:

Element.prototype.insertAfter = function(new) {
    this.parentNode.insertBefore(new, this.nextSibling);
}

Once youve placed the polyfill in a library, gist, or just in your code (or anywhere else where it can be referenced) Just write document.getElementById('foo').insertAfter(document.createElement('bar'));


2019 Solution (Ugly, go to 2020)

You SHOULD NOT USE PROTOTYPES. They overwrite the default codebase and arent very efficient or safe and can cause compatibility errors, but if its for non-commercial projects, it shouldnt matter. if you want a safe function for commercial use, just use a default function. its not pretty but it works:

function insertAfter(el, newEl) {
    el.parentNode.insertBefore(newEl, this.nextSibling);
}

// use

const el = document.body || document.querySelector("body");
// the || means "this OR that"

el.insertBefore(document.createElement("div"), el.nextSibling);
// Insert Before

insertAfter(el, document.createElement("div"));
// Insert After 

2020 Solution

Current Web Standards for ChildNode: https://developer.mozilla.org/en-US/docs/Web/API/ChildNode

Its currently in the Living Standards and is SAFE.

For Unsupported Browsers, use this Polyfill: https://github.com/seznam/JAK/blob/master/lib/polyfills/childNode.js

Someone mentioned that the Polyfill uses Protos, when I said they were bad practice. They are, especially when they are used blindly and overwrited, like with my 2018 solution. However, that polyfill is on the MDN Documentation and uses a kind of initialization and execution that is safer.

How to use the 2020 Solution:

// Parent Element
const el = document.querySelector(".class");

// Create New Element
const newEl = document.createElement("div");
newEl.id = "foo";

// Insert New Element BEFORE an Element
el.before(newEl);

// Insert New Element AFTER an Element
el.after(newEl);

// Remove an Element
el.remove();

// Even though it’s a created element,
// newEl is still a reference to the HTML,
// so using .remove() on it should work
// if you have already appended it somewhere
newEl.remove();

Git: Pull from other remote

git pull is really just a shorthand for git pull <remote> <branchname>, in most cases it's equivalent to git pull origin master. You will need to add another remote and pull explicitly from it. This page describes it in detail:

http://help.github.com/forking/

How do I disable fail_on_empty_beans in Jackson?

ObjectMapper mapper = new ObjectMapper();

Hi,

When I use mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)

My json object values come '' blank in angular page mean in response

Solved with the help of only below settings

mapper.setVisibility(mapper.getSerializationConfig().getDefaultVisibilityChecker().
withFieldVisibility(JsonAutoDetect.Visibility.ANY).withGetterVisibility(JsonAutoDetect.Visibility.NONE)
                .withSetterVisibility(JsonAutoDetect.Visibility.NONE)
                .withCreatorVisibility(JsonAutoDetect.Visibility.NONE));

How to count the number of words in a sentence, ignoring numbers, punctuation and whitespace?

Ok here is my version of doing this. I noticed that you want your output to be 7, which means you dont want to count special characters and numbers. So here is regex pattern:

re.findall("[a-zA-Z_]+", string)

Where [a-zA-Z_] means it will match any character beetwen a-z (lowercase) and A-Z (upper case).


About spaces. If you want to remove all extra spaces, just do:

string = string.rstrip().lstrip() # Remove all extra spaces at the start and at the end of the string
while "  " in string: # While  there are 2 spaces beetwen words in our string...
    string = string.replace("  ", " ") # ... replace them by one space!

LogisticRegression: Unknown label type: 'continuous' using sklearn in python

LogisticRegression is not for regression but classification !

The Y variable must be the classification class,

(for example 0 or 1)

And not a continuous variable,

that would be a regression problem.

How to use graphics.h in codeblocks?

  1. First download WinBGIm from http://winbgim.codecutter.org/ Extract it.
  2. Copy graphics.h and winbgim.h files in include folder of your compiler directory
  3. Copy libbgi.a to lib folder of your compiler directory
  4. In code::blocks open Settings >> Compiler and debugger >>linker settings click Add button in link libraries part and browse and select libbgi.a file
  5. In right part (i.e. other linker options) paste commands -lbgi -lgdi32 -lcomdlg32 -luuid -loleaut32 -lole32
  6. Click OK

For detail information follow this link.

Clearing state es6 React

I will add to the above answer that the reset function should also assign state like so:

reset() {
  this.state = initialState;
  this.setState(initialState);
}

The reason being that if your state picks up a property that wasn't in the initial state, that key/value won't be cleared out, as setState just updates existing keys. Assignment is not enough to get the component to re-render, so include the setState call as well -- you could even get away with this.setState({}) after the assignment.

Run a script in Dockerfile

WORKDIR /scripts
COPY bootstrap.sh .
RUN ./bootstrap.sh 

How to change the URL from "localhost" to something else, on a local system using wampserver?

After another hour or two I can actually answer my own question.

Someone on another forum mentioned that you need to keep a mention of plain ol' localhost in the httpd-vhost.conf file, so here's what I ended up with in there:

ServerName localhost

DocumentRoot "c:/wamp/www/"

DocumentRoot "C:/wamp/www/pocket/"
ServerName pocket.clickng.com
ServerAlias pocket.clickng.com
ErrorLog "logs/pocket.clickng.com-error.log"
CustomLog "logs/pocket.clickng.com-access.log" common
<Directory "C:/wamp/www/pocket/">
    Options Indexes FollowSymLinks Includes
    AllowOverride All
    Order allow,deny
    Allow from all
</Directory>

Exit WAMP, restart - good to go. Hope this helps someone else :)

PHP checkbox set to check based on database value

This simplest ways is to add the "checked attribute.

<label for="tag_1">Tag 1</label>
<input type="checkbox" name="tag_1" id="tag_1" value="yes" 
    <?php if($tag_1_saved_value === 'yes') echo 'checked="checked"';?> />

How can I align text in columns using Console.WriteLine?

Try this

Console.WriteLine("{0,10}{1,10}{2,10}{3,10}{4,10}",
  customer[DisplayPos],
  sales_figures[DisplayPos],
  fee_payable[DisplayPos], 
  seventy_percent_value,
  thirty_percent_value);

where the first number inside the curly brackets is the index and the second is the alignment. The sign of the second number indicates if the string should be left or right aligned. Use negative numbers for left alignment.

Or look at http://msdn.microsoft.com/en-us/library/aa331875(v=vs.71).aspx

Change NULL values in Datetime format to empty string

This also works:

REPLACE(ISNULL(CONVERT(DATE, @date), ''), '1900-01-01', '') AS 'Your Date Field'

jQuery returning "parsererror" for ajax request

I was also getting "Request return with error:parsererror." in the javascript console. In my case it wasn´t a matter of Json, but I had to pass to the view text area a valid encoding.

  String encodedString = getEncodedString(text, encoding);
  view.setTextAreaContent(encodedString);

Java: How to convert List to Map

Without java-8, you'll be able to do this in one line Commons collections, and the Closure class

List<Item> list;
@SuppressWarnings("unchecked")
Map<Key, Item> map  = new HashMap<Key, Item>>(){{
    CollectionUtils.forAllDo(list, new Closure() {
        @Override
        public void execute(Object input) {
            Item item = (Item) input;
            put(i.getKey(), item);
        }
    });
}};

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

Mockito - difference between doReturn() and when()

Both approaches behave differently if you use a spied object (annotated with @Spy) instead of a mock (annotated with @Mock):

  • when(...) thenReturn(...) makes a real method call just before the specified value will be returned. So if the called method throws an Exception you have to deal with it / mock it etc. Of course you still get your result (what you define in thenReturn(...))

  • doReturn(...) when(...) does not call the method at all.

Example:

public class MyClass {
     protected String methodToBeTested() {
           return anotherMethodInClass();
     }

     protected String anotherMethodInClass() {
          throw new NullPointerException();
     }
}

Test:

@Spy
private MyClass myClass;

// ...

// would work fine
doReturn("test").when(myClass).anotherMethodInClass();

// would throw a NullPointerException
when(myClass.anotherMethodInClass()).thenReturn("test");

Sending a JSON HTTP POST request from Android

Posting parameters Using POST:-

URL url;
URLConnection urlConn;
DataOutputStream printout;
DataInputStream  input;
url = new URL (getCodeBase().toString() + "env.tcgi");
urlConn = url.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setUseCaches (false);
urlConn.setRequestProperty("Content-Type","application/json");   
urlConn.setRequestProperty("Host", "android.schoolportal.gr");
urlConn.connect();  
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");

The part which you missed is in the the following... i.e., as follows..

// Send POST output.
printout = new DataOutputStream(urlConn.getOutputStream ());
printout.writeBytes(URLEncoder.encode(jsonParam.toString(),"UTF-8"));
printout.flush ();
printout.close ();

The rest of the thing you can do it.

Is it possible to print a variable's type in standard C++?

Try:

#include <typeinfo>

// …
std::cout << typeid(a).name() << '\n';

You might have to activate RTTI in your compiler options for this to work. Additionally, the output of this depends on the compiler. It might be a raw type name or a name mangling symbol or anything in between.

What is the shortcut to Auto import all in Android Studio?

These are the shortcuts used in Android studio

Go to class CTRL + N
Go to file CTRL + Shift + N
Navigate open tabs ALT + Left-Arrow; ALT + Right-Arrow
Look up recent files CTRL + E
Go to line CTRL + G
Navigate to last edit location CTRL + SHIFT + BACKSPACE
Go to declaration CTRL + B
Go to implementation CTRL + ALT + B
Go to source F4
Go to super Class CTRL + U
Show Call hierarchy CTRL + ALT + H
Search in path/project CTRL + SHIFT + F

Programming Shortcuts:-

Reformat code CTRL + ALT + L
Optimize imports CTRL + ALT + O
Code Completion CTRL + SPACE
Issue quick fix ALT + ENTER
Surround code block CTRL + ALT + T
Rename and Refractor Shift + F6
Line Comment or Uncomment CTRL + /
Block Comment or Uncomment CTRL + SHIFT + /
Go to previous/next method ALT + UP/DOWN
Show parameters for method CTRL + P
Quick documentation lookup CTRL + Q
Delete a line CTRL + Y
View declaration in layout CTRL + B

For more info visit Things worked in Android

Declaring an enum within a class

In general, I always put my enums in a struct. I have seen several guidelines including "prefixing".

enum Color
{
  Clr_Red,
  Clr_Yellow,
  Clr_Blue,
};

Always thought this looked more like C guidelines than C++ ones (for one because of the abbreviation and also because of the namespaces in C++).

So to limit the scope we now have two alternatives:

  • namespaces
  • structs/classes

I personally tend to use a struct because it can be used as parameters for template programming while a namespace cannot be manipulated.

Examples of manipulation include:

template <class T>
size_t number() { /**/ }

which returns the number of elements of enum inside the struct T :)

Eclipse hangs on loading workbench

You have to delete org.eclipse.e4.workbench folder inside metadata.plugins\ which you can find in your workspace folder. Deleting this folder solved the problem for me, hope it helps someone else!

Should I use PATCH or PUT in my REST API?

Since you want to design an API using the REST architectural style you need to think about your use cases to decide which concepts are important enough to expose as resources. Should you decide to expose the status of a group as a sub-resource you could give it the following URI and implement support for both GET and PUT methods:

/groups/api/groups/{group id}/status

The downside of this approach over PATCH for modification is that you will not be able to make changes to more than one property of a group atomically and transactionally. If transactional changes are important then use PATCH.

If you do decide to expose the status as a sub-resource of a group it should be a link in the representation of the group. For example if the agent gets group 123 and accepts XML the response body could contain:

<group id="123">
  <status>Active</status>
  <link rel="/linkrels/groups/status" uri="/groups/api/groups/123/status"/>
  ...
</group>

A hyperlink is needed to fulfill the hypermedia as the engine of application state condition of the REST architectural style.

C# cannot convert method to non delegate type

getTitle is a function, so you need to put () after it.

string t = obj.getTitle();

How can I access getSupportFragmentManager() in a fragment?

if you have this problem and are on api level 21+ do this:

   map = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map))
                    .getMap();

this will get the map when used inside of a fragment.

client denied by server configuration

The error "client denied by server configuration" generally means that somewhere in your configuration are Allow from and Deny from directives that are preventing access. Read the mod_authz_host documentation for more details.

You should be able to solve this in your VirtualHost by adding something like:

<Location />
  Allow from all
  Order Deny,Allow
</Location>

Or alternatively with a Directory directive:

<Directory "D:/Devel/matysart/matysart_dev1">
  Allow from all
  Order Deny,Allow
</Directory>

Some investigation of your Apache configuration files will probably turn up default restrictions on the default DocumentRoot.

How to query for Xml values and attributes from table in SQL Server?

I've been trying to do something very similar but not using the nodes. However, my xml structure is a little different.

You have it like this:

<Metrics>
    <Metric id="TransactionCleanupThread.RefundOldTrans" type="timer" ...>

If it were like this instead:

<Metrics>
    <Metric>
        <id>TransactionCleanupThread.RefundOldTrans</id>
        <type>timer</type>
        .
        .
        .

Then you could simply use this SQL statement.

SELECT
    Sqm.SqmId,
    Data.value('(/Sqm/Metrics/Metric/id)[1]', 'varchar(max)') as id,
    Data.value('(/Sqm/Metrics/Metric/type)[1]', 'varchar(max)') AS type,
    Data.value('(/Sqm/Metrics/Metric/unit)[1]', 'varchar(max)') AS unit,
    Data.value('(/Sqm/Metrics/Metric/sum)[1]', 'varchar(max)') AS sum,
    Data.value('(/Sqm/Metrics/Metric/count)[1]', 'varchar(max)') AS count,
    Data.value('(/Sqm/Metrics/Metric/minValue)[1]', 'varchar(max)') AS minValue,
    Data.value('(/Sqm/Metrics/Metric/maxValue)[1]', 'varchar(max)') AS maxValue,
    Data.value('(/Sqm/Metrics/Metric/stdDeviation)[1]', 'varchar(max)') AS stdDeviation,
FROM Sqm

To me this is much less confusing than using the outer apply or cross apply.

I hope this helps someone else looking for a simpler solution!

NSURLSession/NSURLConnection HTTP load failed on iOS 9

Update:

As of Xcode 7.1, you don't need to manually enter the NSAppTransportSecurity Dictionary in the info.plist.

It will now autocomplete for you, realize it's a dictionary, and then autocomplete the Allows Arbitrary Loads as well. info.plist screenshot

How to center horizontally div inside parent div

I am assuming the parent div has no width or a wide width, and the child div has a smaller width. The following will set the margin for the top and bottom to zero, and the sides to automatically fit. This centers the div.

div#child {
    margin: 0 auto;
}

python tuple to dict

Try:

>>> t = ((1, 'a'),(2, 'b'))
>>> dict((y, x) for x, y in t)
{'a': 1, 'b': 2}

C# - Print dictionary

My goto is

Console.WriteLine( Serialize(dictionary.ToList() ) );

Make sure you include the package using static System.Text.Json.JsonSerializer;

iPhone is not available. Please reconnect the device

I am now using Xcode 11.6, macOS 10.15.6, and iOS 13.5.1.

First the problem was that I was on Xcode 11.4. But I couldn't upgrade since I wasn't on macOS v10.15 (Catalina) yet. (And I couldn't upgrade because my RAID went down and I couldn't make a backup, but that's another saga.)

After upgrading to Catalina, then to Xcode 11.6 I still couldn't build to the device. So I opened Devices and Simulators and unpaired the phone, as mentioned in the comments here. Then when I tried to re-pair, a warning message said that the device was busy (it was not). Finally, after rebooting the phone (had to untether it for it to come back on), cleaning Xcode, and re-pairing the phone, I finally, finally built to the device. So good luck!

OVER clause in Oracle

The OVER clause specifies the partitioning, ordering and window "over which" the analytic function operates.

Example #1: calculate a moving average

AVG(amt) OVER (ORDER BY date ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING)

date   amt   avg_amt
=====  ====  =======
1-Jan  10.0  10.5
2-Jan  11.0  17.0
3-Jan  30.0  17.0
4-Jan  10.0  18.0
5-Jan  14.0  12.0

It operates over a moving window (3 rows wide) over the rows, ordered by date.

Example #2: calculate a running balance

SUM(amt) OVER (ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)

date   amt   sum_amt
=====  ====  =======
1-Jan  10.0  10.0
2-Jan  11.0  21.0
3-Jan  30.0  51.0
4-Jan  10.0  61.0
5-Jan  14.0  75.0

It operates over a window that includes the current row and all prior rows.

Note: for an aggregate with an OVER clause specifying a sort ORDER, the default window is UNBOUNDED PRECEDING to CURRENT ROW, so the above expression may be simplified to, with the same result:

SUM(amt) OVER (ORDER BY date)

Example #3: calculate the maximum within each group

MAX(amt) OVER (PARTITION BY dept)

dept  amt   max_amt
====  ====  =======
ACCT   5.0   7.0
ACCT   7.0   7.0
ACCT   6.0   7.0
MRKT  10.0  11.0
MRKT  11.0  11.0
SLES   2.0   2.0

It operates over a window that includes all rows for a particular dept.

SQL Fiddle: http://sqlfiddle.com/#!4/9eecb7d/122

How to exit if a command failed?

Try:

my_command || { echo 'my_command failed' ; exit 1; }

Four changes:

  • Change && to ||
  • Use { } in place of ( )
  • Introduce ; after exit and
  • spaces after { and before }

Since you want to print the message and exit only when the command fails ( exits with non-zero value) you need a || not an &&.

cmd1 && cmd2

will run cmd2 when cmd1 succeeds(exit value 0). Where as

cmd1 || cmd2

will run cmd2 when cmd1 fails(exit value non-zero).

Using ( ) makes the command inside them run in a sub-shell and calling a exit from there causes you to exit the sub-shell and not your original shell, hence execution continues in your original shell.

To overcome this use { }

The last two changes are required by bash.

How to check for null in Twig?

Without any assumptions the answer is:

{% if var is null %}

But this will be true only if var is exactly NULL, and not any other value that evaluates to false (such as zero, empty string and empty array). Besides, it will cause an error if var is not defined. A safer way would be:

{% if var is not defined or var is null %}

which can be shortened to:

{% if var|default is null %}

If you don't provide an argument to the default filter, it assumes NULL (sort of default default). So the shortest and safest way (I know) to check whether a variable is empty (null, false, empty string/array, etc):

{% if var|default is empty %}

How can I disable the Maven Javadoc plugin from the command line?

Add to the release plugin config in the root-level pom.xml:

<configuration>
    <arguments>-Dmaven.javadoc.skip=true</arguments>
</configuration>

Android Canvas: drawing too large bitmap

if you use Picasso change to Glide like this.

Remove picasso

Picasso.get().load(Uri.parse("url")).into(imageView)

Change Glide

Glide.with(context).load("url").into(imageView)

More efficient Glide than Picasso draw to large bitmap

Regular expression for exact match of a string

if you have a the input password in a variable and you want to match exactly 123456 then anchors will help you:

/^123456$/

in perl the test for matching the password would be something like

print "MATCH_OK" if ($input_pass=~/^123456$/);

EDIT:

bart kiers is right tho, why don't you use a strcmp() for this? every language has it in its own way

as a second thought, you may want to consider a safer authentication mechanism :)

How do I compare two variables containing strings in JavaScript?

instead of using the == sign, more safer use the === sign when compare, the code that you post is work well

How to make a JTable non-editable

I used this and it worked : it is very simple and works fine.

JTable myTable = new JTable();
myTable.setEnabled(false);

How to add plus one (+1) to a SQL Server column in a SQL Query

You need both a value and a field to assign it to. The value is TableField + 1, so the assignment is:

SET TableField = TableField + 1

How to decide when to use Node.js?

My one more reason to choose Node.js for a new project is:

Be able to do pure cloud based development

I have used Cloud9 IDE for a while and now I can't imagine without it, it covers all the development lifecycles. All you need is a browser and you can code anytime anywhere on any devices. You don't need to check in code in one Computer(like at home), then checkout in another computer(like at work place).

Of course, there maybe cloud based IDE for other languages or platforms (Cloud 9 IDE is adding supports for other languages as well), but using Cloud 9 to do Node.js developement is really a great experience for me.

Word-wrap in an HTML table

The following works for me in Internet Explorer. Note the addition of the table-layout:fixed CSS attribute

_x000D_
_x000D_
td {_x000D_
  border: 1px solid;_x000D_
}
_x000D_
<table style="table-layout: fixed; width: 100%">_x000D_
  <tr>_x000D_
    <td style="word-wrap: break-word">_x000D_
      LongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongWord_x000D_
    </td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Making WPF applications look Metro-styled, even in Windows 7? (Window Chrome / Theming / Theme)

Based on Kapitán Mlíko's answer with source above, I would change it to use the following:

Marlett Font Example

It's a better practice to use the Marlett font rather than Path Data points for the Minimize, Restore/Maximize and Close buttons.

<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" VerticalAlignment="Top" WindowChrome.IsHitTestVisibleInChrome="True" Grid.Row="0">
<Button Command="{Binding Source={x:Static SystemCommands.MinimizeWindowCommand}}" ToolTip="minimize" Style="{StaticResource WindowButtonStyle}">
    <Button.Content>
        <Grid Width="30" Height="25">
            <TextBlock Text="0" FontFamily="Marlett" FontSize="14" VerticalAlignment="Center" HorizontalAlignment="Center" Padding="3.5,0,0,3" />
        </Grid>
    </Button.Content>
</Button>
<Grid Margin="1,0,1,0">
    <Button x:Name="Restore" Command="{Binding Source={x:Static SystemCommands.RestoreWindowCommand}}" ToolTip="restore" Visibility="Collapsed" Style="{StaticResource WindowButtonStyle}">
        <Button.Content>
            <Grid Width="30" Height="25" UseLayoutRounding="True">
                <TextBlock Text="2" FontFamily="Marlett" FontSize="14" VerticalAlignment="Center" HorizontalAlignment="Center" Padding="2,0,0,1" />
            </Grid>
        </Button.Content>
    </Button>
    <Button x:Name="Maximize" Command="{Binding Source={x:Static SystemCommands.MaximizeWindowCommand}}" ToolTip="maximize" Style="{StaticResource WindowButtonStyle}">
        <Button.Content>
            <Grid Width="31" Height="25">
                <TextBlock Text="1" FontFamily="Marlett" FontSize="14" VerticalAlignment="Center" HorizontalAlignment="Center" Padding="2,0,0,1" />
            </Grid>
        </Button.Content>
    </Button>
</Grid>
<Button Command="{Binding Source={x:Static SystemCommands.CloseWindowCommand}}" ToolTip="close"  Style="{StaticResource WindowButtonStyle}">
    <Button.Content>
        <Grid Width="30" Height="25">
            <TextBlock Text="r" FontFamily="Marlett" FontSize="14" VerticalAlignment="Center" HorizontalAlignment="Center" Padding="0,0,0,1" />
        </Grid>
    </Button.Content>
</Button>

How to use the CancellationToken property?

You can create a Task with cancellation token, when you app goto background you can cancel this token.

You can do this in PCL https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/app-lifecycle

var cancelToken = new CancellationTokenSource();
Task.Factory.StartNew(async () => {
    await Task.Delay(10000);
    // call web API
}, cancelToken.Token);

//this stops the Task:
cancelToken.Cancel(false);

Anther solution is user Timer in Xamarin.Forms, stop timer when app goto background https://xamarinhelp.com/xamarin-forms-timer/

Call external javascript functions from java code

Use ScriptEngine.eval(java.io.Reader) to read the script

ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
// read script file
engine.eval(Files.newBufferedReader(Paths.get("C:/Scripts/Jsfunctions.js"), StandardCharsets.UTF_8));

Invocable inv = (Invocable) engine;
// call function from script file
inv.invokeFunction("yourFunction", "param");

What does '<?=' mean in PHP?

It means assign the key to $user and the variable to $pass

When you assign an array, you do it like this

$array = array("key" => "value");

It uses the same symbol for processing arrays in foreach statements. The '=>' links the key and the value.

According to the PHP Manual, the '=>' created key/value pairs.

Also, Equal or Greater than is the opposite way: '>='. In PHP the greater or less than sign always goes first: '>=', '<='.

And just as a side note, excluding the second value does not work like you think it would. Instead of only giving you the key, It actually only gives you a value:

$array = array("test" => "foo");

foreach($array as $key => $value)
{
    echo $key . " : " . $value; // Echoes "test : foo"
}

foreach($array as $value)
{
    echo $value; // Echoes "foo"
}

Is Spring annotation @Controller same as @Service?

No, @Controller is not the same as @Service, although they both are specializations of @Component, making them both candidates for discovery by classpath scanning. The @Service annotation is used in your service layer, and @Controller is for Spring MVC controllers in your presentation layer. A @Controller typically would have a URL mapping and be triggered by a web request.

Escape single quote character for use in an SQLite query

Just in case if you have a loop or a json string that need to insert in the database. Try to replace the string with a single quote . here is my solution. example if you have a string that contain's a single quote.

String mystring = "Sample's";
String myfinalstring = mystring.replace("'","''");

 String query = "INSERT INTO "+table name+" ("+field1+") values ('"+myfinalstring+"')";

this works for me in c# and java

Setting up MySQL and importing dump within Dockerfile

Here is a working version using v3 of docker-compose.yml. The key is the volumes directive:

mysql:
  image: mysql:5.6
  ports:
    - "3306:3306"
  environment:
    MYSQL_ROOT_PASSWORD: root
    MYSQL_USER: theusername
    MYSQL_PASSWORD: thepw
    MYSQL_DATABASE: mydb
  volumes:
    - ./data:/docker-entrypoint-initdb.d

In the directory that I have my docker-compose.yml I have a data dir that contains .sql dump files. This is nice because you can have a .sql dump file per table.

I simply run docker-compose up and I'm good to go. Data automatically persists between stops. If you want remove the data and "suck in" new .sql files run docker-compose down then docker-compose up.

If anyone knows how to get the mysql docker to re-process files in /docker-entrypoint-initdb.d without removing the volume, please leave a comment and I will update this answer.

How to handle change of checkbox using jQuery?

$("input[type=checkbox]").on("change", function() { 

    if (this.checked) {

      //do your stuff

     }
});

PHP - remove <img> tag from string

You need to assign the result back to $content as preg_replace does not modify the original string.

$content = preg_replace("/<img[^>]+\>/i", "(image) ", $content);

With block equivalent in C#?

Although C# doesn't have any direct equivalent for the general case, C# 3 gain object initializer syntax for constructor calls:

var foo = new Foo { Property1 = value1, Property2 = value2, etc };

See chapter 8 of C# in Depth for more details - you can download it for free from Manning's web site.

(Disclaimer - yes, it's in my interest to get the book into more people's hands. But hey, it's a free chapter which gives you more information on a related topic...)

Accept server's self-signed ssl certificate in Java client

I had the issue that I was passing a URL into a library which was calling url.openConnection(); I adapted jon-daniel's answer,

public class TrustHostUrlStreamHandler extends URLStreamHandler {

    private static final Logger LOG = LoggerFactory.getLogger(TrustHostUrlStreamHandler.class);

    @Override
    protected URLConnection openConnection(final URL url) throws IOException {

        final URLConnection urlConnection = new URL(url.getProtocol(), url.getHost(), url.getPort(), url.getFile()).openConnection();

        // adapated from
        // https://stackoverflow.com/questions/2893819/accept-servers-self-signed-ssl-certificate-in-java-client
        if (urlConnection instanceof HttpsURLConnection) {
            final HttpsURLConnection conHttps = (HttpsURLConnection) urlConnection;

            try {
                // Set up a Trust all manager
                final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

                    @Override
                    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }

                    @Override
                    public void checkClientTrusted(final java.security.cert.X509Certificate[] certs, final String authType) {
                    }

                    @Override
                    public void checkServerTrusted(final java.security.cert.X509Certificate[] certs, final String authType) {
                    }
                } };

                // Get a new SSL context
                final SSLContext sc = SSLContext.getInstance("TLSv1.2");
                sc.init(null, trustAllCerts, new java.security.SecureRandom());
                // Set our connection to use this SSL context, with the "Trust all" manager in place.
                conHttps.setSSLSocketFactory(sc.getSocketFactory());
                // Also force it to trust all hosts
                final HostnameVerifier allHostsValid = new HostnameVerifier() {
                    @Override
                    public boolean verify(final String hostname, final SSLSession session) {
                        return true;
                    }
                };

                // and set the hostname verifier.
                conHttps.setHostnameVerifier(allHostsValid);

            } catch (final NoSuchAlgorithmException e) {
                LOG.warn("Failed to override URLConnection.", e);
            } catch (final KeyManagementException e) {
                LOG.warn("Failed to override URLConnection.", e);
            }

        } else {
            LOG.warn("Failed to override URLConnection. Incorrect type: {}", urlConnection.getClass().getName());
        }

        return urlConnection;
    }

}

Using this class it is possible to create a new URL with:

trustedUrl = new URL(new URL(originalUrl), "", new TrustHostUrlStreamHandler());
trustedUrl.openConnection();

This has the advantage that it is localized and not replacing the default URL.openConnection.

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

I was facing the same issue and here is the code that resolved it:

\t\n - for new line in Email service JavaMailSender

String mailMessage = JSONObject.toJSONString("Your message").replace(",", "\t\n").trim();

php convert datetime to UTC

As strtotime requires specific input format, DateTime::createFromFormat could be used (php 5.3+ is required)

// set timezone to user timezone
date_default_timezone_set($str_user_timezone);

// create date object using any given format
$date = DateTime::createFromFormat($str_user_dateformat, $str_user_datetime);

// convert given datetime to safe format for strtotime
$str_user_datetime = $date->format('Y-m-d H:i:s');

// convert to UTC
$str_UTC_datetime = gmdate($str_server_dateformat, strtotime($str_user_datetime));

// return timezone to server default
date_default_timezone_set($str_server_timezone);

Plot width settings in ipython notebook

If you use %pylab inline you can (on a new line) insert the following command:

%pylab inline
pylab.rcParams['figure.figsize'] = (10, 6)

This will set all figures in your document (unless otherwise specified) to be of the size (10, 6), where the first entry is the width and the second is the height.

See this SO post for more details. https://stackoverflow.com/a/17231361/1419668

How to use SSH to run a local shell script on a remote machine?

The answer here (https://stackoverflow.com/a/2732991/4752883) works great if you're trying to run a script on a remote linux machine using plink or ssh. It will work if the script has multiple lines on linux.

**However, if you are trying to run a batch script located on a local linux/windows machine and your remote machine is Windows, and it consists of multiple lines using **

plink root@MachineB -m local_script.bat

wont work.

Only the first line of the script will be executed. This is probably a limitation of plink.

Solution 1:

To run a multiline batch script (especially if it's relatively simple, consisting of a few lines):

If your original batch script is as follows

cd C:\Users\ipython_user\Desktop 
python filename.py

you can combine the lines together using the "&&" separator as follows in your local_script.bat file: https://stackoverflow.com/a/8055390/4752883:

cd C:\Users\ipython_user\Desktop && python filename.py

After this change, you can then run the script as pointed out here by @JasonR.Coombs: https://stackoverflow.com/a/2732991/4752883 with:

`plink root@MachineB -m local_script.bat`

Solution 2:

If your batch script is relatively complicated, it may be better to use a batch script which encapsulates the plink command as well as follows as pointed out here by @Martin https://stackoverflow.com/a/32196999/4752883:

rem Open tunnel in the background
start plink.exe -ssh [username]@[hostname] -L 3307:127.0.0.1:3306 -i "[SSH
key]" -N

rem Wait a second to let Plink establish the tunnel 
timeout /t 1

rem Run the task using the tunnel
"C:\Program Files\R\R-3.2.1\bin\x64\R.exe" CMD BATCH qidash.R

rem Kill the tunnel
taskkill /im plink.exe

JPA CriteriaBuilder - How to use "IN" comparison operator

If I understand well, you want to Join ScheduleRequest with User and apply the in clause to the userName property of the entity User.

I'd need to work a bit on this schema. But you can try with this trick, that is much more readable than the code you posted, and avoids the Join part (because it handles the Join logic outside the Criteria Query).

List<String> myList = new ArrayList<String> ();
for (User u : usersList) {
    myList.add(u.getUsername());
}
Expression<String> exp = scheduleRequest.get("createdBy");
Predicate predicate = exp.in(myList);
criteria.where(predicate);

In order to write more type-safe code you could also use Metamodel by replacing this line:

Expression<String> exp = scheduleRequest.get("createdBy");

with this:

Expression<String> exp = scheduleRequest.get(ScheduleRequest_.createdBy);

If it works, then you may try to add the Join logic into the Criteria Query. But right now I can't test it, so I prefer to see if somebody else wants to try.


Not a perfect answer though may be code snippets might help.

public <T> List<T> findListWhereInCondition(Class<T> clazz,
            String conditionColumnName, Serializable... conditionColumnValues) {
        QueryBuilder<T> queryBuilder = new QueryBuilder<T>(clazz);
        addWhereInClause(queryBuilder, conditionColumnName,
                conditionColumnValues);
        queryBuilder.select();
        return queryBuilder.getResultList();

    }


private <T> void addWhereInClause(QueryBuilder<T> queryBuilder,
            String conditionColumnName, Serializable... conditionColumnValues) {

        Path<Object> path = queryBuilder.root.get(conditionColumnName);
        In<Object> in = queryBuilder.criteriaBuilder.in(path);
        for (Serializable conditionColumnValue : conditionColumnValues) {
            in.value(conditionColumnValue);
        }
        queryBuilder.criteriaQuery.where(in);

    }

Default text which won't be shown in drop-down list

Kyle's solution worked perfectly fine for me so I made my research in order to avoid any Js and CSS, but just sticking with HTML. Adding a value of selected to the item we want to appear as a header forces it to show in the first place as a placeholder. Something like:

<option selected disabled>Choose here</option>

The complete markup should be along these lines:

<select>
    <option selected disabled>Choose here</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option>
    <option value="5">Five</option>
</select>

You can take a look at this fiddle, and here's the result:

enter image description here

If you do not want the sort of placeholder text to appear listed in the options once a user clicks on the select box just add the hidden attribute like so:

<select>
    <option selected disabled hidden>Choose here</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option>
    <option value="5">Five</option>
</select>

Check the fiddle here and the screenshot below.

enter image description here


Here is the solution:

<select>
    <option style="display:none;" selected>Select language</option>
    <option>Option 1</option>
    <option>Option 2</option>
</select>

Java Initialize an int array in a constructor

private int[] data = new int[3];

This already initializes your array elements to 0. You don't need to repeat that again in the constructor.

In your constructor it should be:

data = new int[]{0, 0, 0};

Use jquery click to handle anchor onClick()

Lets take an anchor tag with an onclick event, that calls a Javascript function.

<a href="#" onClick="showDiv(1);">1</a>

Now in javascript write the below code

function showDiv(pageid)
{
   alert(pageid);
}

This will show you an alert of "1"....

Want custom title / image / description in facebook share link from a flash app

2016 Update

Use the Sharing Debugger to figure out what your problems are.

Make sure you're following the Facebook Sharing Best Practices.

Make sure you're using the Open Graph Markup correctly.

Original Answer

I agree with what has already been said here, but per documentation on the Facebook developer site, you might want to use the following meta tags.

<meta property="og:title" content="title" />
<meta property="og:description" content="description" />
<meta property="og:image" content="thumbnail_image" />

If you are not able to accomplish your goal with meta tags and you need a URL embedded version, see @Lelis718's answer below.

How to get all Errors from ASP.Net MVC modelState?

And this works too:

var query = from state in ModelState.Values
    from error in state.Errors
    select error.ErrorMessage;
var errors = query.ToArray(); // ToList() and so on...

z-index not working with position absolute

Opacity changes the context of your z-index, as does the static positioning. Either add opacity to the element that doesn't have it or remove it from the element that does. You'll also have to either make both elements static positioned or specify relative or absolute position. Here's some background on contexts: http://philipwalton.com/articles/what-no-one-told-you-about-z-index/

How do I limit the number of decimals printed for a double?

Use a DecimalFormatter:

double number = 0.9999999999999;
DecimalFormat numberFormat = new DecimalFormat("#.00");
System.out.println(numberFormat.format(number));

Will give you "0.99". You can add or subtract 0 on the right side to get more or less decimals.

Or use '#' on the right to make the additional digits optional, as in with #.## (0.30) would drop the trailing 0 to become (0.3).

Closing JFrame with button click

It appears to me that you have two issues here. One is that JFrame does not have a close method, which has been addressed in the other answers.

The other is that you're having trouble referencing your JFrame. Within actionPerformed, super refers to ActionListener. To refer to the JFrame instance there, use MyExtendedJFrame.super instead (you should also be able to use MyExtendedJFrame.this, as I see no reason why you'd want to override the behaviour of dispose or setVisible).

How do I collapse sections of code in Visual Studio Code for Windows?

Code folding controls inside the editor to expand nodes of XML-structured documents and source code in VsCode

No technical tips here, just simple adjustments of the preferences of VsCode.

I managed to show code folding controls always in VsCode by going to Preferences and searching for 'folding'. Now just select to always show these controls. This works with the Typescript code and HTML of templates in the Angular 8 solution I tested it with.

This was tested with VsCode Insiders 1.37.0 running on a Windows 10 OS.

Show code folding controls always in VsCode

Count number of cells with any value (string or number) in a column in Google Docs Spreadsheet

You could also use =COUNTA(A1:A200) which requires no conditions.

From Google Support:

COUNTA counts all values in a dataset, including those which appear more than once and text values (including zero-length strings and whitespace). To count unique values, use COUNTUNIQUE.

WPF TemplateBinding vs RelativeSource TemplatedParent

TemplateBinding is a shorthand for Binding with TemplatedParent but it does not expose all the capabilities of the Binding class, for example you can't control Binding.Mode from TemplateBinding.

adb command for getting ip address assigned by operator

You also can try this:

Step 1: adb shell Step 2: ip -f inet addr show wlan0

Test if object implements interface

I had a situation where I was passing a variable to a method and wasn't sure if it was going to be an interface or an object.

The goals were:

  1. If item is an interface, instantiate an object based on that interface with the interface being a parameter in the constructor call.
  2. If the item is an object, return a null since the constuctor for my calls are expecting an interface and I didn't want the code to tank.

I achieved this with the following:

    if(!typeof(T).IsClass)
    {
       // If your constructor needs arguments...
       object[] args = new object[] { my_constructor_param };
       return (T)Activator.CreateInstance(typeof(T), args, null);
    }
    else
       return default(T);

Adding a caption to an equation in LaTeX

The \caption command is restricted to floats: you will need to place the equation in a figure or table environment (or a new kind of floating environment). For example:

\begin{figure}
\[ E = m c^2 \]
\caption{A famous equation}
\end{figure}

The point of floats is that you let LaTeX determine their placement. If you want to equation to appear in a fixed position, don't use a float. The \captionof command of the caption package can be used to place a caption outside of a floating environment. It is used like this:

\[ E = m c^2 \]
\captionof{figure}{A famous equation}

This will also produce an entry for the \listoffigures, if your document has one.

To align parts of an equation, take a look at the eqnarray environment, or some of the environments of the amsmath package: align, gather, multiline,...

C# Form.Close vs Form.Dispose

Not calling Close probably bypasses sending a bunch of Win32 messages which one would think are somewhat important though I couldn't specifically tell you why...

Close has the benefit of raising events (that can be cancelled) such that an outsider (to the form) could watch for FormClosing and FormClosed in order to react accordingly.

I'm not clear whether FormClosing and/or FormClosed are raised if you simply dispose the form but I'll leave that to you to experiment with.

element not interactable exception in selenium web automation

Try setting an implicit wait of maybe 10 seconds.

gmail.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

Or set an explicit wait. An explicit waits is code you define to wait for a certain condition to occur before proceeding further in the code. In your case, it is the visibility of the password input field. (Thanks to ainlolcat's comment)

WebDriver gmail= new ChromeDriver();
gmail.get("https://www.gmail.co.in"); 
gmail.findElement(By.id("Email")).sendKeys("abcd");
gmail.findElement(By.id("next")).click();
WebDriverWait wait = new WebDriverWait(gmail, 10);
WebElement element = wait.until(
ExpectedConditions.visibilityOfElementLocated(By.id("Passwd")));
gmail.findElement(By.id("Passwd")).sendKeys("xyz");

Explanation: The reason selenium can't find the element is because the id of the password input field is initially Passwd-hidden. After you click on the "Next" button, Google first verifies the email address entered and then shows the password input field (by changing the id from Passwd-hidden to Passwd). So, when the password field is still hidden (i.e. Google is still verifying the email id), your webdriver starts searching for the password input field with id Passwd which is still hidden. And hence, an exception is thrown.

val() vs. text() for textarea

The best way to set/get the value of a textarea is the .val(), .value method.

.text() internally uses the .textContent (or .innerText for IE) method to get the contents of a <textarea>. The following test cases illustrate how text() and .val() relate to each other:

var t = '<textarea>';
console.log($(t).text('test').val());             // Prints test
console.log($(t).val('too').text('test').val());  // Prints too
console.log($(t).val('too').text());              // Prints nothing
console.log($(t).text('test').val('too').val());  // Prints too

console.log($(t).text('test').val('too').text()); // Prints test

The value property, used by .val() always shows the current visible value, whereas text()'s return value can be wrong.

Control flow in T-SQL SP using IF..ELSE IF - are there other ways?

Also you can try to formulate your answer in the form of a SELECT CASE Statement. You can then later create simple if then's that use your results if needed as you have narrowed down the possibilities.

SELECT @Result =   
CASE @inputParam   
WHEN 1 THEN 1   
WHEN 2 THEN 2   
WHEN 3 THEN 1   
ELSE 4   
END  

IF @Result = 1   
BEGIN  
...  
END  

IF @Result = 2   
BEGIN   
....  
END  

IF @Result = 4   
BEGIN   
//Error handling code   
END   

Is it possible to have empty RequestParam values use the defaultValue?

You can also do something like this -

 @RequestParam(value= "i", defaultValue = "20") Optional<Integer> i

Clearing a string buffer/builder after loop

The easiest way to reuse the StringBuffer is to use the method setLength()

public void setLength(int newLength)

You may have the case like

StringBuffer sb = new StringBuffer("HelloWorld");
// after many iterations and manipulations
sb.setLength(0);
// reuse sb

Convert Time DataType into AM PM Format:

select CONVERT(varchar(15),CAST('17:30:00.0000000' AS TIME),100)

almost works perfectly except for the space issue. if that were changed to:

select CONVERT(varchar(15),CAST('17:30:00.0000000' AS TIME),22)

...then you get the space. And additionally, if the column being converted is already of TIME format, you can skip the cast if you reference it directly.

Final answer:

select CONVERT(varchar(15),StartTime,22)

Undefined reference to `sin`

You have compiled your code with references to the correct math.h header file, but when you attempted to link it, you forgot the option to include the math library. As a result, you can compile your .o object files, but not build your executable.

As Paul has already mentioned add "-lm" to link with the math library in the step where you are attempting to generate your executable.

In the comment, linuxD asks:

Why for sin() in <math.h>, do we need -lm option explicitly; but, not for printf() in <stdio.h>?

Because both these functions are implemented as part of the "Single UNIX Specification". This history of this standard is interesting, and is known by many names (IEEE Std 1003.1, X/Open Portability Guide, POSIX, Spec 1170).

This standard, specifically separates out the "Standard C library" routines from the "Standard C Mathematical Library" routines (page 277). The pertinent passage is copied below:

Standard C Library

The Standard C library is automatically searched by cc to resolve external references. This library supports all of the interfaces of the Base System, as defined in Volume 1, except for the Math Routines.

Standard C Mathematical Library

This library supports the Base System math routines, as defined in Volume 1. The cc option -lm is used to search this library.

The reasoning behind this separation was influenced by a number of factors:

  1. The UNIX wars led to increasing divergence from the original AT&T UNIX offering.
  2. The number of UNIX platforms added difficulty in developing software for the operating system.
  3. An attempt to define the lowest common denominator for software developers was launched, called 1988 POSIX.
  4. Software developers programmed against the POSIX standard to provide their software on "POSIX compliant systems" in order to reach more platforms.
  5. UNIX customers demanded "POSIX compliant" UNIX systems to run the software.

The pressures that fed into the decision to put -lm in a different library probably included, but are not limited to:

  1. It seems like a good way to keep the size of libc down, as many applications don't use functions embedded in the math library.
  2. It provides flexibility in math library implementation, where some math libraries rely on larger embedded lookup tables while others may rely on smaller lookup tables (computing solutions).
  3. For truly size constrained applications, it permits reimplementations of the math library in a non-standard way (like pulling out just sin() and putting it in a custom built library.

In any case, it is now part of the standard to not be automatically included as part of the C language, and that's why you must add -lm.

SQL subquery with COUNT help

This is probably the easiest way, not the prettiest though:

SELECT *,
    (SELECT Count(*) FROM eventsTable WHERE columnName = 'Business') as RowCount
    FROM eventsTable
    WHERE columnName = 'Business'

This will also work without having to use a group by

SELECT *, COUNT(*) OVER () as RowCount
    FROM eventsTables
    WHERE columnName = 'Business'

React js onClick can't pass value to method

There are nice answers here, and i agree with @Austin Greco (the second option with separate components)
There is another way i like, currying.
What you can do is create a function that accept a parameter (your parameter) and returns another function that accepts another parameter (the click event in this case). then you are free to do with it what ever you want.

ES5:

handleChange(param) { // param is the argument you passed to the function
    return function (e) { // e is the event object that returned

    };
}

ES6:

handleChange = param => e => {
    // param is the argument you passed to the function
    // e is the event object that returned
};

And you will use it this way:

<input 
    type="text" 
    onChange={this.handleChange(someParam)} 
/>

Here is a full example of such usage:

_x000D_
_x000D_
const someArr = ["A", "B", "C", "D"];_x000D_
_x000D_
class App extends React.Component {_x000D_
  state = {_x000D_
    valueA: "",_x000D_
    valueB: "some initial value",_x000D_
    valueC: "",_x000D_
    valueD: "blah blah"_x000D_
  };_x000D_
_x000D_
  handleChange = param => e => {_x000D_
    const nextValue = e.target.value;_x000D_
    this.setState({ ["value" + param]: nextValue });_x000D_
  };_x000D_
_x000D_
  render() {_x000D_
    return (_x000D_
      <div>_x000D_
        {someArr.map(obj => {_x000D_
          return (_x000D_
            <div>_x000D_
              <label>_x000D_
                {`input ${obj}   `}_x000D_
              </label>_x000D_
              <input_x000D_
                type="text"_x000D_
                value={this.state["value" + obj]}_x000D_
                onChange={this.handleChange(obj)}_x000D_
              />_x000D_
              <br />_x000D_
              <br />_x000D_
            </div>_x000D_
          );_x000D_
        })}_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
}_x000D_
_x000D_
const rootElement = document.getElementById("root");_x000D_
ReactDOM.render(<App />, rootElement);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="root"></div>
_x000D_
_x000D_
_x000D_

Note that this approach doesn't solve the creation of a new instance on each render.
I like this approach over the other inline handlers as this one is more concise and readable in my opinion.

Edit:
As suggested in the comments below, you can cache / memoize the result of the function.

Here is a naive implementation:

_x000D_
_x000D_
let memo = {};_x000D_
_x000D_
const someArr = ["A", "B", "C", "D"];_x000D_
_x000D_
class App extends React.Component {_x000D_
  state = {_x000D_
    valueA: "",_x000D_
    valueB: "some initial value",_x000D_
    valueC: "",_x000D_
    valueD: "blah blah"_x000D_
  };_x000D_
_x000D_
  handleChange = param => {_x000D_
    const handler = e => {_x000D_
      const nextValue = e.target.value;_x000D_
      this.setState({ ["value" + param]: nextValue });_x000D_
    }_x000D_
    if (!memo[param]) {_x000D_
      memo[param] = e => handler(e)_x000D_
    }_x000D_
    return memo[param]_x000D_
  };_x000D_
_x000D_
  render() {_x000D_
    return (_x000D_
      <div>_x000D_
        {someArr.map(obj => {_x000D_
          return (_x000D_
            <div key={obj}>_x000D_
              <label>_x000D_
                {`input ${obj}   `}_x000D_
              </label>_x000D_
              <input_x000D_
                type="text"_x000D_
                value={this.state["value" + obj]}_x000D_
                onChange={this.handleChange(obj)}_x000D_
              />_x000D_
              <br />_x000D_
              <br />_x000D_
            </div>_x000D_
          );_x000D_
        })}_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
}_x000D_
_x000D_
const rootElement = document.getElementById("root");_x000D_
ReactDOM.render(<App />, rootElement);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="root" />
_x000D_
_x000D_
_x000D_

Fragment MyFragment not attached to Activity

if (getActivity() == null) return;

works also in some cases. Just breaks the code execution from it and make sure the app not crash

How to retrieve the first word of the output of a command in bash?

You could try awk

echo "word1 word2" | awk '{ print $1 }'

With awk it is really easy to pick any word you like ($1, $2, ...)

How to provide a mysql database connection in single file in nodejs

From the node.js documentation, "To have a module execute code multiple times, export a function, and call that function", you could use node.js module.export and have a single file to manage the db connections.You can find more at Node.js documentation. Let's say db.js file be like:

    const mysql = require('mysql');

    var connection;

    module.exports = {

    dbConnection: function () {

        connection = mysql.createConnection({
            host: "127.0.0.1",
            user: "Your_user",
            password: "Your_password",
            database: 'Your_bd'
        });
        connection.connect();
        return connection;
    }

    };

Then, the file where you are going to use the connection could be like useDb.js:

const dbConnection = require('./db');

var connection;

function callDb() {

    try {

        connection = dbConnectionManager.dbConnection();

        connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
            if (!error) {

                let response = "The solution is: " + results[0].solution;
                console.log(response);

            } else {
                console.log(error);
            }
        });
        connection.end();


    } catch (err) {
        console.log(err);
    }
}

How can I generate a 6 digit unique number?

Among the answers given here before this one, the one by "Yes Barry" is the most appropriate one.

random_int(100000, 999999)

Note that here we use random_int, which was introduced in PHP 7 and uses a cryptographic random generator, something that is important if you want random codes to be hard to guess. random_bytes was also introduced in PHP 7 and likewise uses a cryptographic random generator.

Many other solutions for random value generation, including those involving time(), microtime(), uniqid(), rand(), mt_rand(), str_shuffle(), and array_rand(), are much more predictable and are unsuitable if the random string will serve as a password, a bearer credential, a nonce, a session identifier, a "verification code" or "confirmation code", or another secret value.

The code above generates a string of 6 decimal digits. If you want to use a bigger character set (such as all upper-case letters, all lower-case letters, and the 10 digits), this is a more involved process, but you have to use random_int or random_bytes rather than rand(), mt_rand(), str_shuffle(), etc., if the string will serve as a password, a "confirmation code", or another secret value. See an answer to a related question, and see also: generating a random code in php?

I also list other things to keep in mind when generating unique identifiers, especially random ones.

Remove decimal values using SQL query

First of all, you tried to replace the entire 12.00 with '', which isn't going to give your desired results.

Second you are trying to do replace directly on a decimal. Replace must be performed on a string, so you have to CAST.

There are many ways to get your desired results, but this replace would have worked (assuming your column name is "height":

REPLACE(CAST(height as varchar(31)),'.00','')

EDIT:

This script works:

DECLARE @Height decimal(6,2);
SET @Height = 12.00;
SELECT @Height, REPLACE(CAST(@Height AS varchar(31)),'.00','');

Android check permission for LocationManager

The last part of the error message you quoted states: ...with ("checkPermission") or explicitly handle a potential "SecurityException"

A much quicker/simpler way of checking if you have permissions is to surround your code with try { ... } catch (SecurityException e) { [insert error handling code here] }. If you have permissions, the 'try' part will execute, if you don't, the 'catch' part will.

How to Set the Background Color of a JButton on the Mac OS

Based on your own purposes, you can do that based on setOpaque(true/false) and setBorderPainted(true/false); try and combine them to fit your purpose

Plotting categorical data with pandas and matplotlib

You might find useful mosaic plot from statsmodels. Which can also give statistical highlighting for the variances.

from statsmodels.graphics.mosaicplot import mosaic
plt.rcParams['font.size'] = 16.0
mosaic(df, ['direction', 'colour']);

enter image description here

But beware of the 0 sized cell - they will cause problems with labels.

See this answer for details

How can I set the default value for an HTML <select> element?

You can use:

<option value="someValue" selected>Some Value</option>

instead of,

<option value="someValue" selected = "selected">Some Value</option>

both are equally correct.

How to find files recursively by file type and copy them to a directory while in ssh?

Something like this should work.

ssh [email protected] 'find -type f -name "*.pdf" -exec cp {} ./pdfsfolder \;'

What's the purpose of git-mv?

There's another use I have for git mv not mentioned above.

Since discovering git add -p (git add's patch mode; see http://git-scm.com/docs/git-add), I like to use it to review changes as I add them to the index. Thus my workflow becomes (1) work on code, (2) review and add to index, (3) commit.

How does git mv fit in? If moving a file directly then using git rm and git add, all changes get added to the index, and using git diff to view changes is less easy (before committing). Using git mv, however, adds the new path to the index but not changes made to the file, thus allowing git diff and git add -p to work as usual.

Ansible playbook shell output

Expanding on what leucos said in his answer, you can also print information with Ansible's humble debug module:

- hosts: all
  gather_facts: no
  tasks:
    - shell: ps -eo pcpu,user,args | sort -r -k1 | head -n5
      register: ps

    # Print the shell task's stdout.
    - debug: msg={{ ps.stdout }}

    # Print all contents of the shell task's output.
    - debug: var=ps

Twitter Bootstrap dropdown menu

I had a similar problem and it was the version of bootstrap.js included in my visual studio project. I linked to here and it worked great

 <script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>

Printing an array in C++?

Just iterate over the elements. Like this:

for (int i = numElements - 1; i >= 0; i--) 
    cout << array[i];

Note: As Maxim Egorushkin pointed out, this could overflow. See his comment below for a better solution.

Usage of \b and \r in C

As for the meaning of each character described in C Primer Plus, what you expected is an 'correct' answer. It should be true for some computer architectures and compilers, but unfortunately not yours.

I wrote a simple c program to repeat your test, and got that 'correct' answer. I was using Mac OS and gcc. enter image description here

Also, I am very curious what is the compiler that you were using. :)

Binary Search Tree - Java Implementation

This program has a functions for

  1. Add Node
  2. Display BST(Inorder)
  3. Find Element
  4. Find Successor

    class BNode{
        int data;
        BNode left, right;
    
        public BNode(int data){
            this.data = data;
            this.left = null;
            this.right = null;
        }
    }
    
    public class BST {
        static BNode root;
    
        public int add(int value){
            BNode newNode, current;
    
            newNode = new BNode(value);
            if(root == null){
                root = newNode;
                current = root;
            }
            else{
                current = root;
                while(current.left != null || current.right != null){
                    if(newNode.data < current.data){
                        if(current.left != null)
                            current = current.left;
                        else
                            break;
                    }                   
                    else{
                        if(current.right != null)
                            current = current.right;
                        else
                            break;
                    }                                           
                }
                if(newNode.data < current.data)
                    current.left = newNode;
                else
                    current.right = newNode;
            }
    
            return value;
        }
    
        public void inorder(BNode root){
            if (root != null) {
                inorder(root.left);
                System.out.println(root.data);
                inorder(root.right);
            }
        }
    
        public boolean find(int value){
            boolean flag = false;
            BNode current;
            current = root;
            while(current!= null){
                if(current.data == value){
                    flag = true;
                    break;
                }   
                else if(current.data > value)
                    current = current.left;
                else
                    current = current.right;
            }
            System.out.println("Is "+value+" present in tree? : "+flag);
            return flag;
        }
    
        public void successor(int value){
            BNode current;
            current = root;
    
            if(find(value)){
                while(current.data != value){
                    if(value < current.data && current.left != null){
                        System.out.println("Node is: "+current.data);
                        current = current.left;
                    }
                    else if(value > current.data && current.right != null){
                        System.out.println("Node is: "+current.data);
                        current = current.right;
                    }                   
                }
            }
            else
                System.out.println(value+" Element is not present in tree");
        }
    
        public static void main(String[] args) {
    
            BST b = new BST();
            b.add(50);
            b.add(30);
            b.add(20);
            b.add(40);
            b.add(70);
            b.add(60);
            b.add(80);
            b.add(90);
    
            b.inorder(root);
            b.find(30);
            b.find(90);
            b.find(100);
            b.find(50);
    
            b.successor(90);
            System.out.println();
            b.successor(70);
        }
    
    }
    

Floating point vs integer calculations on modern hardware

Based of that oh-so-reliable "something I've heard", back in the old days, integer calculation were about 20 to 50 times faster that floating point, and these days it's less than twice as faster.

How to use a ViewBag to create a dropdownlist?

Use Viewbag is wrong for sending list to view.You should using Viewmodel in this case. like this:

Send Country list and City list and Other list you need to show in View:

HomeController Code:

[HttpGet]
        public ActionResult NewAgahi() // New Advertising
        {
            //--------------------------------------------------------
            // ??????? ?? ?????? ???? ????? ??? ??? ?? ???
            Country_Repository blCountry = new Country_Repository();
            Ostan_Repository blOstan = new Ostan_Repository();
            City_Repository blCity = new City_Repository();
            Mahale_Repository blMahale = new Mahale_Repository();
            Agahi_Repository blAgahi = new Agahi_Repository();

            var vm = new NewAgahi_ViewModel();
            vm.Country = blCountry.Select();
            vm.Ostan = blOstan.Select();
            vm.City = blCity.Select();
            vm.Mahale = blMahale.Select();
            //vm.Agahi = blAgahi.Select();

            return View(vm);
        }

        [ValidateAntiForgeryToken]
        [HttpPost]
        public ActionResult NewAgahi(Agahi agahi)
        {

            if (ModelState.IsValid == true)
            {
                Agahi_Repository blAgahi = new Agahi_Repository();

                agahi.Date = DateTime.Now.Date;
                agahi.UserId = 1048;
                agahi.GroupId = 1;


                if (blAgahi.Add(agahi) == true)
                {
                    //Success
                    return JavaScript("alert('??? ??')");

                }
                else
                {
                    //Fail
                    return JavaScript("alert('????? ?? ???')");

            }

Viewmodel Code:

using ProjectName.Models.DomainModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ProjectName.ViewModels
{
    public class NewAgahi_ViewModel // ???? ??????? ???? ?? ??? ??? ?? ?? ???
    { 

        public IEnumerable<Country> Country { get; set; }

        public IEnumerable<Ostan> Ostan { get; set; }

        public IEnumerable<City> City { get; set; }

        public IQueryable<Mahale> Mahale { get; set; }

        public ProjectName.Models.DomainModels.Agahi Agahi { get; set; }

    }
}

View Code:

@model ProjectName.ViewModels.NewAgahi_ViewModel

..... .....

@Html.DropDownList("CountryList", new SelectList(Model.Country, "id", "Name"))

 @Html.DropDownList("CityList", new SelectList(Model.City, "id", "Name"))

Country_Repository Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ProjectName.Models.DomainModels;

namespace ProjectName.Models.Repositories
{
    public class Country_Repository : IDisposable
    {
        private MyWebSiteDBEntities db = null;


        public Country_Repository()
        {
            db = new DomainModels.MyWebSiteDBEntities();
        }

        public Boolean Add(Country entity, bool autoSave = true)
        {
            try
            {
                db.Country.Add(entity);
                if (autoSave)
                    return Convert.ToBoolean(db.SaveChanges()); 
                                                                //return "True";
                else
                    return false;
            }
            catch (Exception e)
            {
                string ss = e.Message;
                //return e.Message;
                return false;
            }
        }


        public bool Update(Country entity, bool autoSave = true)
        {
            try
            {
                db.Country.Attach(entity);
                db.Entry(entity).State = System.Data.Entity.EntityState.Modified;
                if (autoSave)
                    return Convert.ToBoolean(db.SaveChanges());
                else
                    return false;
            }
            catch (Exception e)
            {
                string ss = e.Message; // ?? ?????????? ??? ???? ?????? ?????? ??? ?? ?????

                return false;
            }
        }

        public bool Delete(Country entity, bool autoSave = true)
        {
            try
            {
                db.Entry(entity).State = System.Data.Entity.EntityState.Deleted;
                if (autoSave)
                    return Convert.ToBoolean(db.SaveChanges());
                else
                    return false;
            }
            catch
            {
                return false;
            }
        }

        public bool Delete(int id, bool autoSave = true)
        {
            try
            {
                var entity = db.Country.Find(id);
                db.Entry(entity).State = System.Data.Entity.EntityState.Deleted;
                if (autoSave)
                    return Convert.ToBoolean(db.SaveChanges());
                else
                    return false;
            }
            catch
            {
                return false;
            }
        }

        public Country Find(int id)
        {
            try
            {
                return db.Country.Find(id);
            }
            catch
            {
                return null;
            }
        }


        public IQueryable<Country> Where(System.Linq.Expressions.Expression<Func<Country, bool>> predicate)
        {
            try
            {
                return db.Country.Where(predicate);
            }
            catch
            {
                return null;
            }
        }

        public IQueryable<Country> Select()
        {
            try
            {
                return db.Country.AsQueryable();
            }
            catch
            {
                return null;
            }
        }

        public IQueryable<TResult> Select<TResult>(System.Linq.Expressions.Expression<Func<Country, TResult>> selector)
        {
            try
            {
                return db.Country.Select(selector);
            }
            catch
            {
                return null;
            }
        }

        public int GetLastIdentity()
        {
            try
            {
                if (db.Country.Any())
                    return db.Country.OrderByDescending(p => p.id).First().id;
                else
                    return 0;
            }
            catch
            {
                return -1;
            }
        }

        public int Save()
        {
            try
            {
                return db.SaveChanges();
            }
            catch
            {
                return -1;
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (this.db != null)
                {
                    this.db.Dispose();
                    this.db = null;
                }
            }
        }

        ~Country_Repository()
        {
            Dispose(false);
        }
    }
}

Converting a UNIX Timestamp to Formatted Date String

The DateTime class takes a string in the constructor. If you prefix the timestamp with a @-character you create a DateTime object with the timestamp. For formating use the 'c' format ... a predefined ISO 8601 compound format.

If could use the DateTime class like this ... set the right timezone or leave it out if you want a UTC time.

$dt = new DateTime('@1333699439');
$dt->setTimezone(new DateTimeZone('America/New_York'));
echo $dt->format('c');

PHP syntax question: What does the question mark and colon mean?

It's the ternary form of the if-else operator. The above statement basically reads like this:

if ($add_review) then {
    return FALSE; //$add_review evaluated as True
} else {
    return $arg //$add_review evaluated as False
}

See here for more details on ternary op in PHP: http://www.addedbytes.com/php/ternary-conditionals/